1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
// Copyright (c) 2024, BlockProject 3D
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of BlockProject 3D nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//! Formatting utilities.
use std::mem::MaybeUninit;
/// Fixed length string buffer.
#[derive(Clone, Debug)]
pub struct FixedBufStr<const N: usize> {
len: usize,
buffer: [MaybeUninit<u8>; N],
}
impl<const N: usize> Default for FixedBufStr<N> {
fn default() -> Self {
Self::new()
}
}
impl<const N: usize> FixedBufStr<N> {
/// Creates a new fixed length string buffer.
pub fn new() -> FixedBufStr<N> {
FixedBufStr {
buffer: unsafe { MaybeUninit::uninit().assume_init() },
len: 0,
}
}
/// Extracts the string from this buffer.
//type inference works so why should the code look awfully more complex?
#[allow(clippy::missing_transmute_annotations)]
pub fn str(&self) -> &str {
unsafe { std::str::from_utf8_unchecked(std::mem::transmute(&self.buffer[..self.len as _])) }
}
/// Constructs this buffer from an existing string.
//type inference works so why should the code look awfully more complex?
#[allow(clippy::missing_transmute_annotations)]
//I believe this is a false-positive, FromStr returns a Result not Self.
#[allow(clippy::should_implement_trait)]
pub fn from_str(value: &str) -> Self {
let mut buffer = FixedBufStr::new();
let len = std::cmp::min(value.len(), N);
unsafe {
std::ptr::copy_nonoverlapping(
value.as_ptr(),
std::mem::transmute(buffer.buffer.as_mut_ptr()),
len,
);
}
buffer.len = len as _;
buffer
}
/// Appends a raw byte buffer at the end of this string buffer.
///
/// Returns the number of bytes written.
///
/// # Arguments
///
/// * `buf`: the raw byte buffer to append.
///
/// returns: usize
///
/// # Safety
///
/// * [FixedBufStr](FixedBufStr) contains only valid UTF-8 strings so buf must contain only valid UTF-8
/// bytes.
/// * If buf contains invalid UTF-8 bytes, further operations on the log message buffer may
/// result in UB.
//type inference works so why should the code look awfully more complex?
#[allow(clippy::missing_transmute_annotations)]
pub unsafe fn write(&mut self, buf: &[u8]) -> usize {
let len = std::cmp::min(buf.len(), N - self.len);
unsafe {
std::ptr::copy_nonoverlapping(
buf.as_ptr(),
std::mem::transmute(self.buffer.as_mut_ptr().add(self.len)),
len,
);
}
self.len += len;
len
}
}
impl<const N: usize> std::fmt::Write for FixedBufStr<N> {
fn write_str(&mut self, value: &str) -> std::fmt::Result {
unsafe { self.write(value.as_bytes()) };
Ok(())
}
}
/// An io [Write](std::io::Write) to fmt [Write](std::fmt::Write).
///
/// This may look like a hack but is a requirement for pathological APIs such as presented by the
/// time crate.
pub struct IoToFmt<W: std::fmt::Write>(W);
impl<W: std::fmt::Write> IoToFmt<W> {
/// Create a new [IoToFmt](IoToFmt) wrapper.
///
/// # Arguments
///
/// * `w`: target fmt [Write](std::fmt::Write) to write into.
///
/// returns: IoToFmt<W>
pub fn new(w: W) -> Self {
Self(w)
}
/// Extracts the underlying [Write](std::fmt::Write).
pub fn into_inner(self) -> W {
self.0
}
}
impl<W: std::fmt::Write> std::io::Write for IoToFmt<W> {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
let str = std::str::from_utf8(buf)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?;
self.0
.write_str(str)
.map(|_| str.len())
.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
#[cfg(test)]
mod tests {
use crate::format::FixedBufStr;
use std::fmt::Write;
#[test]
fn basic() {
let mut msg: FixedBufStr<64> = FixedBufStr::new();
let _ = write!(msg, "this");
let _ = write!(msg, " is");
let _ = write!(msg, " a");
let _ = write!(msg, " test");
assert_eq!(msg.str(), "this is a test");
}
}