代码之家  ›  专栏  ›  技术社区  ›  laptou

str::as_bytes和CString::as_bytes_nul之间有区别吗?

  •  1
  • laptou  · 技术社区  · 7 年前

    这样做有什么区别吗:

    name.as_bytes()
    

    而这个:

    CString::new(name)?.as_bytes_with_nul()
    

    name (即 String )在某种程度上,我可以很容易地通过网络发送它们,而且我不确定是否 CString 在这里甚至是必要的。

    2 回复  |  直到 7 年前
        1
  •  5
  •   mcarton    7 年前

    文件 as_bytes_with_nul 开始于:

    相当于 as_bytes 函数,但返回的切片包含尾随的nul终止符。

    当 是:

    返回的切片 不 包含尾随的nul终止符

    是否需要传输nul字节取决于您,这取决于您如何通过网络(TCP/UDP)发送数据?TCP上的原始二进制数据?如果是,您打算如何分离消息?JSON?等等)。

        2
  •  1
  •   Andrey Tyukin    7 年前

    只要没有 0 字符串中的UTF-8代码单元, name.as_bytes() 和 CString::new(name)?.as_bytes() 应该给你同样的字节。另外, CString .as_bytes_with_null() 只需附加一个 字节。下面是一个相当复杂的UTF-8字符串的小演示:

    use std::ffi::CString;
    
    fn main() {
        let message: String = "\nßщ\u{1F601}".to_string();
        println!("bytes_1: {:?}", message.as_bytes());
        println!("bytes_2: {:?}", CString::new(message.clone()).unwrap().as_bytes());
        println!("bytes_3: {:?}", CString::new(message.clone()).unwrap().as_bytes_with_nul());
    }
    

    结果与预期一致(您可能会认识到 10 ,它对应于ASCII字符 \n ,其编码方式与UTF-8相同):

    bytes_1: [10, 195, 159, 209, 137, 240, 159, 152, 129]
    bytes_2: [10, 195, 159, 209, 137, 240, 159, 152, 129]
    bytes_3: [10, 195, 159, 209, 137, 240, 159, 152, 129, 0]
    

    如果字符串包含 U+0000 which is a valid Unicode code point ,由单个 0个 字节输入 UTF-8 ,并且可以出现在普通字符串中。例如:

    use std::ffi::CString;
    
    fn main() {
        let message: String = "\n\u{0000}\n\u{0000}".to_string();
        println!("bytes_1: {:?}", message.as_bytes());
        println!(
            "bytes_2: {:?}",
            match CString::new(message.clone()) {
                Err(e) => format!("an error: {:?}, as expected", e),
                Ok(_) => panic!("won't happen. .as_bytes() must fail."),
            }
        );
    }
    

    会给你

    bytes_1: [10, 0, 10, 0]
    bytes_2: "an error: NulError(1, [10, 0, 10, 0]), as expected"
    

    .as_bytes() 成功了,但是 CString公司 名称。作为字节() 如果可能的话,UTF-8没有理由先把它转换成CString。

    推荐文章