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
359
360
361
362
363
364
365
366
use radix::{Radix};
use apint::{ApInt};
use errors::{Error, Result};
use digit;

//  =======================================================================
///  Deserialization
/// =======================================================================
impl ApInt {
	/// Parses the given `input` `String` with the given `Radix` and returns an `ApInt`
	/// with the given `target_width` `BitWidth`.
	/// 
	/// **Note:** The given `input` is parsed as big-endian value. This means, the most significant bit (MSB)
	/// is the leftst bit in the string representation provided by the user.
	/// 
	/// The string is assumed to contain no whitespace and contain only values within a subset of the 
	/// range of `0`..`9` and `a`..`z` depending on the given `radix`.
	/// 
	/// The string is assumed to have no sign as `ApInt` does not handle signdness.
	/// 
	/// # Errors
	/// 
	/// - If `input` is empty.
	/// - If `input` is not a valid representation for an `ApInt` for the given `radix`.
	/// - If `input` has trailing zero characters (`0`), e.g. `"0042"` instead of `"42"`.
	/// - If `input` represents an `ApInt` value that does not fit into the given `target_bitwidth`.
	/// 
	/// # Examples
	/// 
	/// ```no_run
	/// # use apint::ApInt;
	/// let a = ApInt::from_str_radix(10, "42");      // ok
	/// let b = ApInt::from_str_radix( 2, "1011011"); // ok (dec. = 91)
	/// let c = ApInt::from_str_radix(16, "ffcc00");  // ok (dec. = 16763904)
	/// let c = ApInt::from_str_radix(10, "256");     // Error: 256 does not fit within 8 bits!
	/// let d = ApInt::from_str_radix( 2, "01020");   // Error: Invalid digit '2' at position 3 for given radix.
	/// let e = ApInt::from_str_radix(16, "hello");   // Error: "hello" is not a valid ApInt representation!
	/// ```
	pub fn from_str_radix<R, S>(radix: R, input: S) -> Result<ApInt>
		where R: Into<Radix>,
		      S: AsRef<str>
	{
		let radix = radix.into();
		let input = input.as_ref();

		if input.is_empty() {
			return Err(Error::invalid_string_repr(input, radix)
				.with_annotation("Cannot parse an empty string into an ApInt."))
		}
		if input.starts_with('_') {
			return Err(Error::invalid_string_repr(input, radix)
				.with_annotation("The input string starts with an underscore ('_') instead of a number. \
					              The use of underscores is explicitely for separation of digits."))
		}
		if input.ends_with('_') {
			return Err(Error::invalid_string_repr(input, radix)
				.with_annotation("The input string ends with an underscore ('_') instead of a number. \
					              The use of underscores is explicitely for separation of digits."))
		}

		// First normalize all characters to plain digit values.
		let mut v = Vec::with_capacity(input.len());
		for (i, b) in input.bytes().enumerate() {
			let d = match b {
				b'0'...b'9' => b - b'0',
				b'a'...b'z' => b - b'a' + 10,
				b'A'...b'Z' => b - b'A' + 10,
				b'_' => continue,
				_ => ::std::u8::MAX
			};
			if !radix.is_valid_byte(d) {
				return Err(Error::invalid_char_in_string_repr(input, radix, i, char::from(b)))
			}
			v.push(d);
		}

		let result = match radix.exact_bits_per_digit() {
			Some(bits) => {
				v.reverse();
				if digit::BITS % bits == 0 {
					ApInt::from_bitwise_digits(&v, bits)
				}
				else {
					ApInt::from_inexact_bitwise_digits(&v, bits)
				}
			}
			None => {
				ApInt::from_radix_digits(&v, radix)
			}
		};


		Ok(result)
	}

	// Convert from a power of two radix (bits == ilog2(radix)) where bits evenly divides
	// Digit::BITS.
	// 
	// Forked from: https://github.com/rust-num/num/blob/master/bigint/src/biguint.rs#L126
	// 
	// TODO: Better document what happens here and why.
	fn from_bitwise_digits(v: &[u8], bits: usize) -> ApInt {
		use digit;
		use digit::{DigitRepr, Digit};

	    debug_assert!(!v.is_empty() && bits <= 8 && digit::BITS % bits == 0);
	    debug_assert!(v.iter().all(|&c| DigitRepr::from(c) < (1 << bits)));

	    let radix_digits_per_digit = digit::BITS / bits;

	    let data = v.chunks(radix_digits_per_digit)
	                .map(|chunk| chunk.iter()
	                	              .rev()
	                	              .fold(0, |acc, &c| (acc << bits) | DigitRepr::from(c)))
	                .map(Digit);

	    ApInt::from_iter(data).unwrap()
	}

	// Convert from a power of two radix (bits == ilog2(radix)) where bits doesn't evenly divide
	// Digit::BITS.
	// 
	// Forked from: https://github.com/rust-num/num/blob/master/bigint/src/biguint.rs#L143
	// 
	// TODO: Better document what happens here and why.
	fn from_inexact_bitwise_digits(v: &[u8], bits: usize) -> ApInt {
		use digit;
		use digit::{DigitRepr, Digit};

	    debug_assert!(!v.is_empty() && bits <= 8 && digit::BITS % bits != 0);
	    debug_assert!(v.iter().all(|&c| (DigitRepr::from(c)) < (1 << bits)));

	    let len_digits = (v.len() * bits + digit::BITS - 1) / digit::BITS;
	    let mut data = Vec::with_capacity(len_digits);

	    let mut d = 0;
	    let mut dbits = 0; // Number of bits we currently have in d.

	    // Walk v accumulating bits in d; whenever we accumulate digit::BITS in d, spit out a digit:
	    for &c in v {
	        d |= (DigitRepr::from(c)) << dbits;
	        dbits += bits;

	        if dbits >= digit::BITS {
	            data.push(Digit(d));
	            dbits -= digit::BITS;
	            // If `dbits` was greater than `digit::BITS`, we dropped some of the bits in c
	            // (they couldn't fit in d) - grab the bits we lost here:
	            d = (DigitRepr::from(c)) >> (bits - dbits);
	        }
	    }

	    if dbits > 0 {
	        debug_assert!(dbits < digit::BITS);
	        data.push(Digit(d));
	    }

	    ApInt::from_iter(data).unwrap()
	}

	// Read little-endian radix digits.
	// 
	// Forked from: https://github.com/rust-num/num/blob/master/bigint/src/biguint.rs#L177
	// 
	// TODO: This does not work, yet. Some parts of the algorithm are
	//       commented-out since the required functionality does not exist, yet.
	fn from_radix_digits(v: &[u8], radix: Radix) -> ApInt {
		use digit;
		use digit::{DigitRepr, Digit};

	    debug_assert!(!v.is_empty() && !radix.is_power_of_two());
	    debug_assert!(v.iter().all(|&c| radix.is_valid_byte(c)));

	    // Estimate how big the result will be, so we can pre-allocate it.
	    let bits = (f64::from(radix.to_u8())).log2() * v.len() as f64;
	    let big_digits = (bits / digit::BITS as f64).ceil();
	    let mut data = Vec::with_capacity(big_digits as usize);

	    let (_base, power) = radix.get_radix_base();
	    let radix = DigitRepr::from(radix.to_u8());

	    let r = v.len() % power;
	    let i = if r == 0 {
	        power
	    } else {
	        r
	    };
	    let (head, tail) = v.split_at(i);

	    let first = head.iter().fold(0, |acc, &d| acc * radix + DigitRepr::from(d));
	    data.push(first);

	    debug_assert!(tail.len() % power == 0);
	    for chunk in tail.chunks(power) {
	        if data.last() != Some(&0) {
	            data.push(0);
	        }

	        let mut carry = 0;
	        for _d in &mut data {
	            // *d = mac_with_carry(0, *d, base, &mut carry); // TODO! This was commented out.

				// // fn carry_mul_add(a: Digit, b: Digit, c: Digit, carry: Digit) -> DigitAndCarry
				// // Returns the result of `(a + (b * c)) + carry` and its implied carry value.

	            // let DigitAndCarry(d, carry) = carry_mul_add(digit::ZERO, *d, base, carry); // TODO! This was commented out.
	        }
	        debug_assert!(carry == 0);

	        let _n = chunk.iter().fold(0, |acc, &d| acc * radix + DigitRepr::from(d));
	        // add2(&mut data, &[n]); // TODO: This was commented out.
	    }

	    ApInt::from_iter(data.into_iter().map(Digit)).unwrap()
	}
}

//  =======================================================================
///  Serialization
/// =======================================================================
impl ApInt {
	/// Returns a `String` representation of the binary encoded `ApInt` for the given `Radix`.
	pub fn as_string_with_radix<R>(&self, radix: R) -> String
		where R: Into<Radix>
	{
		let _radix = radix.into();

		unimplemented!();
	}
}

#[cfg(test)]
mod tests {
	use super::*;

	use bitwidth::{BitWidth};

	mod from_str_radix {

		use super::*;

		fn test_radices() -> impl Iterator<Item=Radix> {
			[2, 4, 8, 16, 32, 7, 10, 36].into_iter().map(|&r| Radix::new(r).unwrap())
		}

		fn test_pow2_radices() -> impl Iterator<Item=Radix> {
			[2, 4, 8, 16, 32].into_iter().map(|&r| Radix::new(r).unwrap())
		}

		#[test]
		fn empty() {
			for radix in test_radices() {
				assert_eq!(
					ApInt::from_str_radix(radix, ""),
					Err(Error::invalid_string_repr("", radix)
						.with_annotation("Cannot parse an empty string into an ApInt."))
				)
			}
		}

		#[test]
		fn starts_with_underscore() {
			for radix in test_radices() {
				for &input in &["_0", "_123", "__", "_1_0"] {
					assert_eq!(
						ApInt::from_str_radix(radix, input),
						Err(Error::invalid_string_repr(input, radix)
						    .with_annotation("The input string starts with an underscore ('_') instead of a number. \
						                      The use of underscores is explicitely for separation of digits."))
					)
				}
			}
		}

		#[test]
		fn ends_with_underscore() {
			for radix in test_radices() {
				for &input in &["0_", "123_", "1_0_"] {
					assert_eq!(
						ApInt::from_str_radix(radix, input),
						Err(Error::invalid_string_repr(input, radix)
						    .with_annotation("The input string ends with an underscore ('_') instead of a number. \
						                      The use of underscores is explicitely for separation of digits."))
					)
				}
			}
		}

		#[test]
		fn zero() {
			for radix in test_radices() {
				assert_eq!(
					ApInt::from_str_radix(radix, "0"),
					Ok(ApInt::zero(BitWidth::new(64).unwrap()))
				)
			}
		}

		#[test]
		fn small_values() {
			use std::u64;
			let samples = vec![
				// (Radix, Input String, Expected ApInt)

				( 2,  "0",  0),
				( 8,  "0",  0),
				(10,  "0",  0),
				(16,  "0",  0),

				( 2,  "1",  1),
				( 8,  "1",  1),
				(10,  "1",  1),
				(16,  "1",  1),

				( 2, "10",  2),
				( 8, "10",  8),
				(10, "10", 10),
				(16, "10", 16),

				( 2, "11",  3),
				( 8, "11",  9),
				(10, "11", 11),
				(16, "11", 17),

				( 2, "1001_0011", 0b1001_0011),
				( 2, "0001_0001_0001_0001", 0x1111),
				( 2, "0101_0101_0101_0101", 0x5555),
				( 2, "1010_1010_1010_1010", 0xAAAA),
				( 2, "1111_1111_1111_1111", 0xFFFF),
				( 2, "1111_1111_1111_1111\
					  1111_1111_1111_1111\
					  1111_1111_1111_1111\
					  1111_1111_1111_1111", u64::max_value()),

				( 8, "7654_3210", 0o7654_3210),
				( 8, "0123_4567", 0o0123_4567),
				( 8, "777_747_666", 0o777_747_666),
				( 8, "111", 0b001_001_001),
				( 8,  "7_7777_7777_7777_7777_7777", u64::max_value() / 2),
				// ( 8, "17_7777_7777_7777_7777_7777", u64::max_value()), // Does not work, yet! Should it work?

				(10, "100", 100),
				(10, "42", 42),
				(10, "1337", 1337),
				(10, "5_000_000", 5_000_000),
				// (10, "18_446_744_073_709_551_615", u64::max_value()), // Does not work, yet!

				(16, "100", 0x100),
				(16, "42", 0x42),
				(16, "1337", 0x1337),
				(16, "1111", 0x1111),
				(16, "5555", 0x5555),
				(16, "FFFF", 0xFFFF),
				(16, "0123_4567_89AB_CDEF", 0x0123_4567_89AB_CDEF),
				(16, "FEDC_BA98_7654_3210", 0xFEDC_BA98_7654_3210)
			];
			for sample in &samples {
				let radix = Radix::new(sample.0).unwrap();
				let input = sample.1;
				let result = ApInt::from_str_radix(radix, input).unwrap();
				let expected = ApInt::from_u64(sample.2);
				assert_eq!(result, expected)
			}
		}
	}
}