#![cfg_attr(all(not(test), not(doc)), no_std)]
#![cfg_attr(
not(test),
deny(
clippy::indexing_slicing,
clippy::unwrap_used,
clippy::expect_used,
clippy::panic,
clippy::exhaustive_structs,
clippy::exhaustive_enums,
missing_debug_implementations,
)
)]
extern crate alloc;
mod impls;
mod ops;
use alloc::borrow::Cow;
use alloc::string::String;
use alloc::vec::Vec;
use core::fmt;
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
#[non_exhaustive]
pub struct LengthHint(pub usize, pub Option<usize>);
impl LengthHint {
pub fn undefined() -> Self {
Self(0, None)
}
pub fn exact(n: usize) -> Self {
Self(n, Some(n))
}
pub fn at_least(n: usize) -> Self {
Self(n, None)
}
pub fn at_most(n: usize) -> Self {
Self(0, Some(n))
}
pub fn between(n: usize, m: usize) -> Self {
Self(Ord::min(n, m), Some(Ord::max(n, m)))
}
pub fn capacity(&self) -> usize {
self.1.unwrap_or(self.0)
}
pub fn is_zero(&self) -> bool {
self.1 == Some(0)
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
#[allow(clippy::exhaustive_structs)] pub struct Part {
pub category: &'static str,
pub value: &'static str,
}
pub trait PartsWrite: fmt::Write {
type SubPartsWrite: PartsWrite + ?Sized;
fn with_part(
&mut self,
part: Part,
f: impl FnMut(&mut Self::SubPartsWrite) -> fmt::Result,
) -> fmt::Result;
}
pub trait Writeable {
fn write_to<W: fmt::Write + ?Sized>(&self, sink: &mut W) -> fmt::Result {
struct CoreWriteAsPartsWrite<W: fmt::Write + ?Sized>(W);
impl<W: fmt::Write + ?Sized> fmt::Write for CoreWriteAsPartsWrite<W> {
fn write_str(&mut self, s: &str) -> fmt::Result {
self.0.write_str(s)
}
fn write_char(&mut self, c: char) -> fmt::Result {
self.0.write_char(c)
}
}
impl<W: fmt::Write + ?Sized> PartsWrite for CoreWriteAsPartsWrite<W> {
type SubPartsWrite = CoreWriteAsPartsWrite<W>;
fn with_part(
&mut self,
_part: Part,
mut f: impl FnMut(&mut Self::SubPartsWrite) -> fmt::Result,
) -> fmt::Result {
f(self)
}
}
self.write_to_parts(&mut CoreWriteAsPartsWrite(sink))
}
fn write_to_parts<S: PartsWrite + ?Sized>(&self, sink: &mut S) -> fmt::Result {
self.write_to(sink)
}
fn writeable_length_hint(&self) -> LengthHint {
LengthHint::undefined()
}
fn write_to_string(&self) -> Cow<str> {
let hint = self.writeable_length_hint();
if hint.is_zero() {
return Cow::Borrowed("");
}
let mut output = String::with_capacity(hint.capacity());
let _ = self.write_to(&mut output);
Cow::Owned(output)
}
}
#[macro_export]
macro_rules! impl_display_with_writeable {
($type:ty) => {
impl core::fmt::Display for $type {
#[inline]
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
$crate::Writeable::write_to(&self, f)
}
}
};
}
#[macro_export]
macro_rules! assert_writeable_eq {
($actual_writeable:expr, $expected_str:expr $(,)?) => {
$crate::assert_writeable_eq!($actual_writeable, $expected_str, "");
};
($actual_writeable:expr, $expected_str:expr, $($arg:tt)+) => {{
let actual_writeable = &$actual_writeable;
let (actual_str, _) = $crate::writeable_to_parts_for_test(actual_writeable).unwrap();
assert_eq!(actual_str, $expected_str, $($arg)*);
assert_eq!(actual_str, $crate::Writeable::write_to_string(actual_writeable), $($arg)+);
let length_hint = $crate::Writeable::writeable_length_hint(actual_writeable);
assert!(
length_hint.0 <= actual_str.len(),
"hint lower bound {} larger than actual length {}: {}",
length_hint.0, actual_str.len(), format!($($arg)*),
);
if let Some(upper) = length_hint.1 {
assert!(
actual_str.len() <= upper,
"hint upper bound {} smaller than actual length {}: {}",
length_hint.0, actual_str.len(), format!($($arg)*),
);
}
assert_eq!(actual_writeable.to_string(), $expected_str);
}};
}
#[macro_export]
macro_rules! assert_writeable_parts_eq {
($actual_writeable:expr, $expected_str:expr, $expected_parts:expr $(,)?) => {
$crate::assert_writeable_parts_eq!($actual_writeable, $expected_str, $expected_parts, "");
};
($actual_writeable:expr, $expected_str:expr, $expected_parts:expr, $($arg:tt)+) => {{
let actual_writeable = &$actual_writeable;
let (actual_str, actual_parts) = $crate::writeable_to_parts_for_test(actual_writeable).unwrap();
assert_eq!(actual_str, $expected_str, $($arg)+);
assert_eq!(actual_str, $crate::Writeable::write_to_string(actual_writeable), $($arg)+);
assert_eq!(actual_parts, $expected_parts, $($arg)+);
let length_hint = $crate::Writeable::writeable_length_hint(actual_writeable);
assert!(length_hint.0 <= actual_str.len(), $($arg)+);
if let Some(upper) = length_hint.1 {
assert!(actual_str.len() <= upper, $($arg)+);
}
assert_eq!(actual_writeable.to_string(), $expected_str);
}};
}
#[doc(hidden)]
#[allow(clippy::type_complexity)]
pub fn writeable_to_parts_for_test<W: Writeable>(
writeable: &W,
) -> Result<(String, Vec<(usize, usize, Part)>), fmt::Error> {
struct State {
string: alloc::string::String,
parts: Vec<(usize, usize, Part)>,
}
impl fmt::Write for State {
fn write_str(&mut self, s: &str) -> fmt::Result {
self.string.write_str(s)
}
fn write_char(&mut self, c: char) -> fmt::Result {
self.string.write_char(c)
}
}
impl PartsWrite for State {
type SubPartsWrite = Self;
fn with_part(
&mut self,
part: Part,
mut f: impl FnMut(&mut Self::SubPartsWrite) -> fmt::Result,
) -> fmt::Result {
let start = self.string.len();
f(self)?;
let end = self.string.len();
if start < end {
self.parts.push((start, end, part));
}
Ok(())
}
}
let mut state = State {
string: alloc::string::String::new(),
parts: Vec::new(),
};
writeable.write_to_parts(&mut state)?;
state
.parts
.sort_unstable_by_key(|(begin, end, _)| (*begin, end.wrapping_neg()));
Ok((state.string, state.parts))
}