#string #fixed-length #stack-allocated

no-std fstr

A stack-allocated fixed-length string type

15 releases

0.2.10 Nov 20, 2023
0.2.7 Sep 16, 2023
0.2.4 Jul 10, 2023
0.1.6 Mar 30, 2023
0.1.1 Nov 23, 2022

#230 in Encoding

Download history 1412/week @ 2024-03-13 1222/week @ 2024-03-20 1144/week @ 2024-03-27 1257/week @ 2024-04-03 1408/week @ 2024-04-10 1332/week @ 2024-04-17 1149/week @ 2024-04-24 1009/week @ 2024-05-01 1359/week @ 2024-05-08 1319/week @ 2024-05-15 1047/week @ 2024-05-22 1228/week @ 2024-05-29 1205/week @ 2024-06-05 1094/week @ 2024-06-12 1022/week @ 2024-06-19 1707/week @ 2024-06-26

5,306 downloads per month
Used in 10 crates (5 directly)

Apache-2.0

35KB
550 lines

FStr: a stack-allocated fixed-length string type

Crates.io License

This crate provides a thin wrapper for [u8; N] to handle a stack-allocated byte array as a fixed-length, String-like type through common traits such as Display, PartialEq, and Deref<Target = str>.

use fstr::FStr;

let x = FStr::try_from(b"foo")?;
println!("{}", x); // "foo"
assert_eq!(x, "foo");
assert_eq!(&x[..], "foo");
assert_eq!(&x as &str, "foo");
assert!(!x.is_empty());
assert!(x.is_ascii());

let mut y = FStr::try_from(b"bar")?;
assert_eq!(y, "bar");
y.make_ascii_uppercase();
assert_eq!(y, "BAR");

const K: FStr<8> = FStr::from_str_unwrap("constant");
assert_eq!(K, "constant");

Unlike String and arrayvec::ArrayString, this type has the same binary representation as the underlying [u8; N] and manages fixed-length strings only. The type parameter takes the exact length (in bytes) of a concrete type, and the concrete type only holds the string values of that size.

let s = "Lorem Ipsum ✨";
assert_eq!(s.len(), 15);
assert!(s.parse::<FStr<15>>().is_ok()); // just right
assert!(s.parse::<FStr<10>>().is_err()); // too small
assert!(s.parse::<FStr<20>>().is_err()); // too large
let x: FStr<10> = FStr::from_str_unwrap("helloworld");
let y: FStr<12> = FStr::from_str_unwrap("helloworld  ");

// This code does not compile because `FStr` of different lengths cannot mix.
if x != y {
    unreachable!();
}

Variable-length string operations are partially supported by utilizing a C-style NUL-terminated buffer and some helper methods.

let mut buffer = FStr::<20>::from_str_lossy("haste", b'\0');
assert_eq!(buffer, "haste\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");

let c_str = buffer.slice_to_terminator('\0');
assert_eq!(c_str, "haste");

use core::fmt::Write as _;
write!(buffer.writer_at(c_str.len()), " makes waste")?;
assert_eq!(buffer.slice_to_terminator('\0'), "haste makes waste");

Crate features

  • std (optional; enabled by default) enables the integration with std. Disable default features to operate this crate under no_std environments.
  • serde (optional) enables the serialization and deserialization of FStrthrough serde.

License

Licensed under the Apache License, Version 2.0.

See also

Dependencies

~170KB