pub type String<const N: usize, LenT = usize> = StringInner<LenT, OwnedStorage<N>>;
Expand description
A fixed capacity String
.
Aliased Type§
pub struct String<const N: usize, LenT = usize> { /* private fields */ }
Implementations§
Source§impl<LenT: LenType, const N: usize> String<N, LenT>
impl<LenT: LenType, const N: usize> String<N, LenT>
Sourcepub const fn new() -> Self
pub const fn new() -> Self
Constructs a new, empty String
with a fixed capacity of N
bytes.
§Examples
Basic usage:
use heapless::String;
// allocate the string on the stack
let mut s: String<4> = String::new();
// allocate the string in a static variable
static mut S: String<4> = String::new();
Sourcepub fn from_utf16(v: &[u16]) -> Result<Self, FromUtf16Error>
pub fn from_utf16(v: &[u16]) -> Result<Self, FromUtf16Error>
Decodes a UTF-16–encoded slice v
into a String
, returning Err
if v
contains any invalid data.
§Examples
Basic usage:
use heapless::String;
// 𝄞music
let v = &[0xD834, 0xDD1E, 0x006d, 0x0075, 0x0073, 0x0069, 0x0063];
let s: String<10> = String::from_utf16(v).unwrap();
assert_eq!(s, "𝄞music");
// 𝄞mu<invalid>ic
let v = &[0xD834, 0xDD1E, 0x006d, 0x0075, 0xD800, 0x0069, 0x0063];
assert!(String::<10>::from_utf16(v).is_err());
Sourcepub fn from_utf8(vec: Vec<u8, N, LenT>) -> Result<Self, Utf8Error>
pub fn from_utf8(vec: Vec<u8, N, LenT>) -> Result<Self, Utf8Error>
Convert UTF-8 bytes into a String
.
§Examples
Basic usage:
use heapless::{String, Vec};
let mut sparkle_heart = Vec::<u8, 4>::new();
sparkle_heart.extend_from_slice(&[240, 159, 146, 150]);
let sparkle_heart: String<4> = String::from_utf8(sparkle_heart)?;
assert_eq!("💖", sparkle_heart);
Invalid UTF-8:
use core::str::Utf8Error;
use heapless::{String, Vec};
let mut vec = Vec::<u8, 4>::new();
vec.extend_from_slice(&[0, 159, 146, 150]);
let e: Utf8Error = String::from_utf8(vec).unwrap_err();
assert_eq!(e.valid_up_to(), 1);
Sourcepub unsafe fn from_utf8_unchecked(vec: Vec<u8, N, LenT>) -> Self
pub unsafe fn from_utf8_unchecked(vec: Vec<u8, N, LenT>) -> Self
Convert UTF-8 bytes into a String
, without checking that the string
contains valid UTF-8.
§Safety
The bytes passed in must be valid UTF-8.
§Examples
Basic usage:
use heapless::{String, Vec};
let mut sparkle_heart = Vec::<u8, 4>::new();
sparkle_heart.extend_from_slice(&[240, 159, 146, 150]);
// Safety: `sparkle_heart` Vec is known to contain valid UTF-8
let sparkle_heart: String<4> = unsafe { String::from_utf8_unchecked(sparkle_heart) };
assert_eq!("💖", sparkle_heart);
Sourcepub fn into_bytes(self) -> Vec<u8, N, LenT>
pub fn into_bytes(self) -> Vec<u8, N, LenT>
Converts a String
into a byte vector.
This consumes the String
, so we do not need to copy its contents.
§Examples
Basic usage:
use heapless::String;
let s: String<4> = String::try_from("ab")?;
let b = s.into_bytes();
assert!(b.len() == 2);
assert_eq!(&[b'a', b'b'], &b[..]);