|
1 | 1 | use super::chars::{Char16, Char8, NUL_16, NUL_8};
|
| 2 | +#[cfg(feature = "exts")] |
| 3 | +use crate::alloc_api::string::String; |
2 | 4 | use core::convert::TryInto;
|
3 | 5 | use core::fmt;
|
4 | 6 | use core::iter::Iterator;
|
@@ -162,6 +164,40 @@ impl CStr16 {
|
162 | 164 | pos: 0,
|
163 | 165 | }
|
164 | 166 | }
|
| 167 | + |
| 168 | + /// Writes each [`Char16`] as a [´char´] (4 bytes long in Rust language) into the buffer. |
| 169 | + /// It is up the the implementer of [`core::fmt::Write`] to convert the char to a string |
| 170 | + /// with proper encoding/charset. For example, in the case of [`core::alloc::string::String`] |
| 171 | + /// all Rust chars (UTF-32) get converted to UTF-8. |
| 172 | + /// |
| 173 | + /// ## Example |
| 174 | + /// |
| 175 | + /// ```ignore |
| 176 | + /// let firmware_vendor_c16_str: CStr16 = ...; |
| 177 | + /// // crate "arrayvec" uses stack-allocated arrays for Strings => no heap allocations |
| 178 | + /// let mut buf = arrayvec::ArrayString::<128>::new(); |
| 179 | + /// firmware_vendor_c16_str.as_str_in_buf(&mut buf); |
| 180 | + /// log::info!("as rust str: {}", buf.as_str()); |
| 181 | + /// ``` |
| 182 | + pub fn as_str_in_buf(&self, buf: &mut dyn core::fmt::Write) -> core::fmt::Result { |
| 183 | + for c16 in self.iter() { |
| 184 | + buf.write_char(char::from(*c16))?; |
| 185 | + } |
| 186 | + Ok(()) |
| 187 | + } |
| 188 | + |
| 189 | + /// Transforms the C16Str to a regular Rust String. |
| 190 | + /// **WARNING** This will require **heap allocation**, i.e. you need an global allocator. |
| 191 | + /// If the UEFI boot services are exited, your OS/Kernel needs to provide another allocation |
| 192 | + /// mechanism! |
| 193 | + #[cfg(feature = "exts")] |
| 194 | + pub fn as_string(&self) -> String { |
| 195 | + let mut buf = String::with_capacity(self.0.len() * 2); |
| 196 | + for c16 in self.iter() { |
| 197 | + buf.push(char::from(*c16)); |
| 198 | + } |
| 199 | + buf |
| 200 | + } |
165 | 201 | }
|
166 | 202 |
|
167 | 203 | /// An iterator over `CStr16`.
|
|
0 commit comments