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 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
use core::fmt;
use awint_internals::*;
use const_fn::const_fn;
use SerdeError::*;
use crate::Bits;
/// Runs all pre serialization checks except for equal width and `Overflow`
/// checks
const fn verify_for_bytes_(src: &[u8], radix: u8) -> Result<(), SerdeError> {
if radix < 2 || radix > 36 {
return Err(InvalidRadix)
}
const_for!(i in {0..src.len()} {
let b = src[i];
if b == b'_' {
continue;
}
let in_decimal_range = b'0' <= b && b < b'0'.wrapping_add(if radix < 10 {radix} else {10});
let in_lower_range = (radix > 10)
&& (b'a' <= b)
&& (b < b'a'.wrapping_add(radix).wrapping_sub(10));
let in_upper_range = (radix > 10)
&& (b'A' <= b)
&& (b < b'A'.wrapping_add(radix).wrapping_sub(10));
if radix <= 10 {
if !in_decimal_range {
return Err(InvalidChar)
}
} else if !(in_decimal_range || in_lower_range || in_upper_range) {
return Err(InvalidChar)
}
});
Ok(())
}
/// # `const` string representation conversion
///
/// Note: the `awint_ext` crate has higher level allocating functions
/// `Awi::bits_to_string_radix`, `Awi::bits_to_vec_radix`, and
/// `<Awi as FromStr>::from_str`
impl Bits {
/// A version of [Bits::bytes_radix_] optimized for power of two
/// radixes
#[doc(hidden)]
#[const_fn(cfg(feature = "const_support"))]
pub const fn power_of_two_bytes_(
&mut self,
sign: Option<bool>,
src: &[u8],
radix: u8,
pad: &mut Self,
) -> Result<(), SerdeError> {
if self.bw() != pad.bw() {
return Err(NonEqualWidths)
}
if !radix.is_power_of_two() {
return Err(InvalidRadix)
}
let log2 = radix.trailing_zeros() as usize;
if let Err(e) = verify_for_bytes_(src, radix) {
return Err(e)
}
// the accumulator
pad.zero_();
let mut shl = 0;
const_for!(i in {0..src.len()}.rev() {
let b = src[i];
if b == b'_' {
continue;
}
let char_digit = if b <= b'9' {
b.wrapping_sub(b'0')
} else if b <= b'Z' {
b.wrapping_sub(b'A').wrapping_add(10)
} else {
b.wrapping_sub(b'a').wrapping_add(10)
} as Digit;
pad.digit_or_(char_digit, shl);
shl += log2;
if shl >= self.bw() {
let tmp = if let Some(tmp) = BITS
.wrapping_sub(char_digit.leading_zeros() as usize).checked_add(shl) {
if let Some(tmp) = tmp.checked_sub(log2) {
tmp
} else {
return Err(Overflow)
}
} else {
return Err(Overflow)
};
// check that the last digit did not cross the end
if tmp > self.bw() {
return Err(Overflow)
}
// there may be a bunch of leading zeros, so do not return an error yet
const_for!(j in {0..i} {
match src[j] {
b'_' | b'0' => (),
_ => return Err(Overflow)
}
});
break
}
});
if let Some(sign) = sign {
if sign {
if pad.lz() == 0 && !pad.is_imin() {
// These cannot be represented as negative
return Err(Overflow)
}
// handles `imin` correctly
pad.neg_(true);
} else if pad.lz() == 0 {
// These cannot be represented as positive
return Err(Overflow)
}
}
self.copy_(pad).unwrap();
Ok(())
}
/// Assigns to `self` the integer value represented by `src` in the given
/// `radix`. If `src` should be interpreted as unsigned, `sign` should be
/// `None`, otherwise it should be set to the sign. In order for this
/// function to be `const`, two scratchpads `pad0` and `pad1` with the
/// same bitwidth as `self` must be supplied, which can be mutated by
/// the function in arbitrary ways.
///
/// # Errors
///
/// `self` is not mutated if an error occurs. See [crate::SerdeError] for
/// error conditions. The characters `0..=9`, `a..=z`, and `A..=Z` are
/// allowed depending on the radix. The char `_` is ignored, and all
/// other chars result in an error. `src` cannot be empty. The value of
/// the string must be representable in the bitwidth of `self` with the
/// specified sign, otherwise an overflow error is returned.
#[const_fn(cfg(feature = "const_support"))]
pub const fn bytes_radix_(
&mut self,
sign: Option<bool>,
src: &[u8],
radix: u8,
pad0: &mut Self,
pad1: &mut Self,
) -> Result<(), SerdeError> {
if (self.bw() != pad0.bw()) || (self.bw() != pad1.bw()) {
return Err(NonEqualWidths)
}
if radix.is_power_of_two() {
return self.power_of_two_bytes_(sign, src, radix, pad0)
}
if let Err(e) = verify_for_bytes_(src, radix) {
return Err(e)
}
// the accumulator
pad0.zero_();
// contains the radix exponential
pad1.uone_();
const_for!(i in {0..src.len()}.rev() {
let b = src[i];
if b == b'_' {
continue;
}
let char_digit = if radix <= 10 || b <= b'9' {
b.wrapping_sub(b'0')
} else if b <= b'Z' {
b.wrapping_sub(b'A').wrapping_add(10)
} else {
b.wrapping_sub(b'a').wrapping_add(10)
} as Digit;
let o0 = pad0.digit_mul_add_(pad1, char_digit).unwrap();
if o0 {
return Err(Overflow)
}
let o1 = pad1.digit_cin_mul_(0, radix as Digit);
if o1 != 0 {
// there may be a bunch of leading zeros, so do not return an error yet
const_for!(j in {0..i} {
match src[j] {
b'_' | b'0' => (),
_ => return Err(Overflow)
}
});
break
}
});
if let Some(sign) = sign {
if sign {
if pad0.lz() == 0 && !pad0.is_imin() {
// These cannot be represented as negative
return Err(Overflow)
}
// handles `imin` correctly
pad0.neg_(true);
} else if pad0.lz() == 0 {
// These cannot be represented as positive
return Err(Overflow)
}
}
self.copy_(pad0).unwrap();
Ok(())
}
/// Assigns the `[u8]` representation of `self` to `dst` (sign indicators,
/// prefixes, and postfixes not included). `signed` specifies if `self`
/// should be interpreted as signed. `radix` specifies the radix, and
/// `upper` specifies if letters should be uppercase. In order for this
/// function to be `const`, a scratchpad `pad` with the same bitwidth as
/// `self` must be supplied. Note that if `dst.len()` is more than what
/// is needed to store the representation, the leading bytes will all be
/// set to b'0'.
///
/// # Errors
///
/// Note: If an error is returned, `dst` may be set to anything
///
/// This function can fail from `NonEqualWidths`, `InvalidRadix`, and
/// `Overflow` (if `dst` cannot represent the value of `self`). See
/// [crate::SerdeError].
#[const_fn(cfg(feature = "const_support"))]
pub const fn to_bytes_radix(
&self,
signed: bool,
dst: &mut [u8],
radix: u8,
upper: bool,
pad: &mut Self,
) -> Result<(), SerdeError> {
// there's going to be a lot of potential for downstream confusion if we do not
// check
self.assert_cleared_unused_bits();
if self.bw() != pad.bw() {
return Err(NonEqualWidths)
}
if radix < 2 || radix > 36 {
return Err(InvalidRadix)
}
pad.copy_(self).unwrap();
// happens to do the right thing to `imin`
pad.neg_(signed && pad.msb());
const_for!(i in {0..dst.len()}.rev() {
let rem = pad.digit_udivide_inplace_(radix as Digit).unwrap() as u8;
if rem < 10 {
dst[i] = b'0'.wrapping_add(rem);
} else if upper {
dst[i] = b'A'.wrapping_add(rem).wrapping_sub(10);
} else {
dst[i] = b'a'.wrapping_add(rem).wrapping_sub(10);
}
});
if !pad.is_zero() {
Err(Overflow)
} else {
Ok(())
}
}
/// Writes the bits content as hexadecimal to `f`, with underscores every 8
/// digits. I have decided on including the "0x" prefix and bitwidth suffix
/// always, because it is confusing in `assert_` debugging otherwise.
#[inline]
pub(crate) fn debug_format_hexadecimal(
&self,
f: &mut fmt::Formatter,
upper: bool,
) -> fmt::Result {
self.assert_cleared_unused_bits();
f.write_fmt(format_args!("0x"))?;
const_for!(j0 in {0..(self.bw() >> 2).wrapping_add(1)}.rev() {
if (self.get_digit(j0 << 2) & 0b1111) != 0 {
// we have reached the first nonzero character
const_for!(j1 in {0..j0.wrapping_add(1)}.rev() {
let mut char_digit = (self.get_digit(j1 << 2) & 0b1111) as u8;
if char_digit < 10 {
char_digit += b'0';
} else if upper {
char_digit += b'A'.wrapping_sub(10);
} else {
char_digit += b'a'.wrapping_sub(10);
}
// Safety: we strictly capped the range of possible values above with `& 0b1111`
let c = unsafe { char::from_u32_unchecked(char_digit as u32) };
f.write_fmt(format_args!("{c}"))?;
if ((j1 % 8) == 0) && (j1 != 0) {
f.write_fmt(format_args!("_"))?;
}
});
break
}
if j0 == 0 {
// we have reached the end without printing anything, print at least one '0'
f.write_fmt(format_args!("{}", '0'))?;
}
});
f.write_fmt(format_args!("_u{}", self.bw()))
}
#[inline]
pub(crate) fn debug_format_octal(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.assert_cleared_unused_bits();
f.write_fmt(format_args!("0o"))?;
const_for!(j0 in {0..(self.bw() / 3).wrapping_add(1)}.rev() {
if (self.get_digit(j0.wrapping_mul(3)) & 0b111) != 0 {
// we have reached the first nonzero character
const_for!(j1 in {0..j0.wrapping_add(1)}.rev() {
let mut char_digit = (self.get_digit(j1.wrapping_mul(3)) & 0b111) as u8;
char_digit += b'0';
// Safety: we strictly capped the range of possible values above with `& 0b111`
let c = unsafe { char::from_u32_unchecked(char_digit as u32) };
if let Err(e) = f.write_fmt(format_args!("{c}")) {
return Err(e)
}
if ((j1 % 8) == 0) && (j1 != 0) {
f.write_fmt(format_args!("_"))?;
}
});
break
}
if j0 == 0 {
// we have reached the end without printing anything, print at least one '0'
f.write_fmt(format_args!("{}", '0'))?;
}
});
f.write_fmt(format_args!("_u{}", self.bw()))
}
// TODO this could be optimized
#[inline]
pub(crate) fn debug_format_binary(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.assert_cleared_unused_bits();
f.write_fmt(format_args!("0b"))?;
const_for!(j0 in {0..self.bw()}.rev() {
if (self.get_digit(j0) & 0b1) != 0 {
// we have reached the first nonzero character
const_for!(j1 in {0..(j0 + 1)}.rev() {
let mut char_digit = (self.get_digit(j1) & 0b1) as u8;
char_digit += b'0';
// Safety: we strictly capped the range of possible values above with `& 0b1`
let c = unsafe { char::from_u32_unchecked(char_digit as u32) };
if let Err(e) = f.write_fmt(format_args!("{c}")) {
return Err(e)
}
if ((j1 % 8) == 0) && (j1 != 0) {
f.write_fmt(format_args!("_"))?;
}
});
break
}
if j0 == 0 {
// we have reached the end without printing anything, print at least one '0'
f.write_fmt(format_args!("{}", '0'))?;
}
});
f.write_fmt(format_args!("_u{}", self.bw()))
}
}