src/color.rs
src/color.rs, line 568-625
const DISPLAY_BUFFER_CAPACITY: usize = 19;
#[derive(Copy, Clone, Default, Debug)]
struct DisplayBuffer {
buffer: [u8; DISPLAY_BUFFER_CAPACITY],
len: usize,
}
impl DisplayBuffer {
#[must_use]
#[inline(never)]
fn write_str(mut self, part: &'static str) -> Self {
for (i, b) in part.as_bytes().iter().enumerate() {
self.buffer[self.len + i] = *b;
}
self.len += part.len();
self
}
#[must_use]
#[inline(never)]
fn write_code(mut self, code: u8) -> Self {
let c1: u8 = (code / 100) % 10;
let c2: u8 = (code / 10) % 10;
let c3: u8 = code % 10;
let mut printed = false;
if c1 != 0 {
printed = true;
self.buffer[self.len] = b'0' + c1;
self.len += 1;
}
if c2 != 0 || printed {
self.buffer[self.len] = b'0' + c2;
self.len += 1;
}
// If we received a zero value we must still print a value.
self.buffer[self.len] = b'0' + c3;
self.len += 1;
self
}
#[inline]
fn as_str(&self) -> &str {
// SAFETY: Only `&str` can be written to the buffer
#[allow(unsafe_code)]
unsafe {
core::str::from_utf8_unchecked(&self.buffer[0..self.len])
}
}
#[inline]
#[cfg(feature = "std")]
fn write_to(self, write: &mut dyn std::io::Write) -> std::io::Result<()> {
write.write_all(self.as_str().as_bytes())
}
}
Single unsafe block in the crate: DisplayBuffer::as_str (lines 615-617) calls core::str::from_utf8_unchecked on self.buffer[0..self.len]. The buffer is only written by two methods: write_str (lines 579-585) which copies bytes from a &'static str parameter (already valid UTF-8), and write_code (lines 589-609) which writes ASCII digit bytes (b'0' + cN where cN < 10). Both producers yield valid UTF-8, so the unchecked cast is sound. The // SAFETY: comment on line 613 documents this invariant. The buffer is fixed-size (DISPLAY_BUFFER_CAPACITY = 19 on line 568), so the writes also stay in bounds — write_code's path emits at most 3 bytes and is gated by code: u8. Justifies uses-unsafe, unsafe-safe, unsafe-documented, unsafe-minimal.