loopback.rs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. use core::mem::swap;
  2. use core::cell::RefCell;
  3. #[cfg(feature = "std")]
  4. use std::rc::Rc;
  5. #[cfg(feature = "alloc")]
  6. use alloc::rc::Rc;
  7. #[cfg(feature = "std")]
  8. use std::vec::Vec;
  9. #[cfg(feature = "std")]
  10. use std::collections::VecDeque;
  11. #[cfg(feature = "alloc")]
  12. use alloc::{Vec, VecDeque};
  13. use {Error, Result};
  14. use super::{Device, DeviceLimits};
  15. /// A loopback device.
  16. #[derive(Debug)]
  17. pub struct Loopback(Rc<RefCell<VecDeque<Vec<u8>>>>);
  18. impl Loopback {
  19. /// Creates a loopback device.
  20. ///
  21. /// Every packet transmitted through this device will be received through it
  22. /// in FIFO order.
  23. pub fn new() -> Loopback {
  24. Loopback(Rc::new(RefCell::new(VecDeque::new())))
  25. }
  26. }
  27. impl Device for Loopback {
  28. type RxBuffer = Vec<u8>;
  29. type TxBuffer = TxBuffer;
  30. fn limits(&self) -> DeviceLimits {
  31. DeviceLimits {
  32. max_transmission_unit: 65535,
  33. ..DeviceLimits::default()
  34. }
  35. }
  36. fn receive(&mut self, _timestamp: u64) -> Result<Self::RxBuffer> {
  37. match self.0.borrow_mut().pop_front() {
  38. Some(packet) => Ok(packet),
  39. None => Err(Error::Exhausted)
  40. }
  41. }
  42. fn transmit(&mut self, _timestamp: u64, length: usize) -> Result<Self::TxBuffer> {
  43. let mut buffer = Vec::new();
  44. buffer.resize(length, 0);
  45. Ok(TxBuffer {
  46. queue: self.0.clone(),
  47. buffer: buffer
  48. })
  49. }
  50. }
  51. #[doc(hidden)]
  52. pub struct TxBuffer {
  53. queue: Rc<RefCell<VecDeque<Vec<u8>>>>,
  54. buffer: Vec<u8>
  55. }
  56. impl AsRef<[u8]> for TxBuffer {
  57. fn as_ref(&self) -> &[u8] { self.buffer.as_ref() }
  58. }
  59. impl AsMut<[u8]> for TxBuffer {
  60. fn as_mut(&mut self) -> &mut [u8] { self.buffer.as_mut() }
  61. }
  62. impl Drop for TxBuffer {
  63. fn drop(&mut self) {
  64. let mut buffer = Vec::new();
  65. swap(&mut buffer, &mut self.buffer);
  66. self.queue.borrow_mut().push_back(buffer)
  67. }
  68. }