Skip to content

Commit cf277ca

Browse files
committed
Add C-string version of the write_to
1 parent 56d70af commit cf277ca

File tree

1 file changed

+35
-5
lines changed

1 file changed

+35
-5
lines changed

vesper/src/write_to.rs

+35-5
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,19 @@ impl<'a> WriteTo<'a> {
1919
WriteTo { buffer, used: 0 }
2020
}
2121

22-
pub fn as_str(self) -> Option<&'a str> {
22+
pub fn into_str(self) -> Option<&'a str> {
2323
if self.used <= self.buffer.len() {
2424
// only successful concats of str - must be a valid str.
25-
use core::str::from_utf8_unchecked;
26-
Some(unsafe { from_utf8_unchecked(&self.buffer[..self.used]) })
25+
Some(unsafe { core::str::from_utf8_unchecked(&self.buffer[..self.used]) })
26+
} else {
27+
None
28+
}
29+
}
30+
31+
pub fn into_cstr(self) -> Option<&'a str> {
32+
if self.used < self.buffer.len() {
33+
self.buffer[self.used] = 0; // Terminate the string
34+
Some(unsafe { core::str::from_utf8_unchecked(&self.buffer[..=self.used]) })
2735
} else {
2836
None
2937
}
@@ -48,24 +56,46 @@ impl<'a> fmt::Write for WriteTo<'a> {
4856
}
4957
}
5058

59+
#[inline]
5160
pub fn show<'a>(buffer: &'a mut [u8], args: fmt::Arguments) -> Result<&'a str, fmt::Error> {
5261
let mut w = WriteTo::new(buffer);
5362
fmt::write(&mut w, args)?;
54-
w.as_str().ok_or(fmt::Error)
63+
w.into_str().ok_or(fmt::Error)
64+
}
65+
66+
// Return a zero-terminated str
67+
#[inline] // Crazy bug - result of this call disappears if it's not inlined
68+
pub fn c_show<'a>(buffer: &'a mut [u8], args: fmt::Arguments) -> Result<&'a str, fmt::Error> {
69+
let mut w = WriteTo::new(buffer);
70+
fmt::write(&mut w, args)?;
71+
w.into_cstr().ok_or(fmt::Error)
5572
}
5673

5774
#[cfg(test)]
5875
mod tests {
5976
use super::*;
6077

6178
#[test_case]
62-
pub fn write_to_functions() {
79+
pub fn write_to_works() {
6380
let mut buf = [0u8; 64];
6481
let s: &str = show(
6582
&mut buf,
6683
format_args!("write some stuff {:?}: {}", "foo", 42),
6784
)
6885
.unwrap();
6986
assert_eq!(s, "write some stuff \"foo\": 42");
87+
assert_eq!(s.as_ptr(), buf.as_ptr());
88+
}
89+
90+
#[test_case]
91+
pub fn zero_terminated_write_to_works() {
92+
let mut buf = [0u8; 64];
93+
let s: &str = c_show(
94+
&mut buf,
95+
format_args!("write some stuff {:?}: {}", "foo", 42),
96+
)
97+
.unwrap();
98+
assert_eq!(s, "write some stuff \"foo\": 42\0");
99+
assert_eq!(s.as_ptr(), buf.as_ptr());
70100
}
71101
}

0 commit comments

Comments
 (0)