【问题标题】:How to trim a BytesMut from bytes crate?如何从字节箱中修剪 BytesMut?
【发布时间】:2023-02-24 02:00:43
【问题描述】:

假设我有一个BytesMut,我希望能够让它成为trim_bytes

let some_bytes = BytesMut::from("  hello world  ");
let trim_bytes = some_bytes.some_trim_method();
// trim_bytes = BytesMut::From("hello world");   

some_trim_method() 是我一直在寻找的东西,但是箱子里没有这样的方法。

【问题讨论】:

  • trim_ascii方法,但还是不稳定,需要nightly。 Here 如何使用trim_ascii 的例子。如果你想让它稳定运行,我认为你必须先将 BytesMut 转换为 String 然后调用 trim

标签: rust rust-tokio


【解决方案1】:

您还可以为 bytes 创建自己版本的 trim 函数

fn trim_bytes<'a>(s: &'a bytes::BytesMut) -> &'a [u8] {
  let (mut i, mut j) = (0, s.len() - 1);
  loop {
      if (s[i] != 32 && s[j] != 32) || (i > j) {
          break;
      }

      if s[i] == 32 {
          i += 1;
      }

      if s[j] == 32 {
          j -= 1;
      }
  }
  return &s[i..j+1];
}

fn main() {
    let result = trim_bytes(&some_bytes);
    println!("{:?}", result);
    assert_eq!(b"hello world", result);
}

或者在 byte 类型上实现 trim 方法

trait TrimBytes {
    fn trim(&self) -> &Self;
}

impl TrimBytes for [u8] {
    fn trim(&self) -> &[u8] {
        fn is_whitespace(c: &u8) -> bool {
            *c == b'	' || *c == b' '
        }

        fn is_not_whitespace(c: &u8) -> bool {
            !is_whitespace(c)
        }

        if let Some(first) = self.iter().position(is_not_whitespace) {
            if let Some(last) = self.iter().rposition(is_not_whitespace) {
                &self[first..last + 1]
            } else {
                unreachable!();
            }
        } else {
            &[]
        }
    }
}

fn main() {
    let result = some_bytes.trim();
    println!("{:?}", result);
    assert_eq!(b"hello world", result);
}

【讨论】:

    猜你喜欢
    • 2010-12-27
    • 2011-11-22
    • 1970-01-01
    • 1970-01-01
    • 2010-09-16
    • 2010-10-20
    • 1970-01-01
    • 2017-04-07
    • 1970-01-01
    相关资源
    最近更新 更多