diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-17 12:18:32 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-17 12:18:32 +0000 |
commit | 4547b622d8d29df964fa2914213088b148c498fc (patch) | |
tree | 9fc6b25f3c3add6b745be9a2400a6e96140046e9 /vendor/writeable/src | |
parent | Releasing progress-linux version 1.66.0+dfsg1-1~progress7.99u1. (diff) | |
download | rustc-4547b622d8d29df964fa2914213088b148c498fc.tar.xz rustc-4547b622d8d29df964fa2914213088b148c498fc.zip |
Merging upstream version 1.67.1+dfsg1.
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'vendor/writeable/src')
-rw-r--r-- | vendor/writeable/src/impls.rs | 213 | ||||
-rw-r--r-- | vendor/writeable/src/lib.rs | 390 | ||||
-rw-r--r-- | vendor/writeable/src/ops.rs | 291 |
3 files changed, 894 insertions, 0 deletions
diff --git a/vendor/writeable/src/impls.rs b/vendor/writeable/src/impls.rs new file mode 100644 index 000000000..649ede4d5 --- /dev/null +++ b/vendor/writeable/src/impls.rs @@ -0,0 +1,213 @@ +// This file is part of ICU4X. For terms of use, please see the file +// called LICENSE at the top level of the ICU4X source tree +// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ). + +use crate::*; +use alloc::borrow::Cow; +use core::fmt; + +macro_rules! impl_write_num { + ($u:ty, $i:ty, $test:ident, $log10:ident) => { + impl $crate::Writeable for $u { + fn write_to<W: core::fmt::Write + ?Sized>(&self, sink: &mut W) -> core::fmt::Result { + let mut buf = [b'0'; $log10(<$u>::MAX) as usize + 1]; + let mut n = *self; + let mut i = buf.len(); + #[allow(clippy::indexing_slicing)] // n < 10^i + while n != 0 { + i -= 1; + buf[i] = b'0' + (n % 10) as u8; + n /= 10; + } + if i == buf.len() { + debug_assert_eq!(*self, 0); + i -= 1; + } + #[allow(clippy::indexing_slicing)] // buf is ASCII + let s = unsafe { core::str::from_utf8_unchecked(&buf[i..]) }; + sink.write_str(s) + } + + fn writeable_length_hint(&self) -> $crate::LengthHint { + $crate::LengthHint::exact(if *self == 0 { + 1 + } else { + $log10(*self) as usize + 1 + }) + } + } + + // TODO: use the library functions once stabilized. + // https://github.com/unicode-org/icu4x/issues/1428 + #[inline] + const fn $log10(s: $u) -> u32 { + let b = (<$u>::BITS - 1) - s.leading_zeros(); + // s ∈ [2ᵇ, 2ᵇ⁺¹-1] => ⌊log₁₀(s)⌋ ∈ [⌊log₁₀(2ᵇ)⌋, ⌊log₁₀(2ᵇ⁺¹-1)⌋] + // <=> ⌊log₁₀(s)⌋ ∈ [⌊log₁₀(2ᵇ)⌋, ⌊log₁₀(2ᵇ⁺¹)⌋] + // <=> ⌊log₁₀(s)⌋ ∈ [⌊b log₁₀(2)⌋, ⌊(b+1) log₁₀(2)⌋] + // The second line holds because there is no integer in + // [log₁₀(2ᶜ-1), log₁₀(2ᶜ)], if there were, there'd be some 10ⁿ in + // [2ᶜ-1, 2ᶜ], but it can't be 2ᶜ-1 due to parity nor 2ᶜ due to prime + // factors. + + const M: u32 = (core::f64::consts::LOG10_2 * (1 << 26) as f64) as u32; + let low = (b * M) >> 26; + let high = ((b + 1) * M) >> 26; + + // If the bounds aren't tight (e.g. 87 ∈ [64, 127] ⟹ ⌊log₁₀(87)⌋ ∈ [1,2]), + // compare to 10ʰ (100). This shouldn't happen too often as there are more + // powers of 2 than 10 (it happens for 14% of u32s). + if high == low { + low + } else if s < (10 as $u).pow(high) { + low + } else { + high + } + } + + impl $crate::Writeable for $i { + fn write_to<W: core::fmt::Write + ?Sized>(&self, sink: &mut W) -> core::fmt::Result { + if self.is_negative() { + sink.write_str("-")?; + } + self.unsigned_abs().write_to(sink) + } + + fn writeable_length_hint(&self) -> $crate::LengthHint { + $crate::LengthHint::exact(if self.is_negative() { 1 } else { 0 }) + + self.unsigned_abs().writeable_length_hint() + } + } + + #[test] + fn $test() { + use $crate::assert_writeable_eq; + assert_writeable_eq!(&(0 as $u), "0"); + assert_writeable_eq!(&(0 as $u), "0"); + assert_writeable_eq!(&(-0 as $i), "0"); + assert_writeable_eq!(&(1 as $u), "1"); + assert_writeable_eq!(&(1 as $i), "1"); + assert_writeable_eq!(&(-1 as $i), "-1"); + assert_writeable_eq!(&(10 as $u), "10"); + assert_writeable_eq!(&(10 as $i), "10"); + assert_writeable_eq!(&(-10 as $i), "-10"); + assert_writeable_eq!(&(99 as $u), "99"); + assert_writeable_eq!(&(99 as $i), "99"); + assert_writeable_eq!(&(-99 as $i), "-99"); + assert_writeable_eq!(&(100 as $u), "100"); + assert_writeable_eq!(&(-100 as $i), "-100"); + assert_writeable_eq!(&<$u>::MAX, <$u>::MAX.to_string()); + assert_writeable_eq!(&<$i>::MAX, <$i>::MAX.to_string()); + assert_writeable_eq!(&<$i>::MIN, <$i>::MIN.to_string()); + + use rand::{rngs::SmallRng, Rng, SeedableRng}; + let mut rng = SmallRng::seed_from_u64(4); // chosen by fair dice roll. + // guaranteed to be random. + for _ in 0..1000 { + let rand = rng.gen::<$u>(); + assert_writeable_eq!(rand, rand.to_string()); + } + } + }; +} + +impl_write_num!(u8, i8, test_u8, log10_u8); +impl_write_num!(u16, i16, test_u16, log10_u16); +impl_write_num!(u32, i32, test_u32, log10_u32); +impl_write_num!(u64, i64, test_u64, log10_u64); +impl_write_num!(u128, i128, test_u128, log10_u128); + +#[test] +fn assert_log10_approximation() { + for i in 1..u128::BITS { + assert_eq!(i * 59 / 196, 2f64.powf(i.into()).log10().floor() as u32); + } +} + +impl Writeable for str { + #[inline] + fn write_to<W: fmt::Write + ?Sized>(&self, sink: &mut W) -> fmt::Result { + sink.write_str(self) + } + + #[inline] + fn writeable_length_hint(&self) -> LengthHint { + LengthHint::exact(self.len()) + } + + /// Returns a borrowed `str`. + /// + /// # Examples + /// + /// ``` + /// use std::borrow::Cow; + /// use writeable::Writeable; + /// + /// let cow = "foo".write_to_string(); + /// assert!(matches!(cow, Cow::Borrowed(_))); + /// ``` + #[inline] + fn write_to_string(&self) -> Cow<str> { + Cow::Borrowed(self) + } +} + +impl Writeable for String { + #[inline] + fn write_to<W: fmt::Write + ?Sized>(&self, sink: &mut W) -> fmt::Result { + sink.write_str(self) + } + + #[inline] + fn writeable_length_hint(&self) -> LengthHint { + LengthHint::exact(self.len()) + } + + #[inline] + fn write_to_string(&self) -> Cow<str> { + Cow::Borrowed(self) + } +} + +impl<'a, T: Writeable + ?Sized> Writeable for &T { + #[inline] + fn write_to<W: fmt::Write + ?Sized>(&self, sink: &mut W) -> fmt::Result { + (*self).write_to(sink) + } + + #[inline] + fn write_to_parts<W: PartsWrite + ?Sized>(&self, sink: &mut W) -> fmt::Result { + (*self).write_to_parts(sink) + } + + #[inline] + fn writeable_length_hint(&self) -> LengthHint { + (*self).writeable_length_hint() + } + + #[inline] + fn write_to_string(&self) -> Cow<str> { + (*self).write_to_string() + } +} + +#[test] +fn test_string_impls() { + fn check_writeable_slice<W: Writeable>(writeables: &[W]) { + assert_writeable_eq!(&writeables[0], ""); + assert_writeable_eq!(&writeables[1], "abc"); + } + + // test str impl + let arr: &[&str] = &["", "abc"]; + check_writeable_slice(arr); + + // test String impl + let arr: &[String] = &["".to_string(), "abc".to_string()]; + check_writeable_slice(arr); + + // test &T impl + let arr: &[&String] = &[&"".to_string(), &"abc".to_string()]; + check_writeable_slice(arr); +} diff --git a/vendor/writeable/src/lib.rs b/vendor/writeable/src/lib.rs new file mode 100644 index 000000000..66be7f33b --- /dev/null +++ b/vendor/writeable/src/lib.rs @@ -0,0 +1,390 @@ +// This file is part of ICU4X. For terms of use, please see the file +// called LICENSE at the top level of the ICU4X source tree +// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ). + +// https://github.com/unicode-org/icu4x/blob/main/docs/process/boilerplate.md#library-annotations +#![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, + ) +)] + +//! `writeable` is a utility crate of the [`ICU4X`] project. +//! +//! It includes [`Writeable`], a core trait representing an object that can be written to a +//! sink implementing `std::fmt::Write`. It is an alternative to `std::fmt::Display` with the +//! addition of a function indicating the number of bytes to be written. +//! +//! `Writeable` improves upon `std::fmt::Display` in two ways: +//! +//! 1. More efficient, since the sink can pre-allocate bytes. +//! 2. Smaller code, since the format machinery can be short-circuited. +//! +//! # Examples +//! +//! ``` +//! use std::fmt; +//! use writeable::assert_writeable_eq; +//! use writeable::LengthHint; +//! use writeable::Writeable; +//! +//! struct WelcomeMessage<'s> { +//! pub name: &'s str, +//! } +//! +//! impl<'s> Writeable for WelcomeMessage<'s> { +//! fn write_to<W: fmt::Write + ?Sized>(&self, sink: &mut W) -> fmt::Result { +//! sink.write_str("Hello, ")?; +//! sink.write_str(self.name)?; +//! sink.write_char('!')?; +//! Ok(()) +//! } +//! +//! fn writeable_length_hint(&self) -> LengthHint { +//! // "Hello, " + '!' + length of name +//! LengthHint::exact(8 + self.name.len()) +//! } +//! } +//! +//! let message = WelcomeMessage { name: "Alice" }; +//! assert_writeable_eq!(&message, "Hello, Alice!"); +//! +//! // Types implementing `Writeable` are recommended to also implement `fmt::Display`. +//! // This can be simply done by redirecting to the `Writeable` implementation: +//! writeable::impl_display_with_writeable!(WelcomeMessage<'_>); +//! ``` +//! +//! [`ICU4X`]: ../icu/index.html + +extern crate alloc; + +mod impls; +mod ops; + +use alloc::borrow::Cow; +use alloc::string::String; +use alloc::vec::Vec; +use core::fmt; + +/// A hint to help consumers of `Writeable` pre-allocate bytes before they call +/// [`write_to`](Writeable::write_to). +/// +/// This behaves like `Iterator::size_hint`: it is a tuple where the first element is the +/// lower bound, and the second element is the upper bound. If the upper bound is `None` +/// either there is no known upper bound, or the upper bound is larger than `usize`. +/// +/// `LengthHint` implements std`::ops::{Add, Mul}` and similar traits for easy composition. +/// During computation, the lower bound will saturate at `usize::MAX`, while the upper +/// bound will become `None` if `usize::MAX` is exceeded. +#[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) + } + + /// `write_to` will use exactly n bytes. + pub fn exact(n: usize) -> Self { + Self(n, Some(n)) + } + + /// `write_to` will use at least n bytes. + pub fn at_least(n: usize) -> Self { + Self(n, None) + } + + /// `write_to` will use at most n bytes. + pub fn at_most(n: usize) -> Self { + Self(0, Some(n)) + } + + /// `write_to` will use between `n` and `m` bytes. + pub fn between(n: usize, m: usize) -> Self { + Self(Ord::min(n, m), Some(Ord::max(n, m))) + } + + /// Returns a recommendation for the number of bytes to pre-allocate. + /// If an upper bound exists, this is used, otherwise the lower bound + /// (which might be 0). + /// + /// # Examples + /// + /// ``` + /// use writeable::Writeable; + /// + /// fn pre_allocate_string(w: &impl Writeable) -> String { + /// String::with_capacity(w.writeable_length_hint().capacity()) + /// } + /// ``` + pub fn capacity(&self) -> usize { + self.1.unwrap_or(self.0) + } + + /// Returns whether the `LengthHint` indicates that the string is exactly 0 bytes long. + pub fn is_zero(&self) -> bool { + self.1 == Some(0) + } +} + +#[derive(Clone, Copy, Debug, PartialEq)] +#[allow(clippy::exhaustive_structs)] // stable +pub struct Part { + pub category: &'static str, + pub value: &'static str, +} + +/// A sink that supports annotating parts of the string with `Part`s. +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; +} + +/// `Writeable` is an alternative to `std::fmt::Display` with the addition of a length function. +pub trait Writeable { + /// Writes a string to the given sink. Errors from the sink are bubbled up. + /// The default implementation delegates to `write_to_parts`, and discards any + /// `Part` annotations. + 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)) + } + + /// Write bytes and `Part` annotations to the given sink. Errors from the + /// sink are bubbled up. The default implementation delegates to `write_to`, + /// and doesn't produce any `Part` annotations. + fn write_to_parts<S: PartsWrite + ?Sized>(&self, sink: &mut S) -> fmt::Result { + self.write_to(sink) + } + + /// Returns a hint for the number of UTF-8 bytes that will be written to the sink. + /// + /// Override this method if it can be computed quickly. + fn writeable_length_hint(&self) -> LengthHint { + LengthHint::undefined() + } + + /// Creates a new `String` with the data from this `Writeable`. Like `ToString`, + /// but smaller and faster. + /// + /// The default impl allocates an owned `String`. However, if it is possible to return a + /// borrowed string, overwrite this method to return a `Cow::Borrowed`. + /// + /// To remove the `Cow` wrapper, call `.into_owned()` or `.as_str()` as appropriate. + /// + /// # Examples + /// + /// Inspect a `Writeable` before writing it to the sink: + /// + /// ``` + /// use core::fmt::{Result, Write}; + /// use writeable::Writeable; + /// + /// fn write_if_ascii<W, S>(w: &W, sink: &mut S) -> Result + /// where + /// W: Writeable + ?Sized, + /// S: Write + ?Sized, + /// { + /// let s = w.write_to_string(); + /// if s.is_ascii() { + /// sink.write_str(&s) + /// } else { + /// Ok(()) + /// } + /// } + /// ``` + /// + /// Convert the `Writeable` into a fully owned `String`: + /// + /// ``` + /// use writeable::Writeable; + /// + /// fn make_string(w: &impl Writeable) -> String { + /// w.write_to_string().into_owned() + /// } + /// ``` + fn write_to_string(&self) -> Cow<str> { + let mut output = String::with_capacity(self.writeable_length_hint().capacity()); + let _ = self.write_to(&mut output); + Cow::Owned(output) + } +} + +/// Implements [`Display`](core::fmt::Display) for types that implement [`Writeable`]. +/// +/// It's recommended to do this for every [`Writeable`] type, as it will add +/// support for `core::fmt` features like [`fmt!`](std::fmt), +/// [`print!`](std::print), [`write!`](std::write), etc. +#[macro_export] +macro_rules! impl_display_with_writeable { + ($type:ty) => { + /// This trait is implemented for compatibility with [`fmt!`](alloc::fmt). + /// To create a string, [`Writeable::write_to_string`] is usually more efficient. + impl core::fmt::Display for $type { + #[inline] + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + $crate::Writeable::write_to(&self, f) + } + } + }; +} + +/// Testing macros for types implementing Writeable. The first argument should be a +/// `Writeable`, the second argument a string, and the third argument (*_parts_eq only) +/// a list of parts (`[(usize, usize, Part)]`). +/// +/// The macros tests for equality of string content, parts (*_parts_eq only), and +/// verify the size hint. +/// +/// # Examples +/// +/// ``` +/// # use writeable::Writeable; +/// # use writeable::LengthHint; +/// # use writeable::Part; +/// # use writeable::assert_writeable_eq; +/// # use writeable::assert_writeable_parts_eq; +/// # use std::fmt::{self, Write}; +/// +/// const WORD: Part = Part { +/// category: "foo", +/// value: "word", +/// }; +/// +/// struct Demo; +/// impl Writeable for Demo { +/// fn write_to_parts<S: writeable::PartsWrite + ?Sized>(&self, sink: &mut S) -> fmt::Result { +/// sink.with_part(WORD, |w| w.write_str("foo")) +/// } +/// fn writeable_length_hint(&self) -> LengthHint { +/// LengthHint::exact(3) +/// } +/// } +/// +/// writeable::impl_display_with_writeable!(Demo); +/// +/// assert_writeable_eq!(&Demo, "foo"); +/// assert_writeable_eq!(&Demo, "foo", "Message: {}", "Hello World"); +/// +/// assert_writeable_parts_eq!(&Demo, "foo", [(0, 3, WORD)]); +/// assert_writeable_parts_eq!(&Demo, "foo", [(0, 3, WORD)], "Message: {}", "Hello World"); +/// ``` +#[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(), $($arg)*); + if let Some(upper) = length_hint.1 { + assert!(actual_str.len() <= upper, $($arg)*); + } + }}; +} + +/// See [`assert_writeable_eq`]. +#[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)+); + } + }}; +} + +#[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)?; + self.parts.push((start, self.string.len(), part)); + Ok(()) + } + } + + let mut state = State { + string: alloc::string::String::new(), + parts: Vec::new(), + }; + writeable.write_to_parts(&mut state)?; + + // Sort by first open and last closed + state + .parts + .sort_unstable_by_key(|(begin, end, _)| (*begin, end.wrapping_neg())); + Ok((state.string, state.parts)) +} diff --git a/vendor/writeable/src/ops.rs b/vendor/writeable/src/ops.rs new file mode 100644 index 000000000..3ed4406d7 --- /dev/null +++ b/vendor/writeable/src/ops.rs @@ -0,0 +1,291 @@ +// This file is part of ICU4X. For terms of use, please see the file +// called LICENSE at the top level of the ICU4X source tree +// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ). + +use crate::LengthHint; + +impl core::ops::Add<LengthHint> for LengthHint { + type Output = Self; + + fn add(self, other: LengthHint) -> Self { + LengthHint( + self.0.saturating_add(other.0), + match (self.1, other.1) { + (Some(c), Some(d)) => c.checked_add(d), + _ => None, + }, + ) + } +} + +impl core::ops::AddAssign<LengthHint> for LengthHint { + fn add_assign(&mut self, other: Self) { + *self = *self + other; + } +} + +impl core::iter::Sum<LengthHint> for LengthHint { + fn sum<I>(iter: I) -> Self + where + I: Iterator<Item = LengthHint>, + { + iter.fold(LengthHint::exact(0), core::ops::Add::add) + } +} + +impl core::ops::Add<usize> for LengthHint { + type Output = Self; + + fn add(self, other: usize) -> Self { + Self( + self.0.saturating_add(other), + self.1.and_then(|upper| upper.checked_add(other)), + ) + } +} + +impl core::ops::AddAssign<usize> for LengthHint { + fn add_assign(&mut self, other: usize) { + *self = *self + other; + } +} + +impl core::ops::Mul<usize> for LengthHint { + type Output = Self; + + fn mul(self, other: usize) -> Self { + Self( + self.0.saturating_mul(other), + self.1.and_then(|upper| upper.checked_mul(other)), + ) + } +} + +impl core::ops::MulAssign<usize> for LengthHint { + fn mul_assign(&mut self, other: usize) { + *self = *self * other; + } +} + +impl core::ops::BitOr<LengthHint> for LengthHint { + type Output = Self; + + /// Returns a new hint that is correct wherever `self` is correct, and wherever + /// `other` is correct. + /// + /// Example: + /// ``` + /// # use writeable::{LengthHint, Writeable}; + /// # use core::fmt; + /// # fn coin_flip() -> bool { true } + /// + /// struct NonDeterministicWriteable(String, String); + /// + /// impl Writeable for NonDeterministicWriteable { + /// fn write_to<W: fmt::Write + ?Sized>(&self, sink: &mut W) -> fmt::Result { + /// sink.write_str(if coin_flip() { &self.0 } else { &self.1 }) + /// } + /// + /// fn writeable_length_hint(&self) -> LengthHint { + /// LengthHint::exact(self.0.len()) | LengthHint::exact(self.1.len()) + /// } + /// } + /// + /// writeable::impl_display_with_writeable!(NonDeterministicWriteable); + /// ``` + fn bitor(self, other: LengthHint) -> Self { + LengthHint( + Ord::min(self.0, other.0), + match (self.1, other.1) { + (Some(c), Some(d)) => Some(Ord::max(c, d)), + _ => None, + }, + ) + } +} + +impl core::ops::BitOrAssign<LengthHint> for LengthHint { + fn bitor_assign(&mut self, other: Self) { + *self = *self | other; + } +} + +impl core::iter::Sum<usize> for LengthHint { + fn sum<I>(iter: I) -> Self + where + I: Iterator<Item = usize>, + { + LengthHint::exact(iter.sum::<usize>()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_add() { + assert_eq!(LengthHint::exact(3) + 2, LengthHint::exact(5)); + assert_eq!( + LengthHint::exact(3) + LengthHint::exact(2), + LengthHint::exact(5) + ); + assert_eq!( + LengthHint::exact(3) + LengthHint::undefined(), + LengthHint::at_least(3) + ); + + assert_eq!(LengthHint::undefined() + 2, LengthHint::at_least(2)); + assert_eq!( + LengthHint::undefined() + LengthHint::exact(2), + LengthHint::at_least(2) + ); + assert_eq!( + LengthHint::undefined() + LengthHint::undefined(), + LengthHint::undefined() + ); + + assert_eq!( + LengthHint::at_least(15) + LengthHint::exact(3), + LengthHint::at_least(18) + ); + + assert_eq!( + LengthHint::at_least(15) + LengthHint::at_most(3), + LengthHint::at_least(15) + ); + + assert_eq!(LengthHint::between(48, 92) + 5, LengthHint::between(53, 97)); + + let mut len = LengthHint::exact(5); + len += LengthHint::exact(3); + assert_eq!(len, LengthHint::exact(8)); + len += 2; + assert_eq!(len, LengthHint::exact(10)); + len += LengthHint::undefined(); + assert_eq!(len, LengthHint::at_least(10)); + + len += LengthHint::exact(3); + assert_eq!(len, LengthHint::at_least(13)); + len += 2; + assert_eq!(len, LengthHint::at_least(15)); + len += LengthHint::undefined(); + assert_eq!(len, LengthHint::at_least(15)); + + assert_eq!( + LengthHint::between(usize::MAX - 10, usize::MAX - 5) + LengthHint::exact(20), + LengthHint::at_least(usize::MAX) + ); + } + + #[test] + fn test_sum() { + let lens = vec![ + LengthHint::exact(4), + LengthHint::exact(1), + LengthHint::exact(1), + ]; + assert_eq!( + lens.iter().copied().sum::<LengthHint>(), + LengthHint::exact(6) + ); + + let lens = vec![ + LengthHint::exact(4), + LengthHint::undefined(), + LengthHint::at_least(1), + ]; + assert_eq!( + lens.iter().copied().sum::<LengthHint>(), + LengthHint::at_least(5) + ); + + let lens = vec![ + LengthHint::exact(4), + LengthHint::undefined(), + LengthHint::at_most(1), + ]; + assert_eq!( + lens.iter().copied().sum::<LengthHint>(), + LengthHint::at_least(4) + ); + + let lens = vec![4, 1, 1]; + assert_eq!( + lens.iter().copied().sum::<LengthHint>(), + LengthHint::exact(6) + ); + } + + #[test] + fn test_mul() { + assert_eq!(LengthHint::exact(3) * 2, LengthHint::exact(6)); + + assert_eq!(LengthHint::undefined() * 2, LengthHint::undefined()); + + assert_eq!( + LengthHint::between(48, 92) * 2, + LengthHint::between(96, 184) + ); + + let mut len = LengthHint::exact(5); + len *= 2; + assert_eq!(len, LengthHint::exact(10)); + + assert_eq!( + LengthHint::between(usize::MAX - 10, usize::MAX - 5) * 2, + LengthHint::at_least(usize::MAX) + ); + } + + #[test] + fn test_bitor() { + assert_eq!( + LengthHint::exact(3) | LengthHint::exact(2), + LengthHint::between(2, 3) + ); + assert_eq!( + LengthHint::exact(3) | LengthHint::undefined(), + LengthHint::undefined() + ); + + assert_eq!( + LengthHint::undefined() | LengthHint::undefined(), + LengthHint::undefined() + ); + + assert_eq!( + LengthHint::exact(10) | LengthHint::exact(10), + LengthHint::exact(10) + ); + + assert_eq!( + LengthHint::at_least(15) | LengthHint::exact(3), + LengthHint::at_least(3) + ); + + assert_eq!( + LengthHint::at_least(15) | LengthHint::at_most(18), + LengthHint::undefined() + ); + + assert_eq!( + LengthHint::at_least(15) | LengthHint::at_least(18), + LengthHint::at_least(15) + ); + + assert_eq!( + LengthHint::at_most(15) | LengthHint::at_most(18), + LengthHint::at_most(18) + ); + + assert_eq!( + LengthHint::between(5, 10) | LengthHint::at_most(3), + LengthHint::at_most(10) + ); + + let mut len = LengthHint::exact(5); + len |= LengthHint::exact(3); + assert_eq!(len, LengthHint::between(5, 3)); + } +} |