pub struct StrConstrue<const N: usize>(/* private fields */);
Expand description
Alternative to String
for const
This is just a Construe<u8, N>
with a few additional methods, see the Construe
documentation for a little more info.
use construe::{StrConstrue, construe};
const fn hello_world<const N: usize>() -> StrConstrue<N> {
let strc = StrConstrue::new();
strc.push_str("Hello")
.push_str(" ")
.push_str("World")
.push_str("!")
}
construe!(const HELLO_WORLD: &str = hello_world());
// or manually:
const HELLO_WORLD_2: &str = {
const LEN: usize = hello_world().needs_len();
const ARRAY: [u8; LEN] = hello_world().store_bytes();
StrConstrue::borrow_str(&ARRAY)
};
assert_eq!(HELLO_WORLD, "Hello World!");
assert_eq!(HELLO_WORLD, HELLO_WORLD_2);
Implementations§
Source§impl<const N: usize> StrConstrue<N>
impl<const N: usize> StrConstrue<N>
Sourcepub const fn new() -> Self
pub const fn new() -> Self
Create a StrConstrue
instance (with or without the buffer)
Sourcepub const fn len(&self) -> usize
pub const fn len(&self) -> usize
Amount of bytes stored (or supposed to be stored) in the buffer
Sourcepub const fn is_empty(&self) -> bool
pub const fn is_empty(&self) -> bool
Whether there are no bytes (supposed to be) stored in the buffer
Sourcepub const fn push_str(self, s: &str) -> Self
pub const fn push_str(self, s: &str) -> Self
Push a &str
into the buffer
Note that this takes self
by-value: since &mut
references aren’t yet stable in const
contexts, we have to keep reassigning the output of the function to the variable.
// `mut` because we reassign to it
let mut sc = construe::StrConstrue::<0>::new();
sc = sc.push_str("Test");
// method chaining can save space
sc = sc.push_str("123").push_str(" ").push_str(":^)");
Sourcepub const fn store_bytes(self) -> [u8; N]
pub const fn store_bytes(self) -> [u8; N]
Return the assembled byte buffer, consuming the struct
Panics if the buffer is not filled or if this is a zero-length buffer that was supposed to store bytes.
Use StrConstrue::borrow_str
to obtain a &str
from the buffer.
Source§impl StrConstrue<0>
impl StrConstrue<0>
Sourcepub const fn needs_len(&self) -> usize
pub const fn needs_len(&self) -> usize
Amount of bytes needed to store the string
This is the same as StrConstrue::len
, but it exists as a separate method that’s only implemented for N = 0
so that the const N: usize
generic parameter on functions returning this can be inferred as 0
for the first run.
Sourcepub const fn borrow_str(byte_slice: &[u8]) -> &str
pub const fn borrow_str(byte_slice: &[u8]) -> &str
Borrow a &str
from a byte slice
See the example at the top for how to use this, the buffer returned by StrConstrue::store_bytes
needs to be stored in a constant to be able to borrow a &'static str
from it.
This just calls core::str::from_utf8
and panics if the byte slice contains invalid UTF-8.