1// This file is part of ICU4X. For terms of use, please see the file
2// called LICENSE at the top level of the ICU4X source tree
3// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
4
5use crate::*;
6use alloc::borrow::Cow;
7use core::fmt;
8
9macro_rules! impl_write_num {
10 ($u:ty, $i:ty, $test:ident, $max_ilog_10:expr) => {
11 impl $crate::Writeable for $u {
12 fn write_to<W: core::fmt::Write + ?Sized>(&self, sink: &mut W) -> core::fmt::Result {
13 let mut buf = [b'0'; $max_ilog_10 + 1];
14 let mut n = *self;
15 let mut i = $max_ilog_10 + 1;
16 #[allow(clippy::indexing_slicing)] // n < 10^i
17 while n != 0 {
18 i -= 1;
19 buf[i] = b'0' + (n % 10) as u8;
20 n /= 10;
21 }
22 if i == buf.len() {
23 debug_assert_eq!(*self, 0);
24 i -= 1;
25 }
26 #[allow(clippy::indexing_slicing)] // buf is ASCII
27 let s = unsafe { core::str::from_utf8_unchecked(&buf[i..]) };
28 sink.write_str(s)
29 }
30
31 fn writeable_length_hint(&self) -> $crate::LengthHint {
32 #[allow(unstable_name_collisions)] // that's the idea
33 LengthHint::exact(self.checked_ilog10().unwrap_or(0) as usize + 1)
34 }
35 }
36
37 impl ILog10Ext for $u {
38 fn checked_ilog10(self) -> Option<u32> {
39 if self == 0 {
40 return None;
41 }
42 let b = (<$u>::BITS - 1) - self.leading_zeros();
43 // self ∈ [2ᵇ, 2ᵇ⁺¹-1] => ⌊log₁₀(self)⌋ ∈ [⌊log₁₀(2ᵇ)⌋, ⌊log₁₀(2ᵇ⁺¹-1)⌋]
44 // <=> ⌊log₁₀(self)⌋ ∈ [⌊log₁₀(2ᵇ)⌋, ⌊log₁₀(2ᵇ⁺¹)⌋]
45 // <=> ⌊log₁₀(self)⌋ ∈ [⌊b log₁₀(2)⌋, ⌊(b+1) log₁₀(2)⌋]
46 // The second line holds because there is no integer in
47 // [log₁₀(2ᶜ-1), log₁₀(2ᶜ)], if there were, there'd be some 10ⁿ in
48 // [2ᶜ-1, 2ᶜ], but it can't be 2ᶜ-1 due to parity nor 2ᶜ due to prime
49 // factors.
50
51 const M: u32 = (core::f64::consts::LOG10_2 * (1 << 26) as f64) as u32;
52 let low = (b * M) >> 26;
53 let high = ((b + 1) * M) >> 26;
54
55 // If the bounds aren't tight (e.g. 87 ∈ [64, 127] ⟹ ⌊log₁₀(87)⌋ ∈ [1,2]),
56 // compare to 10ʰ (100). This shouldn't happen too often as there are more
57 // powers of 2 than 10 (it happens for 14% of u32s).
58 Some(if high == low {
59 low
60 } else if self < (10 as $u).pow(high) {
61 low
62 } else {
63 high
64 })
65 }
66 }
67
68 impl $crate::Writeable for $i {
69 fn write_to<W: core::fmt::Write + ?Sized>(&self, sink: &mut W) -> core::fmt::Result {
70 if self.is_negative() {
71 sink.write_str("-")?;
72 }
73 self.unsigned_abs().write_to(sink)
74 }
75
76 fn writeable_length_hint(&self) -> $crate::LengthHint {
77 $crate::LengthHint::exact(if self.is_negative() { 1 } else { 0 })
78 + self.unsigned_abs().writeable_length_hint()
79 }
80 }
81
82 #[test]
83 fn $test() {
84 use $crate::assert_writeable_eq;
85 assert_writeable_eq!(&(0 as $u), "0");
86 assert_writeable_eq!(&(0 as $i), "0");
87 assert_writeable_eq!(&(-0 as $i), "0");
88 assert_writeable_eq!(&(1 as $u), "1");
89 assert_writeable_eq!(&(1 as $i), "1");
90 assert_writeable_eq!(&(-1 as $i), "-1");
91 assert_writeable_eq!(&(9 as $u), "9");
92 assert_writeable_eq!(&(9 as $i), "9");
93 assert_writeable_eq!(&(-9 as $i), "-9");
94 assert_writeable_eq!(&(10 as $u), "10");
95 assert_writeable_eq!(&(10 as $i), "10");
96 assert_writeable_eq!(&(-10 as $i), "-10");
97 assert_writeable_eq!(&(99 as $u), "99");
98 assert_writeable_eq!(&(99 as $i), "99");
99 assert_writeable_eq!(&(-99 as $i), "-99");
100 assert_writeable_eq!(&(100 as $u), "100");
101 assert_writeable_eq!(&(-100 as $i), "-100");
102 assert_writeable_eq!(&<$u>::MAX, <$u>::MAX.to_string());
103 assert_writeable_eq!(&<$i>::MAX, <$i>::MAX.to_string());
104 assert_writeable_eq!(&<$i>::MIN, <$i>::MIN.to_string());
105
106 use rand::{rngs::SmallRng, Rng, SeedableRng};
107 let mut rng = SmallRng::seed_from_u64(4); // chosen by fair dice roll.
108 // guaranteed to be random.
109 for _ in 0..1000 {
110 let rand = rng.gen::<$u>();
111 assert_writeable_eq!(rand, rand.to_string());
112 }
113 }
114 };
115}
116
117/// `checked_ilog10` is added as a method on integer types in 1.67.
118/// This extension trait provides it for older compilers.
119trait ILog10Ext: Sized {
120 fn checked_ilog10(self) -> Option<u32>;
121}
122
123impl_write_num!(u8, i8, test_u8, 2);
124impl_write_num!(u16, i16, test_u16, 4);
125impl_write_num!(u32, i32, test_u32, 9);
126impl_write_num!(u64, i64, test_u64, 19);
127impl_write_num!(u128, i128, test_u128, 38);
128impl_write_num!(
129 usize,
130 isize,
131 test_usize,
132 if usize::MAX as u64 == u64::MAX { 19 } else { 9 }
133);
134
135impl Writeable for str {
136 #[inline]
137 fn write_to<W: fmt::Write + ?Sized>(&self, sink: &mut W) -> fmt::Result {
138 sink.write_str(self)
139 }
140
141 #[inline]
142 fn writeable_length_hint(&self) -> LengthHint {
143 LengthHint::exact(self.len())
144 }
145
146 /// Returns a borrowed `str`.
147 ///
148 /// # Examples
149 ///
150 /// ```
151 /// use std::borrow::Cow;
152 /// use writeable::Writeable;
153 ///
154 /// let cow = "foo".write_to_string();
155 /// assert!(matches!(cow, Cow::Borrowed(_)));
156 /// ```
157 #[inline]
158 fn write_to_string(&self) -> Cow<str> {
159 Cow::Borrowed(self)
160 }
161}
162
163impl Writeable for String {
164 #[inline]
165 fn write_to<W: fmt::Write + ?Sized>(&self, sink: &mut W) -> fmt::Result {
166 sink.write_str(self)
167 }
168
169 #[inline]
170 fn writeable_length_hint(&self) -> LengthHint {
171 LengthHint::exact(self.len())
172 }
173
174 #[inline]
175 fn write_to_string(&self) -> Cow<str> {
176 Cow::Borrowed(self)
177 }
178}
179
180impl<T: Writeable + ?Sized> Writeable for &T {
181 #[inline]
182 fn write_to<W: fmt::Write + ?Sized>(&self, sink: &mut W) -> fmt::Result {
183 (*self).write_to(sink)
184 }
185
186 #[inline]
187 fn write_to_parts<W: PartsWrite + ?Sized>(&self, sink: &mut W) -> fmt::Result {
188 (*self).write_to_parts(sink)
189 }
190
191 #[inline]
192 fn writeable_length_hint(&self) -> LengthHint {
193 (*self).writeable_length_hint()
194 }
195
196 #[inline]
197 fn write_to_string(&self) -> Cow<str> {
198 (*self).write_to_string()
199 }
200}
201
202#[test]
203fn test_string_impls() {
204 fn check_writeable_slice<W: Writeable + core::fmt::Display>(writeables: &[W]) {
205 assert_writeable_eq!(&writeables[0], "");
206 assert_writeable_eq!(&writeables[1], "abc");
207 }
208
209 // test str impl
210 let arr: &[&str] = &["", "abc"];
211 check_writeable_slice(writeables:arr);
212
213 // test String impl
214 let arr: &[String] = &[String::new(), "abc".to_owned()];
215 check_writeable_slice(writeables:arr);
216
217 // test &T impl
218 let arr: &[&String] = &[&String::new(), &"abc".to_owned()];
219 check_writeable_slice(writeables:arr);
220}
221