summaryrefslogtreecommitdiffstats
path: root/vendor/writeable/src
diff options
context:
space:
mode:
Diffstat (limited to 'vendor/writeable/src')
-rw-r--r--vendor/writeable/src/impls.rs104
-rw-r--r--vendor/writeable/src/lib.rs60
-rw-r--r--vendor/writeable/src/ops.rs5
3 files changed, 113 insertions, 56 deletions
diff --git a/vendor/writeable/src/impls.rs b/vendor/writeable/src/impls.rs
index 649ede4d5..a2b5201e0 100644
--- a/vendor/writeable/src/impls.rs
+++ b/vendor/writeable/src/impls.rs
@@ -7,12 +7,12 @@ use alloc::borrow::Cow;
use core::fmt;
macro_rules! impl_write_num {
- ($u:ty, $i:ty, $test:ident, $log10:ident) => {
+ ($u:ty, $i:ty, $test:ident, $max_ilog_10:expr) => {
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 buf = [b'0'; $max_ilog_10 + 1];
let mut n = *self;
- let mut i = buf.len();
+ let mut i = $max_ilog_10 + 1;
#[allow(clippy::indexing_slicing)] // n < 10^i
while n != 0 {
i -= 1;
@@ -29,40 +29,38 @@ macro_rules! impl_write_num {
}
fn writeable_length_hint(&self) -> $crate::LengthHint {
- $crate::LengthHint::exact(if *self == 0 {
- 1
- } else {
- $log10(*self) as usize + 1
- })
+ LengthHint::exact(self.checked_ilog10().unwrap_or(0) 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 ILog10Ext for $u {
+ fn checked_ilog10(self) -> Option<u32> {
+ if self == 0 {
+ return None;
+ }
+ let b = (<$u>::BITS - 1) - self.leading_zeros();
+ // self ∈ [2ᵇ, 2ᵇ⁺¹-1] => ⌊log₁₀(self)⌋ ∈ [⌊log₁₀(2ᵇ)⌋, ⌊log₁₀(2ᵇ⁺¹-1)⌋]
+ // <=> ⌊log₁₀(self)⌋ ∈ [⌊log₁₀(2ᵇ)⌋, ⌊log₁₀(2ᵇ⁺¹)⌋]
+ // <=> ⌊log₁₀(self)⌋ ∈ [⌊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).
+ Some(if high == low {
+ low
+ } else if self < (10 as $u).pow(high) {
+ low
+ } else {
+ high
+ })
}
}
@@ -84,11 +82,14 @@ macro_rules! impl_write_num {
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!(&(-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!(&(9 as $u), "9");
+ assert_writeable_eq!(&(9 as $i), "9");
+ assert_writeable_eq!(&(-9 as $i), "-9");
assert_writeable_eq!(&(10 as $u), "10");
assert_writeable_eq!(&(10 as $i), "10");
assert_writeable_eq!(&(-10 as $i), "-10");
@@ -112,19 +113,24 @@ macro_rules! impl_write_num {
};
}
-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);
- }
+/// `checked_ilog10` is added as a method on integer types in 1.67.
+/// This extension trait provides it for older compilers.
+trait ILog10Ext: Sized {
+ fn checked_ilog10(self) -> Option<u32>;
}
+impl_write_num!(u8, i8, test_u8, 2);
+impl_write_num!(u16, i16, test_u16, 4);
+impl_write_num!(u32, i32, test_u32, 9);
+impl_write_num!(u64, i64, test_u64, 19);
+impl_write_num!(u128, i128, test_u128, 38);
+impl_write_num!(
+ usize,
+ isize,
+ test_usize,
+ if usize::MAX as u64 == u64::MAX { 19 } else { 9 }
+);
+
impl Writeable for str {
#[inline]
fn write_to<W: fmt::Write + ?Sized>(&self, sink: &mut W) -> fmt::Result {
@@ -194,7 +200,7 @@ impl<'a, T: Writeable + ?Sized> Writeable for &T {
#[test]
fn test_string_impls() {
- fn check_writeable_slice<W: Writeable>(writeables: &[W]) {
+ fn check_writeable_slice<W: Writeable + core::fmt::Display>(writeables: &[W]) {
assert_writeable_eq!(&writeables[0], "");
assert_writeable_eq!(&writeables[1], "abc");
}
@@ -204,10 +210,10 @@ fn test_string_impls() {
check_writeable_slice(arr);
// test String impl
- let arr: &[String] = &["".to_string(), "abc".to_string()];
+ let arr: &[String] = &[String::new(), "abc".to_owned()];
check_writeable_slice(arr);
// test &T impl
- let arr: &[&String] = &[&"".to_string(), &"abc".to_string()];
+ let arr: &[&String] = &[&String::new(), &"abc".to_owned()];
check_writeable_slice(arr);
}
diff --git a/vendor/writeable/src/lib.rs b/vendor/writeable/src/lib.rs
index 66be7f33b..0eb6be8d6 100644
--- a/vendor/writeable/src/lib.rs
+++ b/vendor/writeable/src/lib.rs
@@ -136,6 +136,28 @@ impl LengthHint {
}
}
+/// [`Part`]s are used as annotations for formatted strings. For example, a string like
+/// `Alice, Bob` could assign a `NAME` part to the substrings `Alice` and `Bob`, and a
+/// `PUNCTUATION` part to `, `. This allows for example to apply styling only to names.
+///
+/// `Part` contains two fields, whose usage is left up to the producer of the [`Writeable`].
+/// Conventionally, the `category` field will identify the formatting logic that produces
+/// the string/parts, whereas the `value` field will have semantic meaning. `NAME` and
+/// `PUNCTUATION` could thus be defined as
+/// ```
+/// # use writeable::Part;
+/// const NAME: Part = Part {
+/// category: "userlist",
+/// value: "name",
+/// };
+/// const PUNCTUATION: Part = Part {
+/// category: "userlist",
+/// value: "punctuation",
+/// };
+/// ```
+///
+/// That said, consumers should not usually have to inspect `Part` internals. Instead,
+/// formatters should expose the `Part`s they produces as constants.
#[derive(Clone, Copy, Debug, PartialEq)]
#[allow(clippy::exhaustive_structs)] // stable
pub struct Part {
@@ -240,7 +262,11 @@ pub trait Writeable {
/// }
/// ```
fn write_to_string(&self) -> Cow<str> {
- let mut output = String::with_capacity(self.writeable_length_hint().capacity());
+ 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)
}
@@ -289,7 +315,10 @@ macro_rules! impl_display_with_writeable {
///
/// struct Demo;
/// impl Writeable for Demo {
-/// fn write_to_parts<S: writeable::PartsWrite + ?Sized>(&self, sink: &mut S) -> fmt::Result {
+/// 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 {
@@ -303,7 +332,13 @@ macro_rules! impl_display_with_writeable {
/// 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");
+/// assert_writeable_parts_eq!(
+/// &Demo,
+/// "foo",
+/// [(0, 3, WORD)],
+/// "Message: {}",
+/// "Hello World"
+/// );
/// ```
#[macro_export]
macro_rules! assert_writeable_eq {
@@ -316,10 +351,19 @@ macro_rules! assert_writeable_eq {
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)*);
+ 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, $($arg)*);
+ 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);
}};
}
@@ -340,6 +384,7 @@ macro_rules! assert_writeable_parts_eq {
if let Some(upper) = length_hint.1 {
assert!(actual_str.len() <= upper, $($arg)+);
}
+ assert_eq!(actual_writeable.to_string(), $expected_str);
}};
}
@@ -371,7 +416,10 @@ pub fn writeable_to_parts_for_test<W: Writeable>(
) -> fmt::Result {
let start = self.string.len();
f(self)?;
- self.parts.push((start, self.string.len(), part));
+ let end = self.string.len();
+ if start < end {
+ self.parts.push((start, end, part));
+ }
Ok(())
}
}
diff --git a/vendor/writeable/src/ops.rs b/vendor/writeable/src/ops.rs
index 3ed4406d7..2ccad7d6d 100644
--- a/vendor/writeable/src/ops.rs
+++ b/vendor/writeable/src/ops.rs
@@ -82,7 +82,10 @@ impl core::ops::BitOr<LengthHint> for LengthHint {
/// struct NonDeterministicWriteable(String, String);
///
/// impl Writeable for NonDeterministicWriteable {
- /// fn write_to<W: fmt::Write + ?Sized>(&self, sink: &mut W) -> fmt::Result {
+ /// fn write_to<W: fmt::Write + ?Sized>(
+ /// &self,
+ /// sink: &mut W,
+ /// ) -> fmt::Result {
/// sink.write_str(if coin_flip() { &self.0 } else { &self.1 })
/// }
///