#string #byte-string #stack-allocated #generic #traits #wrapper #fixed-length

string-wrapper

可能堆分配的具有泛型字节存储的字符串

9 个版本

使用旧的 Rust 2015

0.3.0 2017年5月30日
0.2.0 2017年2月16日
0.1.7 2017年1月19日
0.1.5 2015年11月5日
0.1.3 2015年10月30日

1765数据结构

Download history 23/week @ 2024-03-09 2/week @ 2024-03-16 40/week @ 2024-03-30 1/week @ 2024-04-06 1/week @ 2024-05-25

每月321 次下载

MIT/Apache

24KB
457

Build Status Latest Version

string_wrapper

string_wrapper 是一个 crate,它提供了一个 StringWrapper,这是一个通常是*堆分配的 UTF-8 字符串类型。功能

  • 基于数组的 StringWrappers 可以完全存储在堆栈上
  • 可以实现 Copy 特性,与标准字符串不同
  • 实现了 Serde 序列化和反序列化特性,以与 String 完全相同的方式操作

文档

文档位于 http://docs.rs/string-wrapper

示例

首先,将以下内容添加到您的 Cargo.toml

[dependencies]
string-wrapper = "0.2"

如果您想使用 Serde 支持,您必须启用 use_serde 功能并使用 Rust 1.15 或更高版本。

[dependencies]
string-wrapper = {version = "0.1.6", features = ["use_serde"]}

请确保在您的 "crate root" 模块中(通常是 lib.rsmain.rs)使用 extern crate

extern crate string_wrapper;

最后,实际使用 StringWrapper 类型

use string_wrapper::StringWrapper;

fn foo() {
  // `from_str` may panic; use `from_str_safe` if you're using arbitrary input
  let s: StringWrapper<[u8; 32]> = StringWrapper::from_str("foo");

  // a StringWrapper can be converted back to a String with `to_string`:
  println!("{}", s.to_string());
  // However, it also supports the Display trait directly:
  println!("{}", s);
}

请注意,类型参数必须是 u8 的组合,通常是*作为一个 [u8; N] 数组。数组的大小可以在 Buffer 特性文档的 Implementors 部分找到: https://docs.rs/string-wrapper/*/string_wrapper/trait.Buffer.html.

StringWrapper 还支持许多其他特性。请参阅 http://docs.rs/string-wrapper/.

"通常*"? 堆分配的 StringWrappers

Vec<u8> 也可以作为后备缓冲区而不是 [u8; N] 使用。使用 Vec<u8> 意味着您的字符串将位于堆上。

何时有用?

如果您有大量符合固定长度的短字符串,并且处理这些短字符串的指针开销对您的程序有害,这可能会很有用。如果您不确定,您可能应该只使用 String,因为它更灵活、更方便。

这是否是“小字符串优化”(SSO)?

请注意,这并不是通常所说的“SSO String”,它是一种动态大小的字符串,如果是小的,则直接存储在栈上(如果是大的,则存储在堆上)。这样的字符串无法实现 Copy 特性。

致谢

感谢 @SimonSapin,此代码的原始作者。

还有

许可证

string-wrapper 在 MIT 许可证和 Apache 2.0 许可证下双许可。所有贡献都必须在这两个许可证的条款下进行。

依赖关系

约 175KB