buffer.rs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. #!(allow(unused))
  2. use alloc::vec::Vec;
  3. use alloc::sync::Arc;
  4. use system_error::SystemError;
  5. use crate::libs::spinlock::SpinLock;
  6. #[derive(Debug)]
  7. pub struct Buffer {
  8. metadata: Metadata,
  9. read_buffer: SpinLock<Vec<u8>>,
  10. write_buffer: SpinLock<Vec<u8>>,
  11. }
  12. impl Buffer {
  13. pub fn new() -> Arc<Self> {
  14. Arc::new(Self {
  15. metadata: Metadata::default(),
  16. read_buffer: SpinLock::new(Vec::new()),
  17. write_buffer: SpinLock::new(Vec::new()),
  18. })
  19. }
  20. pub fn is_read_buf_empty(&self) -> bool {
  21. return self.read_buffer.lock().is_empty();
  22. }
  23. pub fn is_read_buf_full(&self) -> bool {
  24. return self.metadata.buf_size - self.read_buffer.lock().len() == 0;
  25. }
  26. #[allow(unused)]
  27. pub fn is_write_buf_empty(&self) -> bool {
  28. return self.write_buffer.lock().is_empty();
  29. }
  30. #[allow(unused)]
  31. pub fn is_write_buf_full(&self) -> bool {
  32. return self.write_buffer.lock().len() >= self.metadata.buf_size;
  33. }
  34. pub fn read_read_buffer(&self, buf: &mut [u8]) -> Result<usize, SystemError> {
  35. let mut read_buffer = self.read_buffer.lock_irqsave();
  36. let len = core::cmp::min(buf.len(), read_buffer.len());
  37. buf[..len].copy_from_slice(&read_buffer[..len]);
  38. let _ = read_buffer.split_off(len);
  39. // log::debug!("recv buf {}", String::from_utf8_lossy(buf));
  40. return Ok(len);
  41. }
  42. pub fn write_read_buffer(&self, buf: &[u8]) -> Result<usize, SystemError> {
  43. let mut buffer = self.read_buffer.lock_irqsave();
  44. // log::debug!("send buf {}", String::from_utf8_lossy(buf));
  45. let len = buf.len();
  46. if self.metadata.buf_size - buffer.len() < len {
  47. return Err(SystemError::ENOBUFS);
  48. }
  49. buffer.extend_from_slice(buf);
  50. Ok(len)
  51. }
  52. #[allow(unused)]
  53. pub fn write_write_buffer(&self, buf: &[u8]) -> Result<usize, SystemError> {
  54. let mut buffer = self.write_buffer.lock_irqsave();
  55. let len = buf.len();
  56. if self.metadata.buf_size - buffer.len() < len {
  57. return Err(SystemError::ENOBUFS);
  58. }
  59. buffer.extend_from_slice(buf);
  60. Ok(len)
  61. }
  62. }
  63. #[derive(Debug)]
  64. pub struct Metadata {
  65. /// 默认的元数据缓冲区大小
  66. #[allow(dead_code)]
  67. metadata_buf_size: usize,
  68. /// 默认的缓冲区大小
  69. buf_size: usize,
  70. }
  71. impl Default for Metadata {
  72. fn default() -> Self {
  73. Self {
  74. metadata_buf_size: 1024,
  75. buf_size: 64 * 1024,
  76. }
  77. }
  78. }