bitutils2/bit_field.rs
1use crate::bit_index::{BitIndex, BitIndexable};
2/*
3#[derive(Clone, Debug)]
4enum BitFieldConversionErrorKind {
5 TooLong,
6 TooShort
7}
8
9#[derive(Clone, Debug)]
10pub struct BitFieldConversionError {
11 kind: BitFieldConversionErrorKind
12}
13
14impl BitFieldConversionError {
15 fn new(kind: BitFieldConversionErrorKind) -> BitFieldConversionError {
16 BitFieldConversionError {kind}
17 }
18}
19
20impl std::fmt::Display for BitFieldConversionError {
21 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
22 match self.kind {
23 BitFieldConversionErrorKind::TooLong => write!(f, "Bitfield is too long for data type"),
24 BitFieldConversionErrorKind::TooShort => write!(f, "Bitfield is too short for data type"),
25 }
26 }
27}
28*/
29
30pub enum IntFormat {
31 Unsigned,
32 SignMagnitude,
33 OnesCompliment,
34 TwosCompliment,
35 BaseMinusTwo
36}
37
38/// Represents a method that can be used for padding a [`BitField`]
39pub enum BitPad {
40 /// Represents all-ones padding (i.e. 0xFF)
41 Ones,
42 /// Represents all-zeros padding (i.e. 0x00)
43 Zeros
44}
45
46impl BitPad {
47 /// Generates a [`BitField`] of the specified length using the padding method
48 /// specified by `self`.
49 ///
50 /// # Panics
51 /// Panics if `length` is negative
52 ///
53 /// # Examples
54 ///```rust
55 /// use bitutils2::{BitField, BitIndex, bx, BitPad};
56 ///
57 /// let bf = BitPad::Zeros.bit_field(bx!(2, 4));
58 /// assert_eq!(bf, BitField::from_hex_str("00 00 0"));
59 ///
60 /// let bf = BitPad::Ones.bit_field(bx!(2, 4));
61 /// assert_eq!(bf, BitField::from_hex_str("ff ff f"));
62 ///```
63 pub fn bit_field(&self, length: BitIndex) -> BitField {
64 if length.is_negative() {
65 panic!("Negative length supplied to BitPad::bit_field: {}", length);
66 }
67 match self {
68 BitPad::Ones => BitField::ones(length),
69 BitPad::Zeros => BitField::zeros(length)
70 }
71 }
72}
73
74
75/// Represents a finite array of contiguous bits that supports several operations such as
76/// indexing, slicing, shifting, etc.
77///
78/// The [`BitField`](crate::BitField) structure stores the bits packed in an array of bytes
79/// for memory efficiency, but attempts to make this mostly unapparant in the API. When a
80/// singular bit is accessed, it is returned as a u8 (either 0x00 or 0x01) to facilitate
81/// performing bitwise operations with the result.
82///
83/// # Examples
84/// ### Constructors
85///```rust
86/// use bitutils2::{BitField, BitIndex};
87///
88/// // Returns a bitfield with 0001 0010 0011 0100 0100 0101 0000 0000
89/// let bf1 = BitField::new(vec![0x12, 0x34, 0x45, 0x00], BitIndex::new(4, 0));
90/// // Returns a bitfield with 0001 0010 0011 0100 0100 0101 00. The bytes represented by the
91/// // vector are clipped to the bit index provided.
92/// let bf2 = BitField::new(vec![0x12, 0x34, 0x45, 0x00], BitIndex::new(3, 2));
93///
94/// // Returns the same bitfield as 'bf1' but automatically infers the length from
95/// // the provided vec. This constructor cannot be used to produce a bit field that
96/// // does not end on a byte boundary like 'bf2'
97/// let bf3 = BitField::from_vec(vec![0x12, 0x34, 0x45, 0x00]);
98///
99/// assert_eq!(bf1, bf3);
100/// assert_ne!(bf1, bf2); // bf1 and bf3 are not equal because they have different lengths
101///
102///
103/// // Returns a bitfield with 0001 0010 0011 0100 0100 0101 00 and an inferred length
104/// // of 3 bytes and 2 bits. This constructor can be used to create a bitfield of
105/// // any length. Spaces or underscores can be used anywhere in the input and are
106/// // ignored by the constructor.
107/// let bf4 = BitField::from_bin_str("0001 0010 0011 0100 0100 0101 00");
108///
109/// // bf5 has the same contents as bf4 but is two bits longer
110/// let bf5 = BitField::from_bin_str("0001 0010 0011 0100 0100 0101 0000");
111///
112/// assert_eq!(bf2, bf4); // bf2 and bf4 are equal in both length and contents
113/// assert_ne!(bf4, bf5); // bf4 and bf5 are not equal because they have different lengths
114///
115/// // Returns a bitfield with 0001 0010 0011 0100 0100 0101 0000 and an inferred length
116/// // of 3 bytes and 4 bits. This constructor can only be used to create bitfields witg
117/// // lengths that end on nibble boundaries. Spaces or underscores can be used anywhere
118/// // in the input and are ignored by the constructor.
119/// let bf6 = BitField::from_hex_str("12 34 45 0");
120///
121/// // bf7 has the same contents as bf6 but is four bits (one nibble) longer
122/// let bf7 = BitField::from_hex_str("12 34 45 00");
123///
124/// assert_eq!(bf5, bf6); // bf5 and bf6 are equal in both length and contents
125/// assert_eq!(bf3, bf7); // bf3 and bf7 are equal in both length and contents
126///
127/// // Returns a bitfield with 5 bytes of 0x00
128/// let bf8 = BitField::zeros(BitIndex::new(5, 0));
129///
130///
131///```
132/// ### Bitwise AND, OR, XOR, and NOT
133///
134/// The common bitwise operations (AND, OR, XOR, NOT) are supported. If the two sides have the same
135/// length, then the operation is applied to every bit in the arguments and the resulting
136/// [`BitField`](crate::BitField) is returned. If the two sides have different lengths, then
137/// The operation is only applied to bits up to the shortest length and the resulting
138/// [`BitField`](crate::BitField) is returned.
139///
140///```rust
141/// use bitutils2::{BitField, BitIndex};
142///
143/// // Initializing two bitfields that have the same length, and one that is much shorter
144/// let bf1 = BitField::from_bin_str("0011 1010 0000 1111 1100 0101 0111");
145/// let bf2 = BitField::from_bin_str("0101 0000 1100 0111 1010 1111 0001");
146/// let bf3 = BitField::from_bin_str("0101 0000 1100 01");
147///
148/// // Bitwise AND (&)
149/// assert_eq!(&bf1 & &bf2, BitField::from_bin_str("0001 0000 0000 0111 1000 0101 0001"));
150/// assert_eq!(&bf1 & &bf3, BitField::from_bin_str("0001 0000 0000 01"));
151///
152/// // Bitwise OR (|)
153/// assert_eq!(&bf1 | &bf2, BitField::from_bin_str("0111 1010 1100 1111 1110 1111 0111"));
154/// assert_eq!(&bf1 | &bf3, BitField::from_bin_str("0111 1010 1100 11"));
155///
156/// // Bitwise XOR (^)
157/// assert_eq!(&bf1 ^ &bf2, BitField::from_bin_str("0110 1010 1100 1000 0110 1010 0110"));
158/// assert_eq!(&bf1 ^ &bf3, BitField::from_bin_str("0110 1010 1100 10"));
159///
160/// // Bitwise NOT (!)
161/// assert_eq!(!&bf1, BitField::from_bin_str("1100 0101 1111 0000 0011 1010 1000"));
162/// assert_eq!(!&bf2, BitField::from_bin_str("1010 1111 0011 1000 0101 0000 1110"));
163/// assert_eq!(!&bf3, BitField::from_bin_str("1010 1111 0011 10"));
164///```
165#[derive(Clone, Debug)]
166pub struct BitField {
167 v: Vec<u8>,
168 length: BitIndex
169}
170
171impl BitField {
172
173 /// Returns a new [`BitField`](crate::BitField) structure with the contents of the vector `v`
174 /// interpreted as bytes and the length `length` in bits. If the length does not lie on a
175 /// byte boundary, it is expected that the vector will have a final element that specifies
176 /// the remaining bits.
177 ///
178 /// Panics if `length` is negative
179 ///
180 /// # Examples
181 ///```rust
182 /// use bitutils2::{BitField, BitIndex};
183 ///
184 /// let bf = BitField::new(vec![0b11001100, 0b01010101, 0b00110000], BitIndex::new(2, 4));
185 /// assert_eq!(bf, BitField::from_bin_str("1100 1100 0101 0101 0011"));
186 ///
187 /// let bf = BitField::new(vec![0b11001100, 0b01010101, 0b00110000], BitIndex::new(3, 0));
188 /// assert_eq!(bf, BitField::from_bin_str("1100 1100 0101 0101 0011 0000"));
189 ///```
190 pub fn new(v: Vec<u8>, length: BitIndex) -> BitField {
191 if length.is_negative() {
192 panic!("Negative length supplied to BitField::new: {}", length)
193 }
194 BitField {v, length}
195 }
196
197 /// Returns a [`BitField`](crate::BitField) structure with the contents of the vector `v`.
198 ///
199 /// The length of the bitfield is automatically calculated as the number of bits in the
200 /// input vector. To create a [`BitField`](crate::BitField) that is not an integral
201 /// number of bytes long, use the [`new`](crate::BitField::new) constructor.
202 ///
203 /// # Examples
204 ///```rust
205 /// use bitutils2::{BitField, BitIndex};
206 ///
207 /// let bf = BitField::from_vec(vec![0x00, 0xab, 0xff]);
208 /// assert_eq!(bf.len(), BitIndex::new(3, 0));
209 /// assert_eq!(bf, BitField::from_bin_str("0000 0000 1010 1011 1111 1111"));
210 ///```
211 pub fn from_vec(v: Vec<u8>) -> BitField {
212 let length = BitIndex::new(v.len(), 0);
213 BitField {v, length}
214 }
215
216 /// Creates and returns a [`BitField`](crate::BitField) of zeros (0x00) with the given length.
217 ///
218 /// # Panics:
219 /// Panics if `length` is negative
220 pub fn zeros(length: BitIndex) -> BitField {
221 if length.is_negative() {
222 panic!("Negative length supplied to BitField::zeros: {}", length)
223 }
224 let end = if length.is_byte_boundary() {length.byte()} else {length.byte() + 1};
225 BitField {v: vec![0; end], length}
226 }
227
228 /// Creates and returns a [`BitField`](crate::BitField) of ones (0xFF) with the given length.
229 ///
230 /// # Panics:
231 /// Panics if `length` is negative
232 pub fn ones(length: BitIndex) -> BitField {
233 if length.is_negative() {
234 panic!("Negative length supplied to BitField::ones: {}", length)
235 }
236 let mut v = Vec::<u8>::new();
237 if length.is_byte_boundary() {
238 v.resize(length.byte(), 0xff);
239 } else {
240 v.resize(length.byte() + 1, 0xff);
241 let last = (v[length.byte()] >> length.cbit()) << length.cbit();
242 v[length.byte()] = last;
243 }
244 BitField {v, length}
245 }
246
247 /// Parses a [`BitField`](crate::BitField) from a `str` of ones and zeros. Underscores and
248 /// spaces are allowed and are ignored. Panics if any other character is encountered
249 ///
250 /// # Panics:
251 /// Panics if `s` contains any character other than `0`, `1`, `_`, or ` `.
252 pub fn from_bin_str(s: &str) -> BitField {
253 let mut length = BitIndex::new(0, 0);
254 let mut byte = 0;
255 let mut v = Vec::<u8>::new();
256 for c in s.chars() {
257 match c {
258 '0' => {
259 length += 1;
260 },
261 '1' => {
262 byte += 0x01 << (7 - length.bit());
263 length += 1;
264 },
265 ' ' | '_' => continue,
266 _ => panic!("Encountered unexpected character when parsing binary: '{}'", c)
267 }
268 if length.is_byte_boundary() {
269 v.push(byte);
270 byte = 0;
271 }
272 }
273 if length.bit() != 0 {
274 v.push(byte);
275 }
276 BitField {v, length}
277 }
278
279 /// Parses a [`BitField`](crate::BitField) from a `str` of hex characters (`0-9`, `a-f`, or `A-F`).
280 /// Underscores and spaces are allowed and are ignored. Panics if any other character is encountered.
281 ///
282 /// # Panics:
283 /// Panics if `s` contains any character other than `0-9`, `a-f`, `A-F`, `_`, or ` `.
284 pub fn from_hex_str(s: &str) -> BitField {
285 let mut buffer = Vec::<u8>::new();
286 let mut left = true;
287 let mut n: u8 = 0;
288 for c in s.chars() {
289 match c {
290 '0'..='9' => {
291 if left {
292 n = ((c as u8) - 48) << 4;
293 } else {
294 buffer.push(n + ((c as u8) - 48));
295 n = 0;
296 }
297 },
298 'a'..='f' => {
299 if left {
300 n = ((c as u8) - 87) << 4;
301 } else {
302 buffer.push(n + ((c as u8) - 87));
303 n = 0;
304 }
305 },
306 'A'..='F' => {
307 if left {
308 n = ((c as u8) - 55) << 4;
309 } else {
310 buffer.push(n + ((c as u8) - 55));
311 n = 0;
312 }
313 },
314 '_' | ' ' => continue,
315 _ => panic!("Encountered unexpected character when parsing hex: '{}'", c)
316 }
317 left = !left;
318 }
319
320 let length = if left {
321 BitIndex::new(buffer.len(), 0)
322 } else {
323 buffer.push(n);
324 BitIndex::new(buffer.len() - 1, 4)
325 };
326
327 BitField {v: buffer, length}
328 }
329
330 pub fn to_bin_str(&self) -> String {
331 let mut s = "".to_string();
332 for b in &self.v {
333 s.push_str(&format!("{:>08b}", b))
334 }
335 return s[..(self.len().total_bits() as usize)].to_string()
336 }
337
338 /// Returns the length of `self` as a [`BitIndex`](crate::BitIndex).
339 pub fn len(&self) -> BitIndex {
340 self.length
341 }
342
343 /// Returns `true` if the length is zero and `false` otherwise
344 pub fn is_empty(&self) -> bool {
345 self.length.is_zero()
346 }
347
348 /// Deletes the contents of the [`BitField`](crate::BitField) and sets the length to 0.
349 pub fn clear(&mut self) {
350 self.v.clear();
351 self.length = BitIndex::new(0, 0);
352 }
353
354 /// Truncates the [`BitField`](crate::BitField) to `new_length` if `new_length` is shorter than
355 /// the current length. Does nothing otherwise.
356 ///
357 /// Panics if `new_length` is negative.
358 fn truncate(&mut self, new_length: BitIndex, be: bool) {
359 if self.length <= new_length {
360 return
361 }
362 if new_length.is_byte_boundary() {
363 self.v.truncate(new_length.byte());
364 } else {
365 self.v.truncate(new_length.byte() + 1);
366
367 // Take the MS bits if in big-endian and the LS bits if little-endian
368 let last = if be {
369 (self.v[new_length.byte()] >> new_length.cbit()) << new_length.cbit()
370 } else if new_length.byte() != self.length.byte() {
371 // Full byte is valid, so take the required LS bits
372 self.v[new_length.byte()] << new_length.cbit()
373 } else {
374 // Only part of the byte is valid, so need to shift the bits over
375 // to the LS position before taking the required bits
376 (self.v[new_length.byte()] >> self.length.cbit()) << new_length.cbit()
377 };
378
379 self.v[new_length.byte()] = last;
380 }
381 self.length = new_length;
382 }
383
384 /// Truncates the [`BitField`](crate::BitField) to `new_length` by retaining the
385 /// most-significant bits assuming a big-endian byte order if `new_length` is
386 /// shorter than the current length. Does nothing otherwise.
387 ///
388 /// Equivalent to [`truncate_le`](crate::BitField::truncate_le) if `new_length` is
389 /// on a byte boundary.
390 ///
391 /// Panics if `new_length` is negative.
392 ///
393 /// # Examples
394 ///```rust
395 /// use bitutils2::{BitField, BitIndex};
396 ///
397 /// let mut bf = BitField::from_bin_str("0101 1100 1111 0000 1010 1100");
398 /// // Most significant 2B6b -> ---- ---- ---- ---- ---- --
399 /// bf.truncate_be(BitIndex::new(2, 6));
400 ///
401 /// assert_eq!(bf, BitField::from_bin_str("0101 1100 1111 0000 1010 11"));
402 /// // Most significant 2B3b -> ---- ---- ---- ---- ---
403 /// bf.truncate_be(BitIndex::new(2, 3));
404 ///
405 /// assert_eq!(bf, BitField::from_bin_str("0101 1100 1111 0000 101"));
406 /// // Most significant 0B4b -> ----
407 /// bf.truncate_be(BitIndex::new(0, 4));
408 ///
409 /// assert_eq!(bf, BitField::from_bin_str("0101"));
410 ///
411 /// // Does nothing if new_length >= length
412 /// bf.truncate_be(BitIndex::new(1, 4));
413 /// assert_eq!(bf, BitField::from_bin_str("0101"));
414 ///```
415 pub fn truncate_be(&mut self, new_length: BitIndex) {
416 if new_length.is_negative() {
417 panic!("Negative length supplied to BitField::truncate_be: {}", new_length)
418 }
419 self.truncate(new_length, true);
420 }
421
422 /// Truncates the [`BitField`](crate::BitField) to `new_length` by retaining the
423 /// least-significant bits assuming a little-endian byte order if `new_length` is
424 /// shorter than the current length. Does nothing otherwise.
425 ///
426 /// Equivalent to [`truncate_be`](crate::BitField::truncate_be) if `new_length` is
427 /// on a byte boundary.
428 ///
429 /// Panics if `new_length` is negative.
430 ///
431 /// # Examples
432 ///```rust
433 /// use bitutils2::{BitField, BitIndex};
434 ///
435 /// let mut bf = BitField::from_bin_str("0101 1100 1111 0000 1010 1100");
436 /// // Least significant 2B6b -> ---- ---- ---- ---- -- ----
437 /// bf.truncate_le(BitIndex::new(2, 6));
438 ///
439 /// assert_eq!(bf, BitField::from_bin_str("0101 1100 1111 0000 1011 00"));
440 /// // Least significant 2B3b -> ---- ---- ---- ---- - --
441 /// bf.truncate_le(BitIndex::new(2, 3));
442 ///
443 /// assert_eq!(bf, BitField::from_bin_str("0101 1100 1111 0000 100"));
444 /// // Least significant 0B4b -> ----
445 /// bf.truncate_le(BitIndex::new(0, 4));
446 ///
447 /// assert_eq!(bf, BitField::from_bin_str("1100"));
448 ///
449 /// // Does nothing if new_length >= length
450 /// bf.truncate_le(BitIndex::new(1, 4));
451 /// assert_eq!(bf, BitField::from_bin_str("1100"));
452 ///```
453 pub fn truncate_le(&mut self, new_length: BitIndex) {
454 if new_length.is_negative() {
455 panic!("Negative length supplied to BitField::truncate_le: {}", new_length)
456 }
457 self.truncate(new_length, false);
458 }
459
460 /// Concatenates the argument onto the end of the [`BitField`](crate::BitField), adjusting the
461 /// length of the [`BitField`](crate::BitField) accordingly.
462 pub fn extend(&mut self, other: &BitField, be: bool) {
463 let new_length = self.length + other.length;
464
465 if other.is_empty() {
466 // Do nothing
467 } else if self.length.is_byte_boundary() {
468 self.v.extend(other.v.clone());
469 } else {
470 let cbit = self.length.cbit();
471
472 let mut carry = self.v.pop().unwrap();
473
474 if be {
475 for b in other.iter_bytes(true) {
476 self.v.push((b >> self.length.bit()) | carry);
477 carry = b << cbit;
478 }
479 } else {
480 carry >>= cbit;
481 for b in other.iter_bytes(false) {
482 self.v.push((b << self.length.bit()) | carry);
483 carry = b >> cbit;
484 }
485 }
486 if new_length.ceil().byte() > self.v.len() {
487 self.v.push(carry);
488 }
489
490 // Shift the bits in the last byte into the MSB position
491 if !be {
492 if let Some(last) = self.v.last_mut() {
493 let total_cbit = new_length.cbit() % 8;
494 *last <<= total_cbit;
495 }
496 }
497
498
499 }
500 self.length = new_length;
501 }
502
503 /// Iterates over the bytes of a [`BitField`](crate::BitField), from the least
504 /// significant to the most significant assuming little endian byte order.
505 ///
506 /// # Examples
507 ///```rust
508 /// use bitutils2::{BitField, BitIndex};
509 ///
510 /// let bf1 = BitField::from_bin_str("0101 1100 11");
511 /// let mut i = bf1.iter_bytes(false);
512 /// assert_eq!(i.next(), Some(0b01011100));
513 /// assert_eq!(i.next(), Some(0b11));
514 /// assert_eq!(i.next(), None);
515 ///```
516 pub fn iter_bytes(&self, ms: bool) -> Box<dyn Iterator<Item = u8> + '_> {
517 if self.length.is_byte_boundary() || ms {
518 Box::new(self.v.iter().cloned())
519 } else {
520 // Shift the last byte into the LS position
521 let cbit = self.length.cbit();
522 let n = self.length.byte();
523 Box::new(self.v.iter().take(n).cloned().chain(std::iter::once(self.v[n] >> cbit)))
524 }
525 }
526
527 /// Concatenates the argument onto the end of the [`BitField`](crate::BitField), adjusting the
528 /// length of the [`BitField`](crate::BitField) accordingly.
529 ///
530 /// # Examples
531 ///```rust
532 /// use bitutils2::{BitField, BitIndex};
533 ///
534 /// let mut bf1 = BitField::from_bin_str("0101 1100 11");
535 /// bf1.extend_be(&BitField::from_bin_str("0011 1010 0001"));
536 /// assert_eq!(bf1, BitField::from_bin_str("0101 1100 1100 1110 1000 01"));
537 ///```
538 pub fn extend_be(&mut self, other: &BitField) {
539 self.extend(other, true);
540 }
541
542 /// Concatenates the argument onto the end of the [`BitField`](crate::BitField), adjusting the
543 /// length of the [`BitField`](crate::BitField) accordingly.
544 ///
545 /// # Examples
546 ///```rust
547 /// use bitutils2::{BitField, BitIndex};
548 ///
549 /// let mut bf1 = BitField::from_bin_str("0101 1100 11");
550 /// // OPQR STUV MN
551 /// bf1.extend_le(&BitField::from_bin_str("0011 1010 0001"));
552 /// // EFGH IJKL ABCD
553 /// assert_eq!(bf1, BitField::from_bin_str("0101 1100 1110 1011 0001 00"));
554 /// // OPQR STUV GHIJ KLMN ABCD EF
555 ///```
556 pub fn extend_le(&mut self, other: &BitField) {
557 self.extend(other, false)
558 }
559
560 /// Repeats a [`BitField`](crate::BitField) `n` times. If `n` is zero, the bitfield is cleared and if `n` is one, the bitfield
561 /// is unmodified. Otherwise, the bitfield is extended such that it's contents repeat `n` times and its
562 /// length is multiplied by `n`.
563 fn repeat(&mut self, n: usize, be: bool) {
564 match n {
565 0 => self.clear(),
566 1 => (),
567 _ => {
568 let extra = self.clone();
569 for _ in 0..(n - 1) {
570 self.extend(&extra, be);
571 }
572 }
573 }
574 }
575
576 pub fn repeat_be(&mut self, n: usize) {
577 self.repeat(n, true)
578 }
579
580 pub fn repeat_le(&mut self, n: usize) {
581 self.repeat(n, false)
582 }
583
584 /// Extends `self` to the new provided length by repeating as many times as needed to fill the new length. Final repetition is
585 /// truncated to the specified length. If the specified length is less than `self`'s current length, then `self` is truncated
586 /// to the new length.
587 ///
588 /// # Panics
589 /// Panics if the provided length is negative or if `self` is empty
590 ///
591 /// # Examples
592 ///```rust
593 /// use bitutils2::{BitField, BitIndex};
594 ///
595 /// let mut bf = BitField::from_bin_str("0101 1100 11");
596 /// bf.repeat_until_be(BitIndex::new(5, 4));
597 /// assert_eq!(bf, BitField::from_bin_str("0101 1100 1101 0111 0011 0101 1100 1101 0111 0011 0101"));
598 ///
599 /// // If the new length is less than the current length, then self is truncated.
600 /// bf.repeat_until_be(BitIndex::new(0, 6));
601 /// assert_eq!(bf, BitField::from_bin_str("0101 11"));
602 ///```
603 pub fn repeat_until_be(&mut self, new_length: BitIndex) {
604 if new_length.is_negative() {
605 panic!("Negative length supplied to BitField::repeat_until_be: {}", new_length);
606 }
607 if self.is_empty() {
608 panic!("BitField::repeat_until_be called on empty BitField")
609 }
610 let n = new_length / &self.length;
611
612 self.repeat_be(n as usize + 1);
613 self.truncate_be(new_length);
614
615 }
616
617 pub fn repeat_until_le(&mut self, new_length: BitIndex) {
618 if new_length.is_negative() {
619 panic!("Negative length supplied to BitField::repeat_until_le: {}", new_length);
620 }
621 if self.is_empty() {
622 panic!("BitField::repeat_until_le called on empty BitField")
623 }
624 let n = new_length / &self.length;
625
626 self.repeat_le(n as usize + 1);
627 self.truncate_le(new_length);
628
629 }
630
631 /// Finds the index of the first `1` bit in `self`. Returns None if
632 /// there are no zeros in `self` or if `self` is empty.
633 ///
634 /// # Examples
635 ///```rust
636 /// use bitutils2::{BitField, BitIndex};
637 ///
638 /// let bf = BitField::from_bin_str("0000 0101 1100 1100 0000");
639 /// assert_eq!(bf.find_first_one().unwrap(), BitIndex::bits(5));
640 /// let bf = BitField::from_bin_str("1000 0101 1100 1100 0000");
641 /// assert_eq!(bf.find_first_one().unwrap(), BitIndex::bits(0));
642 /// let bf = BitField::from_bin_str("0000 0000 0000 0000 0000 0000");
643 /// assert!(bf.find_first_one().is_none());
644 /// let bf = BitField::from_vec(vec![]);
645 /// assert!(bf.find_first_one().is_none());
646 ///```
647 pub fn find_first_one(&self) -> Option<BitIndex> {
648 self.v.iter().enumerate().find_map(|(i, b)| {
649 if *b == 0 {
650 None
651 } else {
652 let mut b = *b;
653 let mut bit = 8;
654 while b > 0 {
655 b >>= 1;
656 bit -= 1;
657 }
658 Some(BitIndex::new(i, bit))
659 }
660 })
661 }
662
663 /// Finds the index of the next `1` bit in `self`, starting from and including the
664 /// provided start index. Returns None if there are no zeros in `self`
665 /// after or including `start` or if `self` is empty.
666 ///
667 /// # Examples
668 ///```rust
669 /// use bitutils2::{BitField, BitIndex};
670 ///
671 /// let mut bf = BitField::from_bin_str("0101 1100 1100 0000 0000 0010 0001 0000 0000");
672 /// assert_eq!(bf.find_next_one(BitIndex::zero()).unwrap(), BitIndex::bits(1));
673 /// assert_eq!(bf.find_next_one(BitIndex::bits(1)).unwrap(), BitIndex::bits(1));
674 /// assert_eq!(bf.find_next_one(BitIndex::bits(11)).unwrap(), BitIndex::bits(22));
675 /// assert!(bf.find_next_one(BitIndex::bits(29)).is_none());
676 /// assert!(bf.find_next_one(BitIndex::bits(100)).is_none());
677 ///```
678 pub fn find_next_one(&self, start: BitIndex) -> Option<BitIndex> {
679 self.v.iter().enumerate().skip(start.byte()).find_map(|(i, b)| {
680 if *b == 0 {
681 None
682 } else {
683 let mut b = *b;
684 let mut bit = 8;
685 if i == start.byte() {
686 b <<= start.bit();
687 if b == 0 {
688 return None
689 }
690 b >>= start.bit()
691 }
692 while b > 0 {
693 b >>= 1;
694 bit -= 1;
695 }
696 Some(BitIndex::new(i, bit))
697 }
698 })
699 }
700
701 /// Inserts the bits specified in `new` to the right of `self`, shifting the
702 /// existing contents of `self` left to accommodate the new data without changing
703 /// `self`'s length. If `new` is longer than `self`, then `self` will be overwritten
704 /// with the rightmost data in `new`.
705 ///
706 /// # Examples
707 ///```rust
708 /// use bitutils2::{BitField, BitIndex};
709 ///
710 /// let mut bf = BitField::from_bin_str("0101 1100 1100 0011 1010");
711 ///
712 /// // When new is shorter than self, self's data is left shifted by new's length
713 /// bf.shove_left(&BitField::from_bin_str("1101 00"));
714 /// assert_eq!(bf, BitField::from_bin_str("0011 0000 1110 1011 0100"));
715 ///
716 /// // When new is the same length as self, self is overwritten with the data in new
717 /// bf.shove_left(&BitField::from_bin_str("0101 1010 1101 0011 1100"));
718 /// assert_eq!(bf, BitField::from_bin_str("0101 1010 1101 0011 1100"));
719 ///
720 /// // When new is longer than self, self is overwritten with the rightmost data in new
721 /// bf.shove_left(&BitField::from_bin_str("1100 0011 1001 0110 0101 1100"));
722 /// assert_eq!(bf, BitField::from_bin_str("0011 1001 0110 0101 1100"));
723 ///```
724 pub fn shove_left(&mut self, new: &BitField) {
725 if new.len() < self.len() {
726 *self <<= new.len();
727 self.truncate_be(self.len() - new.len());
728 self.extend_be(new);
729 } else if new.len() > self.len() {
730 *self = new.bit_slice(&(new.len() - self.len()), &new.len());
731 } else {
732 *self = new.clone();
733 }
734 }
735
736 /// Inserts the bits specified in `new` to the left of `self`, shifting the
737 /// existing contents of `self` right to accommodate the new data without changing
738 /// `self`'s length. If `new` is longer than `self`, then `self` will be overwritten
739 /// with the leftmost data in `new`.
740 ///
741 /// # Examples
742 ///```rust
743 /// use bitutils2::{BitField, BitIndex};
744 ///
745 /// let mut bf = BitField::from_bin_str("0101 1100 1100 0011 1010");
746 ///
747 /// // When new is shorter than self, self's data is right shifted by new's length
748 /// bf.shove_right(BitField::from_bin_str("1101 00"));
749 /// assert_eq!(bf, BitField::from_bin_str("1101 0001 0111 0011 0000"));
750 ///
751 /// // When new is the same length as self, self is overwritten with the data in new
752 /// bf.shove_right(BitField::from_bin_str("0101 1010 1101 0011 1100"));
753 /// assert_eq!(bf, BitField::from_bin_str("0101 1010 1101 0011 1100"));
754 ///
755 /// // When new is longer than self, self is overwritten with the leftmost data in new
756 /// bf.shove_right(BitField::from_bin_str("1100 0011 1001 0110 0101 1100"));
757 /// assert_eq!(bf, BitField::from_bin_str("1100 0011 1001 0110 0101"));
758 ///```
759 pub fn shove_right(&mut self, mut new: BitField) {
760 if new.len() < self.len() {
761 self.truncate_be(self.len() - new.len());
762 std::mem::swap(self, &mut new);
763 self.extend_be(&new);
764 } else if new.len() > self.len() {
765 new.truncate_be(self.len());
766 std::mem::swap(self, &mut new);
767 } else {
768 *self = new;
769 }
770 }
771
772 /// Returns a slice of `self` that may extend beyond the length of `self`. The returned
773 /// slice will be padded according to the provided `pad` parameter. If both `start` and
774 /// `end` are less than `self`'s length, this is equivalant to
775 /// [`bit_slice`](crate::BitField::bit_slice). If both `start` and `end` are greater than
776 /// `self`'s length, then the return value is entirely comprised of padding.
777 ///
778 /// #Panics
779 /// Panics if `end` is less than `start` or if either is negative.
780 ///
781 /// # Examples
782 ///```rust
783 /// use bitutils2::{BitField, BitIndex, BitPad};
784 ///
785 /// let bf = BitField::from_bin_str("0101 1100 1100 0011 1010");
786 ///
787 /// // When the slice is contained within the bitfield, no padding is done.
788 /// let slice_zeros = bf.slice_with_rpad(&BitIndex::new(0, 4), &BitIndex::new(2, 2), BitPad::Zeros);
789 /// let slice_ones = bf.slice_with_rpad(&BitIndex::new(0, 4), &BitIndex::new(2, 2), BitPad::Ones);
790 /// assert_eq!(slice_zeros, BitField::from_bin_str("1100 1100 0011 10"));
791 /// assert_eq!(slice_ones , BitField::from_bin_str("1100 1100 0011 10"));
792 ///
793 /// // When the slice is partially contained within the bitfield, then the remaining
794 /// // portion will be filled in with padding.
795 /// let slice_zeros = bf.slice_with_rpad(&BitIndex::new(1, 2), &BitIndex::new(3, 4), BitPad::Zeros);
796 /// let slice_ones = bf.slice_with_rpad(&BitIndex::new(1, 2), &BitIndex::new(3, 4), BitPad::Ones);
797 /// assert_eq!(slice_zeros, BitField::from_bin_str("0000 1110 1000 0000 00"));
798 /// assert_eq!(slice_ones , BitField::from_bin_str("0000 1110 1011 1111 11"));
799 ///
800 /// // When the slice is fully beyond the bitfield, then the entire slice will be filled in with padding.
801 /// let slice_zeros = bf.slice_with_rpad(&BitIndex::new(2, 4), &BitIndex::new(3, 6), BitPad::Zeros);
802 /// let slice_ones = bf.slice_with_rpad(&BitIndex::new(2, 4), &BitIndex::new(3, 6), BitPad::Ones);
803 /// assert_eq!(slice_zeros, BitField::from_bin_str("0000 0000 00"));
804 /// assert_eq!(slice_ones , BitField::from_bin_str("1111 1111 11"));
805 ///```
806 pub fn slice_with_rpad(&self, start: &BitIndex, end: &BitIndex, pad: BitPad) -> BitField {
807 if *end > self.len() {
808 if *start >= self.len() {
809 pad.bit_field(end - start)
810 } else {
811 let mut slice = self.bit_slice(start, &self.len());
812 slice.extend_be(&pad.bit_field(end - &self.len()));
813 slice
814 }
815 } else {
816 self.bit_slice(start, end)
817 }
818 }
819
820 /// Returns a slice of `self` that may extend beyond the contents of `self` in the positive and/or
821 /// negative directions. The returned slice will be padded to the left (in the case of a negative
822 /// `start` index) according to the `lpad` parameter, and to the right (in the case of a `end` index
823 /// that is greater than `self`'s length) according to the provided `rpad` parameter. If neither `start`
824 /// nor `end` are negative, then this is equivalent in function to [`slice_with_rpad`](crate::BitField::slice_with_rpad)
825 ///
826 /// # Panics
827 /// Panics if `end` is less than `start`.
828 ///
829 /// # Examples
830 ///```rust
831 /// use bitutils2::{BitField, BitIndex, BitPad};
832 ///
833 /// let bf = BitField::from_bin_str("0101 1100 1100 0011 1010");
834 ///
835 /// // When the slice is contained within the bitfield, no padding is done.
836 /// let slice_l0_r1 = bf.slice_with_pad(&BitIndex::new(0, 4), &BitIndex::new(2, 2), BitPad::Zeros, BitPad::Ones);
837 /// let slice_r0_l1 = bf.slice_with_pad(&BitIndex::new(0, 4), &BitIndex::new(2, 2), BitPad::Ones, BitPad::Zeros);
838 /// assert_eq!(slice_l0_r1, BitField::from_bin_str("1100 1100 0011 10"));
839 /// assert_eq!(slice_r0_l1, BitField::from_bin_str("1100 1100 0011 10"));
840 ///
841 /// // When the slice is partially contained within the bitfield, then the remaining
842 /// // portion will be filled in with padding.
843 /// let slice_l0_r1 = bf.slice_with_pad(&BitIndex::new(1, 2), &BitIndex::new(3, 4), BitPad::Zeros, BitPad::Ones);
844 /// let slice_r0_l1 = bf.slice_with_pad(&BitIndex::new(1, 2), &BitIndex::new(3, 4), BitPad::Ones, BitPad::Zeros);
845 ///
846 /// assert_eq!(slice_l0_r1, BitField::from_bin_str("0000 1110 10 11 1111 11"));
847 /// assert_eq!(slice_r0_l1, BitField::from_bin_str("0000 1110 10 00 0000 00"));
848 /// // \----------/ \--------/
849 /// // from bf from rpad
850 ///
851 /// // When the slice starts at a negative index, then that portion will be filled in with padding.
852 /// let slice_l0_r1 = bf.slice_with_pad(&-BitIndex::new(1, 2), &BitIndex::new(3, 4), BitPad::Zeros, BitPad::Ones);
853 /// let slice_r0_l1 = bf.slice_with_pad(&-BitIndex::new(1, 2), &BitIndex::new(3, 4), BitPad::Ones, BitPad::Zeros);
854 ///
855 /// assert_eq!(slice_l0_r1, BitField::from_bin_str("00 0000 0000 0101 1100 1100 0011 1010 1111 1111"));
856 /// assert_eq!(slice_r0_l1, BitField::from_bin_str("11 1111 1111 0101 1100 1100 0011 1010 0000 0000"));
857 /// // \----------/ \----------------------/ \--------/
858 /// // from lpad from bf from rpad
859 ///
860 /// // When the slice is fully negative, then it will be filled in completely with rpad
861 /// let slice_l0_r1 = bf.slice_with_pad(&-BitIndex::new(1, 2), &-BitIndex::new(0, 2), BitPad::Zeros, BitPad::Ones);
862 /// let slice_r0_l1 = bf.slice_with_pad(&-BitIndex::new(1, 2), &-BitIndex::new(0, 2), BitPad::Ones, BitPad::Zeros);
863 ///
864 /// assert_eq!(slice_l0_r1, BitField::from_bin_str("0000 0000"));
865 /// assert_eq!(slice_r0_l1, BitField::from_bin_str("1111 1111"));
866 /// // \-------/
867 /// // from lpad
868 ///```
869 pub fn slice_with_pad(&self, start: &BitIndex, end: &BitIndex, lpad: BitPad, rpad: BitPad) -> BitField {
870 if start.is_negative() {
871 if end.is_negative() {
872 lpad.bit_field(end - start)
873 } else {
874 let mut slice = lpad.bit_field(start.abs());
875 slice.extend_be(&self.slice_with_rpad(&BitIndex::zero(), end, rpad));
876 slice
877 }
878
879 } else {
880 self.slice_with_rpad(start, end, rpad)
881 }
882 }
883
884 /// Calculates the CRC of `self` using the provided initial value and
885 /// polynomial assuming big-endian bit order. Note that the polynomial paramter
886 /// must not include the leading 1.
887 ///
888 /// Panics if the `initial` and `polynomial` parameters are different lengths.
889 pub fn crc_be(&self, initial: BitField, polynomial: BitField) -> BitField {
890 let n = polynomial.len();
891 if initial.len() != n {
892 panic!("Length of 'initial' must be equal to length of 'polynomial'")
893 }
894 let mut current = BitIndex::zero();
895 let mut slice = self.slice_with_rpad(&BitIndex::zero(), &n, BitPad::Zeros);
896
897 slice ^= &initial;
898
899 // let mut next = None;
900 loop {
901 loop {
902
903 // Look for the next non-zero bit
904 match slice.find_first_one() {
905 None => {
906 let slice_end = current + n;
907 if slice_end > self.len() {
908
909 slice.shove_left(&BitField::zeros(slice_end - self.len()));
910 return slice
911 } else {
912 current = slice_end;
913 }
914 break;
915 },
916 Some(offset) => {
917 let offset = offset + 1;
918 if current + offset > self.len() {
919 slice.shove_left(&BitField::zeros(self.len() - current));
920 return slice
921 }
922 let slice_end = current + n;
923
924 slice.shove_left(&self.slice_with_rpad(&slice_end, &(slice_end + offset), BitPad::Zeros));
925
926 slice ^= &polynomial;
927 current += offset;
928 }
929 }
930 }
931
932 // Find the next non-zero bit if one exists
933 match self.find_next_one(current) {
934 None => {
935 let slice_end = current + n;
936 if slice_end > self.len() {
937 slice.shove_left(&BitField::zeros(slice_end - self.len()));
938 return slice
939 } else {
940 return BitField::zeros(n)
941 }
942 },
943 Some(next) => {
944 current = next + 1;
945 let slice_end = current + n;
946 slice = self.slice_with_rpad(¤t, &slice_end, BitPad::Zeros);
947 slice ^= &polynomial;
948 }
949 }
950 }
951 }
952
953 /// Swaps the byte order of `self` from litte-endian to big-endian. Does nothing
954 /// if `self` is less than or equal to one byte long. Note that in the case of
955 /// a [`BitField`](crate::BitField) that does not end on a byte coundary, this
956 /// method is not equivalent to [`swap_be_to_le`](crate::BitField::swap_be_to_le).
957 /// This method will always undo the effect of [`swap_be_to_le`](crate::BitField::swap_be_to_le)
958 /// and vice-versa.
959 ///
960 /// # Examples
961 ///```rust
962 /// use bitutils2::{BitField, BitIndex};
963 ///
964 /// let mut bf = BitField::from_bin_str("0101 1100 0110 1001 011");
965 /// bf.swap_le_to_be();
966 /// assert_eq!(bf, BitField::from_bin_str("0110 1101 0010 1011 100"));
967 ///```
968 pub fn swap_le_to_be(&mut self) {
969 if self.length.ceil().byte() <= 1 {
970 return
971 }
972 self.v.reverse();
973 if !self.length.is_byte_boundary() {
974 self.v[0] >>= self.length.cbit();
975 for i in 0..self.v.len() {
976 self.v[i] <<= self.length.cbit();
977 if i + 1 < self.v.len() {
978 self.v[i] |= self.v[i + 1] >> self.length.bit();
979 }
980 }
981 }
982 }
983
984 /// Swaps the byte order of `self` from big-endian to little-endian. Does nothing
985 /// if `self` is less than or equal to one byte long. Note that in the case of
986 /// a [`BitField`](crate::BitField) that does not end on a byte coundary, this
987 /// method is not equivalent to [`swap_le_to_be`](crate::BitField::swap_le_to_be).
988 /// This method will always undo the effect of [`swap_le_to_be`](crate::BitField::swap_le_to_be)
989 /// and vice-versa.
990 ///
991 /// # Examples
992 ///```rust
993 /// use bitutils2::{BitField, BitIndex};
994 ///
995 /// let mut bf = BitField::from_bin_str("0101 1100 0110 1001 011");
996 ///
997 /// bf.swap_be_to_le(); // "0101 1100 0110 1001 011"
998 /// assert_eq!(bf, BitField::from_bin_str("0100 1011 1110 0011 010"));
999 ///```
1000 pub fn swap_be_to_le(&mut self) {
1001 if self.length.ceil().byte() <= 1 {
1002 return
1003 }
1004 self.v.reverse();
1005 if !self.length.is_byte_boundary() {
1006 for i in 0..self.v.len() {
1007 self.v[i] >>= self.length.cbit();
1008 if i + 1 < self.v.len() {
1009 self.v[i] |= self.v[i + 1] << self.length.bit();
1010 } else {
1011 self.v[i] <<= self.length.cbit();
1012 }
1013 }
1014 }
1015 }
1016
1017 /// Maps a [`BitIndex`](crate::BitIndex) that corresponds to a big-endian location
1018 /// in `self` to one that corresponds to the same bit if self were little-endian.
1019 ///
1020 /// # Examples
1021 ///```rust
1022 /// use bitutils2::{BitField, BitIndex, BitIndexable};
1023 ///
1024 /// let mut bf = BitField::from_bin_str("0101 1100 0110 1001 011");
1025 /// let mut bf2 = bf.clone();
1026 ///
1027 /// bf2.swap_be_to_le();
1028 /// for i in 0..19 {
1029 /// let bi1 = BitIndex::bits(i);
1030 /// let bi2 = bf.map_be_to_le(&bi1);
1031 /// println!("New Index: {:?}", bi2);
1032 /// assert_eq!(bf.bit_at(&bi1), bf2.bit_at(&bi2));
1033 /// }
1034 ///
1035 /// let mut bf = BitField::from_bin_str("0101 1100 0110 1001 0110 1001");
1036 /// let mut bf2 = bf.clone();
1037 ///
1038 /// bf2.swap_be_to_le();
1039 /// for i in 0..24 {
1040 /// let bi1 = BitIndex::bits(i);
1041 /// let bi2 = bf.map_be_to_le(&bi1);
1042 /// println!("New Index: {:?}", bi2);
1043 /// assert_eq!(bf.bit_at(&bi1), bf2.bit_at(&bi2));
1044 /// }
1045 ///```
1046 pub fn map_be_to_le(&self, index: &BitIndex) -> BitIndex {
1047 println!("Length: {:?}, index: {:?}", self.length, index);
1048 let b = self.length.ceil().byte() - index.byte();
1049 println!("b: {}", b);
1050 if self.length.is_byte_boundary() {
1051 // If the length is an even number of bytes, just return the same bit
1052 // in whatever byte corresponds to the given index after converting
1053 // endianness.
1054 BitIndex::new(b - 1, index.bit())
1055 } else {
1056 if index.bit() < self.length.bit() {
1057 if b == self.length.ceil().byte() {
1058 BitIndex::new(b - 1, index.bit())
1059 } else {
1060 let bit = index.bit() + self.length.cbit();
1061 BitIndex::new(b + (bit >> 3) as usize - 1, bit & 0x07)
1062 }
1063
1064 } else {
1065 BitIndex::new(b - 2, index.bit() - self.length.bit())
1066 }
1067 }
1068 }
1069
1070 pub fn extract_u8(&self, start: BitIndex) -> u8 {
1071 if start.is_byte_boundary() {
1072 self.v[start.byte()]
1073 } else {
1074 (self.v[start.byte()] << start.bit()) | (self.v[start.byte() + 1] >> start.cbit())
1075 }
1076 }
1077
1078 pub fn extract_u8_cyclical(&self, start: BitIndex) -> u8 {
1079 if self.length.byte() == 0 {
1080 // TODO: This is a stupid implementation
1081 let mut r = self.clone();
1082 r.repeat_be(8);
1083 return r.extract_u8_cyclical(start)
1084 }
1085 let start = start.rem_euclid(&self.length);
1086 let i = start.byte();
1087 if start.is_byte_boundary() {
1088 if i == self.length.byte() {
1089 // If the 8-bit span starts on the partial byte at the end of the field, we need
1090 // to grab some bits from the start.
1091 self.v[start.byte()] | self.v[0] >> self.length.bit()
1092 } else {
1093 self.v[start.byte()]
1094 }
1095 } else {
1096 let res = self.v[start.byte()] << start.bit();
1097 let last_byte = if self.length.is_byte_boundary() {
1098 self.length.byte() - 1
1099 } else {
1100 self.length.byte()
1101 };
1102 if i == last_byte {
1103 // 0101 0011 1010 0011 010
1104 // ---- -- ^-
1105 if self.length.is_byte_boundary() {
1106 res | (self.v[0] >> (8 - start.bit()))
1107 } else {
1108 res | (self.v[0] >> (self.length.bit() - start.bit()))
1109 }
1110
1111 } else {
1112 let next_byte = self.v[start.byte() + 1] >> start.cbit();
1113 if start + BitIndex::new(1, 0) > self.length {
1114 //let diff = start + BitIndex::new(1, 0) - self.length;
1115 let shift = start.cbit() + self.length.bit();
1116 let first_byte = self.v[0] >> shift;//diff.cbit();
1117 res | next_byte | first_byte
1118 } else {
1119 res | next_byte
1120 }
1121 }
1122 }
1123 }
1124
1125 /// Converts `self` into a boxed slice, where each element represents a byte. Returns `Err`
1126 /// if `self` does not end on a byte boundary and `Ok` otherwise. This function is helpful
1127 /// in converting from a [`BitField`] to other variable-length types such as [`str`](std::str)
1128 /// or [`Vec`](std::vec::Vec).
1129 ///
1130 /// # Example:
1131 ///```rust
1132 /// use bitutils2::{BitField, BitIndex, BitIndexable};
1133 ///
1134 /// // If self ends on a byte boundary, then into_boxed_slice is a useful way
1135 /// // to convert to other variable-length types such as str.
1136 /// let bf = BitField::from_hex_str("48 65 6C 6C 6F 20 57 6F 72 6C 64 21");
1137 /// let boxed_slice = bf.into_boxed_slice().unwrap();
1138 /// let s = std::str::from_utf8(&boxed_slice).unwrap();
1139 /// assert_eq!(s, "Hello World!");
1140 ///
1141 /// // If self does not end on a byte boundary, into_boxed_slice returns Err.
1142 /// let bf = BitField::from_bin_str("0101 1100 1111");
1143 /// assert!(bf.into_boxed_slice().is_err());
1144 ///
1145 ///```
1146 pub fn into_boxed_slice(self) -> Result<Box<[u8]>, ()> {
1147 if self.length.is_byte_boundary() {
1148 Ok(self.v.into_boxed_slice())
1149 } else {
1150 Err(())
1151 }
1152 }
1153
1154 /// Converts `self` into a byte array. Returns `Err` if `self` does not end on a byte boundary
1155 /// or is the wrong length for the destination type and `Ok` otherwise. This function is helpful
1156 /// in converting from a [`BitField`] to fixed-length types such as integers or floats.
1157 ///
1158 /// # Example:
1159 ///```rust
1160 /// use bitutils2::{BitField, BitIndex, BitIndexable};
1161 ///
1162 /// // If self ends on a byte boundary, then into_array is a useful way
1163 /// // to convert to fixed-length types such as u16.
1164 /// let bf = BitField::from_hex_str("AB CD");
1165 /// let arr = bf.into_array().unwrap();
1166 /// let n = u16::from_be_bytes(arr);
1167 /// assert_eq!(n, 0xABCD);
1168 ///
1169 /// // If self does not end on a byte boundary, into_array returns Err.
1170 /// let bf = BitField::from_bin_str("0101 1100 1111");
1171 /// assert!(bf.into_array::<2>().is_err());
1172 ///
1173 /// // If self is the wrong length for the destination type, into_array returns Err.
1174 /// let bf = BitField::from_bin_str("0101 1100 1111 0000");
1175 /// assert!(bf.into_array::<4>().is_err());
1176 ///
1177 ///```
1178 pub fn into_array<const N: usize>(self) -> Result<[u8; N], ()> {
1179 let boxed_slice = self.into_boxed_slice()?;
1180 match <Box<[u8]> as TryInto<Box<[u8; N]>>>::try_into(boxed_slice) {
1181 Ok(a) => Ok(*a),
1182 Err(_) => Err(())
1183 }
1184 }
1185
1186 /// Returns the specified slice of `self` assuming that `self` is in a big-endian
1187 /// format. The bits in the slice are arranged in such a way that their relative
1188 /// magnitude is preserved when interpreted as a big-endian byte array. Equivalent
1189 /// to the [`bit_slice`](crate::BitIndexable::bit_slice) implementation for this type.
1190 pub fn slice_be(&self, start: &BitIndex, end: &BitIndex) -> BitField {
1191 self.bit_slice(start, end)
1192 }
1193
1194 /// Returns the specified slice of `self` assuming that `self` is in a little-endian
1195 /// format. The bits in the slice are arranged in such a way that their relative
1196 /// magnitude is preserved when interpreted as a little-endian byte array. If `start`
1197 /// is not byte-aligned, then the most significant bits from the `start` byte are
1198 /// included in the slice, and if `end` is not byte-aligned, then the least significant
1199 /// bits from the `end` byte are included in the slice.
1200 ///
1201 /// # Panics
1202 /// Panics if `start` or `end` is negative, `start` is greater than `end`, or `end` is
1203 /// greater than `self`'s length.
1204 ///
1205 /// # Example
1206 ///```rust
1207 /// use bitutils2::{BitField, BitIndex};
1208 ///
1209 /// let mut bf = BitField::from_bin_str("0101 1100 1010 0110 0101 1001 1011 0000");
1210 /// // CBA KJIH GFED RQP ONML
1211 /// let bf2 = bf.slice_le(&BitIndex::new(0, 5), &BitIndex::new(2, 7));
1212 ///
1213 /// // HGFE DCBA PONM LKJI RQ
1214 /// assert_eq!(bf2, BitField::from_bin_str("0011 0010 1100 1101 10"));
1215 ///
1216 /// let mut bf = BitField::from_bin_str("0101 1100 1010 0110 0101 1001 1011 0");
1217 /// let bf2 = bf.slice_le(&BitIndex::new(0, 5), &BitIndex::new(3, 3));
1218 ///
1219 /// assert_eq!(bf2, BitField::from_bin_str("0011 0010 1100 1101 1100 10"));
1220 ///
1221 /// let mut bf = BitField::from_bin_str("0101 1100 1010 0110 0101 1001 1011 01");
1222 /// let bf2 = bf.slice_le(&BitIndex::new(0, 5), &BitIndex::new(3, 5));
1223 /// assert_eq!(bf2, BitField::from_bin_str("0011 0010 1100 1101 0110 1010"));
1224 ///```
1225 pub fn slice_le(&self, start: &BitIndex, end: &BitIndex) -> BitField {
1226 if start.is_negative() {
1227 panic!("Negative start index supplied to BitField::slice_le: {}", start);
1228 }
1229 if end.is_negative() {
1230 panic!("Negative end index supplied to BitField::slice_le: {}", end);
1231 }
1232 if end > &self.length {
1233 panic!("Out-of-range end index supplied to BitField::slice_le: {}", end);
1234 }
1235 let length = end - start;
1236 if end.is_negative() {
1237 panic!("BitField::slice_le called with end index is less than start index: start={}, end={}", start, end);
1238 }
1239
1240 let mut v = vec![];
1241 let mut byte_iter = self.iter_bytes(false).skip(start.byte());
1242 let mut c = byte_iter.next().unwrap();
1243 let start_cbit = start.cbit();
1244 for _ in 0..length.ceil().byte(){
1245 let mut b = c;
1246 c = byte_iter.next().unwrap();
1247 b >>= start.bit(); // Move most significant bits of current byte to LS position
1248 b |= c << start_cbit; // Take least significant bits of next byte to MS position
1249
1250 v.push(b);
1251 }
1252 if !length.is_byte_boundary() {
1253 if let Some(last) = v.last_mut() {
1254 *last <<= length.cbit();
1255 }
1256 }
1257
1258 BitField::new(v, length)
1259 }
1260
1261 /// Returns the specified slice of `self` assuming that `self` is in a little-endian
1262 /// format, but uses the least significant portion of the first byte and the most-significant
1263 /// portion of the last byte. The bits in the slice are arranged in such
1264 /// a way that their relative magnitude is preserved when interpreted as a little-endian
1265 /// byte array.
1266 ///
1267 /// # Example
1268 ///```rust
1269 /// use bitutils2::{BitField, BitIndex};
1270 /// // 0B5b 2B7b
1271 /// // v v
1272 /// let mut bf = BitField::from_bin_str("0101 1100 1010 0110 0101 1001 1111 0000");
1273 /// // |____ _AAA|CCCB BBBB|EEDD DDD_|
1274 /// // |MSB-->LSB|MSB-->LSB|MSB-->LSB|
1275 /// // Byte 2 Byte 1 Byte 0
1276 /// //
1277 /// // AAA = Least significant bits of least significant byte in slice
1278 /// // BBBBB = Least significant bits of second-to-least significant byte in slice
1279 /// // CCC = Most significant bits of second-to-least significant byte in slice
1280 /// // DDDDD = Least significant bits of most significant byte in slice
1281 /// // EE = Most signiciant bits of most significant byte in slice
1282 /// //
1283 /// let bf2 = bf.slice_le2(&BitIndex::new(0, 5), &BitIndex::new(2, 7));
1284 ///
1285 /// // BBBB BAAA|DDDD DCCC|EE
1286 /// assert_eq!(bf2, BitField::from_bin_str("0011 0100 0110 0101 01"));
1287 ///```
1288 pub fn slice_le2(&self, start: &BitIndex, end: &BitIndex) -> BitField {
1289 // 0123 4567 89ab cdef ghij klmn opqr stuv
1290 // --- ---- ---- ---- -
1291 // kcde fghi j567 89ab
1292 // j567 89ab kcde fghi
1293
1294 // 0123 4567 89ab cdef ghij klmn opqr stuv
1295 // --- ---- ---- ---- ---
1296 // bcde f567 ijkl m89a gh
1297
1298 let length = end - start;
1299 let mut v = vec![0; length.ceil().byte()];
1300
1301 for i in 0..(v.len() - 1) {
1302 let mut b = self.v[start.byte() + i];
1303 let mut c = self.v[start.byte() + i + 1];
1304 if i == 0 {
1305 // Move the portion of the byte within the slice to the MSB position
1306 b <<= start.bit();
1307 } else if start.byte() + i + 1 == end.byte() {
1308 // Move the portion of the byte within the slice to the LSB position
1309 c >>= end.cbit();
1310 //println!("{}, {}", i, c);
1311 }
1312 v[i] = b >> start.bit();
1313 v[i] |= c << start.cbit();
1314 }
1315
1316 v[length.ceil().byte() - 1] = ((self.v[end.byte()] >> end.cbit()) >> start.bit()) << length.cbit();
1317
1318 // // v[0] = ____ _567
1319 // v[0] = (self.v[start.byte()] << start.bit()) >> start.bit();
1320 // // v[0] |= bcde f___ = bcde f567
1321 // v[0] |= self.v[start.byte() + 1] << start.cbit();
1322
1323 // // v[1] = ____ _89a
1324 // v[1] = self.v[start.byte() + 1] >> start.bit();
1325 // // v[1] |= ijkl m___
1326 // if start.byte() + 2 == end.byte() {
1327 // v[1] |= (self.v[start.byte() + 2] >> end.cbit()) << start.cbit();
1328 // }
1329
1330 // v[2] = ((self.v[start.byte() + 2] >> end.cbit()) >> start.bit()) << length.cbit();
1331
1332 BitField::new(v, length)
1333 }
1334
1335 /// Converts the data contained within `self` to a big-endian unsigned
1336 /// integer by removing the sign information according to the source
1337 /// format provided. Returns `true` if the sign was negative before being
1338 /// removed, even if the magnitude is `0`. Returns `false` if the sign was
1339 /// positive, even if the magnitude is `0`.
1340 ///
1341 /// If the source format is `Unsigned`, then `self` is not mutated and
1342 /// `false` is returned.
1343 pub fn convert_unsigned_be(&mut self, src_format: IntFormat) -> bool {
1344 let mut negative: bool;
1345
1346 match src_format {
1347 IntFormat::SignMagnitude => {
1348 negative = self.bit_at(&BitIndex::zero()) != 0;
1349 self.v[0] &= 0x7f;
1350 },
1351 IntFormat::OnesCompliment => {
1352 negative = self.bit_at(&BitIndex::zero()) != 0;
1353 if negative {
1354 for b in self.v.iter_mut() {
1355 *b ^= 0xff;
1356 }
1357 if !self.length.is_byte_boundary() {
1358 let last_byte = self.v.len() - 1;
1359 self.v[last_byte] &= 0xff << self.length.cbit();
1360 }
1361 }
1362 },
1363 IntFormat::TwosCompliment => {
1364 negative = self.bit_at(&BitIndex::zero()) != 0;
1365 if negative {
1366 let mut carry = true;
1367 for b in self.v.iter_mut().rev() {
1368 if carry {
1369 (*b, carry) = b.overflowing_sub(1);
1370 }
1371 *b ^= 0xff;
1372 }
1373 if !self.length.is_byte_boundary() {
1374 let last_byte = self.v.len() - 1;
1375 self.v[last_byte] &= 0xff << self.length.cbit();
1376 }
1377 }
1378 },
1379 IntFormat::Unsigned => {
1380 negative = false
1381 },
1382 IntFormat::BaseMinusTwo => {
1383 // If the BitField ends with an odd number of bits, then
1384 // it needs to be accounted for since the bits are counted
1385 // from the LSB, so which bits are even and odd will be switched
1386 let odd_bits = self.length.bit() & 0x01 != 0;
1387
1388 // Iterate through from the most significant to least
1389 // significant bytes to tell whether the highest value
1390 // bit is negative or positive. This will determine the
1391 // sign of the result. Also record the location of the
1392 // MSB so that we can save some iterations in the subtration
1393 negative = false;
1394 let mut num_significant_bytes = self.v.len();
1395 for (i, b) in self.v.iter().enumerate() {
1396 if *b != 0 {
1397 negative = ((*b & 0xaa) > (*b & 0x55)) ^ odd_bits;
1398 num_significant_bytes -= i;
1399 break;
1400 }
1401 }
1402
1403 // Subtract the even bits from the odd bits if positive,
1404 // and vice versa if negative to guarantee a positive result.
1405 let mut carry = false;
1406 let mut minuend;
1407 let mut subtrahend;
1408 for b in self.v.iter_mut().rev().take(num_significant_bytes) {
1409 (minuend, subtrahend) = match negative ^ odd_bits {
1410 true => (*b & 0xaa, *b & 0x55),
1411 false => (*b & 0x55, *b & 0xaa)
1412 };
1413 if carry {
1414 subtrahend += 1;
1415 }
1416 (*b, carry) = minuend.overflowing_sub(subtrahend);
1417
1418 }
1419 }
1420 };
1421
1422 return negative
1423 }
1424
1425 /// Converts the data contained within `self` to a little-endian unsigned
1426 /// integer by removing the sign information according to the source
1427 /// format provided. Returns `true` if the sign was negative before being
1428 /// removed, even if the magnitude is `0`. Returns `false` if the sign was
1429 /// positive, even if the magnitude is `0`.
1430 ///
1431 /// If the source format is `Unsigned`, then `self` is not mutated and
1432 /// `false` is returned.
1433 pub fn convert_unsigned_le(&mut self, src_format: IntFormat) -> bool {
1434 let mut negative: bool;
1435
1436 let msb = BitIndex::new(self.len().ceil().byte() - 1, 0);
1437
1438 match src_format {
1439 IntFormat::SignMagnitude => {
1440 negative = self.bit_at(&msb) != 0;
1441 self.v[msb.byte()] &= 0x7f;
1442 },
1443 IntFormat::OnesCompliment => {
1444 negative = self.bit_at(&msb) != 0;
1445 if negative {
1446 for b in self.v.iter_mut() {
1447 *b ^= 0xff;
1448 }
1449 if !self.length.is_byte_boundary() {
1450 let last_byte = self.v.len() - 1;
1451 self.v[last_byte] &= 0xff << self.length.cbit();
1452 }
1453 }
1454 },
1455 IntFormat::TwosCompliment => {
1456 negative = self.bit_at(&msb) != 0;
1457 if negative {
1458 let mut carry = true;
1459 for b in self.v.iter_mut() {
1460 if carry {
1461 (*b, carry) = b.overflowing_sub(1);
1462 }
1463 *b ^= 0xff;
1464 }
1465 if !self.length.is_byte_boundary() {
1466 let last_byte = self.v.len() - 1;
1467 self.v[last_byte] &= 0xff << self.length.cbit();
1468 }
1469 }
1470 },
1471 IntFormat::Unsigned => {
1472 negative = false
1473 },
1474 IntFormat::BaseMinusTwo => {
1475 // If the BitField ends with an odd number of bits, then
1476 // it needs to be accounted for since the bits are counted
1477 // from the LSB, so which bits are even and odd will be switched
1478 // in the leftmost byte
1479 let odd_bits = self.length.bit() & 0x01 != 0;
1480
1481 let last_byte = self.v.len() - 1;
1482
1483 // Iterate through from the most significant to least
1484 // significant bytes to tell whether the highest value
1485 // bit is negative or positive. This will determine the
1486 // sign of the result. Also record the location of the
1487 // MSB so that we can save some iterations in the subtration
1488 negative = false;
1489 let mut num_significant_bytes = self.v.len();
1490 for (i, b) in self.v.iter().rev().enumerate() {
1491 if *b != 0 {
1492 negative = ((*b & 0xaa) > (*b & 0x55)) ^ (odd_bits && i == last_byte);
1493 num_significant_bytes -= i;
1494 break;
1495 }
1496 }
1497
1498 // Subtract the even bits from the odd bits if positive,
1499 // and vice versa if negative to guarantee a positive result.
1500 let mut carry = false;
1501 let mut minuend;
1502 let mut subtrahend;
1503 for (i, b) in self.v.iter_mut().enumerate().take(num_significant_bytes) {
1504 (minuend, subtrahend) = match negative ^ (odd_bits && i == last_byte) {
1505 true => (*b & 0xaa, *b & 0x55),
1506 false => (*b & 0x55, *b & 0xaa)
1507 };
1508 if carry {
1509 subtrahend += 1;
1510 }
1511 (*b, carry) = minuend.overflowing_sub(subtrahend);
1512
1513 }
1514 }
1515 }
1516
1517 return negative
1518 }
1519
1520 /// Pads `self` to the specified length in such a way that when interpreted
1521 /// as an unsigned big-endian integer, the value is unchanged. More specifically,
1522 /// `self` is extended to the new length by padding the left side with zeros.
1523 ///
1524 /// This also works for base -2 numbers
1525 ///
1526 /// Does nothing if the provided length is less than or equal to `self`'s current
1527 /// length.
1528 ///
1529 /// # Examples
1530 ///```rust
1531 /// use bitutils2::{BitField, BitIndex};
1532 ///
1533 /// let mut bf = BitField::from_vec(vec![0x30, 0x39]);
1534 /// assert_eq!(u16::from_be_bytes(bf.clone().into_array().unwrap()), 12345);
1535 ///
1536 /// bf.pad_unsigned_be(BitIndex::bits(32));
1537 /// assert_eq!(u32::from_be_bytes(bf.clone().into_array().unwrap()), 12345);
1538 ///
1539 /// bf.pad_unsigned_be(BitIndex::bits(64));
1540 /// assert_eq!(u64::from_be_bytes(bf.clone().into_array().unwrap()), 12345);
1541 ///```
1542 pub fn pad_unsigned_be(&mut self, new_length: BitIndex) {
1543 if self.length < new_length {
1544 let delta = new_length - self.length;
1545 let pad = BitField::zeros(delta);
1546 let original = std::mem::replace(self, pad);
1547 self.extend_be(&original);
1548 }
1549 }
1550
1551 /// Pads `self` to the specified length in such a way that when interpreted
1552 /// as an unsigned little-endian integer, the value is unchanged. More specifically,
1553 /// `self` is extended to the new length by padding the right side with zeros
1554 /// and, if `self` doesn't currently end on a byte boundary, shifting the contents
1555 /// of the last partial byte so that they retain the same significance
1556 ///
1557 /// This also works for base -2 numbers
1558 ///
1559 /// Does nothing if the provided length is less than or equal to `self`'s current
1560 /// length.
1561 ///
1562 /// # Examples
1563 ///```rust
1564 /// use bitutils2::{BitField, BitIndex};
1565 ///
1566 /// let mut bf = BitField::from_vec(vec![0x39, 0x30]);
1567 /// assert_eq!(u16::from_le_bytes(bf.clone().into_array().unwrap()), 12345);
1568 ///
1569 /// bf.pad_unsigned_le(BitIndex::bits(32));
1570 /// assert_eq!(u32::from_le_bytes(bf.clone().into_array().unwrap()), 12345);
1571 ///
1572 /// bf.pad_unsigned_le(BitIndex::bits(64));
1573 /// assert_eq!(u64::from_le_bytes(bf.clone().into_array().unwrap()), 12345);
1574 ///```
1575 pub fn pad_unsigned_le(&mut self, new_length: BitIndex) {
1576 if self.length < new_length {
1577
1578 // Pad the right side with zeros to the new length
1579 let pad = BitField::zeros(new_length - self.length);
1580 self.extend_le(&pad);
1581 }
1582 }
1583
1584 /// Pads `self` to the specified length in such a way that when interpreted
1585 /// as an signed twos-compliment big-endian integer, the value is unchanged.
1586 /// More specifically, `self` is extended to the new length by padding the left
1587 /// side with either zeros or ones depending on the value of the most significant
1588 /// bit.
1589 ///
1590 /// This also works for one's compliment numbers.
1591 ///
1592 /// Does nothing if the provided length is less than or equal to `self`'s current
1593 /// length.
1594 ///
1595 /// # Examples
1596 ///```rust
1597 /// use bitutils2::{BitField, BitIndex};
1598 ///
1599 /// let mut bf = BitField::from_vec(vec![0x30, 0x39]);
1600 /// assert_eq!(i16::from_be_bytes(bf.clone().into_array().unwrap()), 12345);
1601 ///
1602 /// bf.pad_twos_compliment_be(BitIndex::bits(32));
1603 /// assert_eq!(i32::from_be_bytes(bf.clone().into_array().unwrap()), 12345);
1604 ///
1605 /// bf.pad_twos_compliment_be(BitIndex::bits(64));
1606 /// assert_eq!(i64::from_be_bytes(bf.clone().into_array().unwrap()), 12345);
1607 ///
1608 /// let mut bf = BitField::from_vec(vec![0xcf, 0xc7]);
1609 /// assert_eq!(i16::from_be_bytes(bf.clone().into_array().unwrap()), -12345);
1610 ///
1611 /// bf.pad_twos_compliment_be(BitIndex::bits(32));
1612 /// assert_eq!(i32::from_be_bytes(bf.clone().into_array().unwrap()), -12345);
1613 ///
1614 /// bf.pad_twos_compliment_be(BitIndex::bits(64));
1615 /// assert_eq!(i64::from_be_bytes(bf.clone().into_array().unwrap()), -12345);
1616 ///```
1617 pub fn pad_twos_compliment_be(&mut self, new_length: BitIndex) {
1618 if self.length < new_length {
1619 let delta = new_length - self.length;
1620 let pad = if self.bit_at(&BitIndex::zero()) == 0 {
1621 BitField::zeros(delta)
1622 } else {
1623 BitField::ones(delta)
1624 };
1625 let original = std::mem::replace(self, pad);
1626 self.extend_be(&original);
1627 }
1628 }
1629
1630 /// Pads `self` to the specified length in such a way that when interpreted
1631 /// as an signed twos-compliment little-endian integer, the value is unchanged.
1632 /// More specifically, `self` is extended to the new length by padding the right
1633 /// side with either zeros or ones depending on the value of the most significant
1634 /// byte. In addition, if `self` doesn't currently end on a byte boundary,
1635 /// shifting the contents of the last partial byte so that they retain the same
1636 /// significance.
1637 ///
1638 /// This also works for one's compliment numbers.
1639 ///
1640 /// Does nothing if the provided length is less than or equal to `self`'s current
1641 /// length.
1642 ///
1643 /// # Examples
1644 ///```rust
1645 /// use bitutils2::{BitField, BitIndex};
1646 ///
1647 /// let mut bf = BitField::from_vec(vec![0x39, 0x30]);
1648 /// assert_eq!(i16::from_le_bytes(bf.clone().into_array().unwrap()), 12345);
1649 ///
1650 /// bf.pad_twos_compliment_le(BitIndex::bits(32));
1651 /// assert_eq!(i32::from_le_bytes(bf.clone().into_array().unwrap()), 12345);
1652 ///
1653 /// bf.pad_twos_compliment_le(BitIndex::bits(64));
1654 /// assert_eq!(i64::from_le_bytes(bf.clone().into_array().unwrap()), 12345);
1655 ///
1656 /// let mut bf = BitField::from_vec(vec![0xc7, 0xcf]);
1657 /// assert_eq!(i16::from_le_bytes(bf.clone().into_array().unwrap()), -12345);
1658 ///
1659 /// bf.pad_twos_compliment_le(BitIndex::bits(32));
1660 /// assert_eq!(i32::from_le_bytes(bf.clone().into_array().unwrap()), -12345);
1661 ///
1662 /// bf.pad_twos_compliment_le(BitIndex::bits(64));
1663 /// assert_eq!(i64::from_le_bytes(bf.clone().into_array().unwrap()), -12345);
1664 ///```
1665 pub fn pad_twos_compliment_le(&mut self, new_length: BitIndex) {
1666 if self.length < new_length {
1667
1668 let sign_index = if self.length.is_byte_boundary() {
1669 BitIndex::new(self.length.byte() - 1, 0)
1670 } else {
1671 BitIndex::new(self.length.byte(), 0)
1672 };
1673
1674 let negative = self.bit_at(&sign_index) != 0;
1675
1676 let old_length = self.length.clone();
1677
1678
1679 // Determine how many bytes to add after the current byte (even if it's partial)
1680 let new_bytes = new_length.ceil().byte() - self.v.len();
1681
1682 // If the number is negative, pad out the new bytes with 1
1683 if negative {
1684 self.v.extend(vec![0xff; new_bytes]);
1685 let last_byte = self.v.len() - 1;
1686 if !new_length.is_byte_boundary() {
1687 // If the new length has a partial byte, zero out the extra bits
1688 self.v[last_byte] &= 0xff << new_length.cbit();
1689 }
1690 } else {
1691 self.v.extend(vec![0x00; new_bytes]);
1692 }
1693 // Update the length to account for the new bytes added
1694 self.length = new_length;
1695
1696
1697
1698 if !old_length.is_byte_boundary() {
1699 // If `self` ended in a partial byte, that data will need to be
1700 // shifted so that it retains the same significance.
1701 let shift: u8;
1702 if new_length.byte() > old_length.byte() {
1703 // If a new byte was added, push the partial byte at the end
1704 // of the original to the LSB position
1705 shift = old_length.cbit();
1706 } else {
1707 // If a new byte hasn't been added, push the partial byte at
1708 // the end to the new LSB position (not the end of the byte)
1709 shift = new_length.bit() - old_length.bit();
1710 }
1711
1712 // If the number is negative, shift the data in the last byte over
1713 // and fill in with ones. Otherwise, don't fill.
1714 if negative {
1715 self.v[old_length.byte()] = 0xff << (8 - shift) | (self.v[old_length.byte()] >> shift);
1716 } else {
1717 self.v[old_length.byte()] = self.v[old_length.byte()] >> shift;
1718 }
1719
1720 }
1721 }
1722 }
1723
1724 /// Pads `self` to the specified length in such a way that when interpreted
1725 /// as an sign-magnitude big-endian integer, the value is unchanged. More
1726 /// specifically, the sign bit is removed, `self` is extended to the new
1727 /// length by padding the left side with zeros, and the sign bit is reinserted
1728 /// at the new MSB location.
1729 ///
1730 /// Does nothing if the provided length is less than or equal to `self`'s current
1731 /// length.
1732 ///
1733 /// # Examples
1734 ///```rust
1735 /// use bitutils2::{BitField, BitIndex};
1736 ///
1737 /// let mut bf = BitField::from_vec(vec![0x30, 0x39]);
1738 /// let u = u16::from_be_bytes(bf.clone().into_array().unwrap());
1739 /// assert_eq!(u & 0x7fff, 12345); // Magnitude = 12345
1740 /// assert_eq!((u & 0x8000) >> 15, 0); // Sign = positive
1741 ///
1742 /// bf.pad_sign_magnitude_be(BitIndex::bits(32));
1743 /// let u = u32::from_be_bytes(bf.clone().into_array().unwrap());
1744 /// assert_eq!(u & 0x7fffffff, 12345); // Magnitude = 12345
1745 /// assert_eq!((u & 0x80000000) >> 31, 0); // Sign = positive
1746 ///
1747 /// bf.pad_sign_magnitude_be(BitIndex::bits(64));
1748 /// let u = u64::from_be_bytes(bf.clone().into_array().unwrap());
1749 /// assert_eq!(u & 0x7fffffffffffffff, 12345); // Magnitude = 12345
1750 /// assert_eq!((u & 0x8000000000000000) >> 63, 0); // Sign = positive
1751 ///
1752 /// let mut bf = BitField::from_vec(vec![0xb0, 0x39]);
1753 /// let u = u16::from_be_bytes(bf.clone().into_array().unwrap());
1754 /// assert_eq!(u & 0x7fff, 12345); // Magnitude = 12345
1755 /// assert_eq!((u & 0x8000) >> 15, 1); // Sign = negative
1756 ///
1757 /// bf.pad_sign_magnitude_be(BitIndex::bits(32));
1758 /// let u = u32::from_be_bytes(bf.clone().into_array().unwrap());
1759 /// assert_eq!(u & 0x7fffffff, 12345); // Magnitude = 12345
1760 /// assert_eq!((u & 0x80000000) >> 31, 1); // Sign = negative
1761 ///
1762 /// bf.pad_sign_magnitude_be(BitIndex::bits(64));
1763 /// let u = u64::from_be_bytes(bf.clone().into_array().unwrap());
1764 /// assert_eq!(u & 0x7fffffffffffffff, 12345); // Magnitude = 12345
1765 /// assert_eq!((u & 0x8000000000000000) >> 63, 1); // Sign = negative
1766 ///```
1767 pub fn pad_sign_magnitude_be(&mut self, new_length: BitIndex) {
1768 if self.length < new_length {
1769 let delta = new_length - self.length;
1770
1771 // Read and remove sign bit at the MSB position
1772 let sign = self.v[0] & 0x80;
1773 self.v[0] &= 0x7f;
1774
1775 // Left pad to the new length with zeros
1776 let pad = BitField::zeros(delta);
1777 let original = std::mem::replace(self, pad);
1778 self.extend_be(&original);
1779
1780 // Insert the sign at the new MSB position
1781 self.v[0] |= sign;
1782 }
1783 }
1784
1785 /// Pads `self` to the specified length in such a way that when interpreted
1786 /// as an sign-magnitude little-endian integer, the value is unchanged. More
1787 /// specifically, the sign bit is removed, `self` is extended to the new
1788 /// length using [`pad_unsigned_le`](BitField::pad_unsigned_le), and the sign
1789 /// bit is reinserted at the new MSB location.
1790 ///
1791 /// Does nothing if the provided length is less than or equal to `self`'s current
1792 /// length.
1793 ///
1794 /// # Examples
1795 ///```rust
1796 /// use bitutils2::{BitField, BitIndex};
1797 ///
1798 /// let mut bf = BitField::from_vec(vec![0x39, 0x30]);
1799 /// let u = u16::from_le_bytes(bf.clone().into_array().unwrap());
1800 /// assert_eq!(u & 0x7fff, 12345); // Magnitude = 12345
1801 /// assert_eq!((u & 0x8000) >> 15, 0); // Sign = positive
1802 ///
1803 /// bf.pad_sign_magnitude_le(BitIndex::bits(32));
1804 /// let u = u32::from_le_bytes(bf.clone().into_array().unwrap());
1805 /// assert_eq!(u & 0x7fffffff, 12345); // Magnitude = 12345
1806 /// assert_eq!((u & 0x80000000) >> 31, 0); // Sign = positive
1807 ///
1808 /// bf.pad_sign_magnitude_le(BitIndex::bits(64));
1809 /// let u = u64::from_le_bytes(bf.clone().into_array().unwrap());
1810 /// assert_eq!(u & 0x7fffffffffffffff, 12345); // Magnitude = 12345
1811 /// assert_eq!((u & 0x8000000000000000) >> 63, 0); // Sign = positive
1812 ///
1813 /// let mut bf = BitField::from_vec(vec![0x39, 0xb0]);
1814 /// let u = u16::from_le_bytes(bf.clone().into_array().unwrap());
1815 /// assert_eq!(u & 0x7fff, 12345); // Magnitude = 12345
1816 /// assert_eq!((u & 0x8000) >> 15, 1); // Sign = negative
1817 ///
1818 /// bf.pad_sign_magnitude_le(BitIndex::bits(32));
1819 /// let u = u32::from_le_bytes(bf.clone().into_array().unwrap());
1820 /// assert_eq!(u & 0x7fffffff, 12345); // Magnitude = 12345
1821 /// assert_eq!((u & 0x80000000) >> 31, 1); // Sign = negative
1822 ///
1823 /// bf.pad_sign_magnitude_le(BitIndex::bits(64));
1824 /// let u = u64::from_le_bytes(bf.clone().into_array().unwrap());
1825 /// assert_eq!(u & 0x7fffffffffffffff, 12345); // Magnitude = 12345
1826 /// assert_eq!((u & 0x8000000000000000) >> 63, 1); // Sign = negative
1827 ///```
1828 pub fn pad_sign_magnitude_le(&mut self, new_length: BitIndex) {
1829 if self.length < new_length {
1830
1831 // Read and remove sign bit at the MSB position
1832 let msb = self.length.ceil().byte() - 1;
1833 let sign = self.v[msb] & 0x80;
1834 self.v[msb] &= 0x7f;
1835
1836 // Pad as an unsigned value (since it pretty much is now)
1837 self.pad_unsigned_le(new_length);
1838
1839 // Insert the sign at the new MSB position
1840 let msb = self.length.ceil().byte() - 1;
1841 self.v[msb] |= sign;
1842 }
1843 }
1844
1845}
1846
1847impl BitIndexable for BitField {
1848 fn bit_at(&self, index: &BitIndex) -> u8 {
1849 (self.v[index.byte()] >> (7 - index.bit())) & 0x01
1850 }
1851
1852 fn bit_slice(&self, start: &BitIndex, end: &BitIndex) -> BitField {
1853 // This is the same implementation as the Vec<u8> bit_slice method. If you change this, consider changing the other one
1854 let start_byte = start.byte();
1855 let start_bit = start.bit();
1856 let start_cbit = start.cbit();
1857 let end_byte = end.byte();
1858 let end_bit = end.bit();
1859 let end_cbit = end.cbit();
1860
1861 let mut res = Vec::<u8>::new();
1862
1863 if start_bit == 0 {
1864 res = self.v[start_byte..end_byte].to_vec();
1865 } else {
1866 for i in start_byte..end_byte {
1867 let carry = if i + 1 < self.v.len() {self.v[i+1] >> start_cbit} else {0};
1868 // println!("{} {}", i, carry);
1869 res.push((self.v[i] << start_bit) | carry);
1870 }
1871 }
1872 match start_bit.cmp(&end_bit) {
1873 std::cmp::Ordering::Greater => {
1874 let res_len = res.len();
1875 let last = res[res_len - 1];
1876 res[res_len - 1] = (last >> (start_bit - end_bit)) << (start_bit - end_bit);
1877 },
1878 std::cmp::Ordering::Less => {
1879 res.push((self.v[end_byte] >> end_cbit) << (start_bit + end_cbit));
1880 },
1881 _ => ()
1882 }
1883 BitField {v: res, length: *end - *start}
1884 }
1885
1886 fn max_index(&self) -> BitIndex {
1887 self.length
1888 }
1889}
1890
1891impl Default for BitField {
1892 fn default() -> BitField {
1893 BitField::new(vec![], BitIndex::zero())
1894 }
1895}
1896
1897impl std::cmp::PartialEq for BitField {
1898 fn eq(&self, other: &Self) -> bool {
1899 if self.len() != other.len() {
1900 false
1901 } else if self.len().is_byte_boundary() {
1902 self.v == other.v
1903 } else {
1904 let n = self.length.byte();
1905 if self.v[0..n] != other.v[0..n] {
1906 return false
1907 }
1908 let m = if cfg!(test) { // If testing, verify all bits, even the ones past the end of the "final" bit
1909 0
1910 } else {
1911 self.len().cbit()
1912 };
1913 (self.v[n] >> m) == (other.v[n] >> m)
1914 }
1915 }
1916}
1917
1918impl std::cmp::Eq for BitField {}
1919
1920impl std::ops::BitAnd for &BitField {
1921 type Output = BitField;
1922
1923 /// Returns the bitwise `&` operation on the two inputs. If the two inputs have different lengths,
1924 /// then the returned value will have the length of the shortest input.
1925 ///
1926 /// # Example
1927 ///```rust
1928 /// use bitutils2::{BitField, BitIndex};
1929 ///
1930 /// let bf1 = BitField::from_bin_str("0011 1010 0000 1111 1100 0101 0111");
1931 /// let bf2 = BitField::from_bin_str("0101 0000 1100 0111 1010 1111 0001");
1932 /// assert_eq!(&bf1 & &bf2, BitField::from_bin_str("0001 0000 0000 0111 1000 0101 0001"));
1933 ///```
1934 fn bitand(self, rhs: &BitField) -> BitField {
1935 // Figure out the number of bytes for the shortest input and generate a new vector with that
1936 // capacity
1937 let min_len = std::cmp::min(self.len(), rhs.len());
1938 let end = min_len.ceil().byte();
1939 let mut res = Vec::<u8>::with_capacity(end);
1940
1941 // Perform the bitwise operation on all bytes
1942 for i in 0..end {
1943 res.push(self.v[i] & rhs.v[i]);
1944 }
1945 // No need to clear bits past the end of the length since the & operation should zero them out
1946 BitField {v: res, length: min_len}
1947 }
1948}
1949
1950impl std::ops::BitAndAssign<&BitField> for BitField {
1951
1952 /// Transforms `self` to have the value of `self & rhs`. If the two inputs have different lengths,
1953 /// then the resulting value will have the length of the shortest input.
1954 ///
1955 /// # Example
1956 ///```rust
1957 /// use bitutils2::{BitField, BitIndex};
1958 ///
1959 /// let mut bf1 = BitField::from_bin_str("0011 1010 0000 1111 1100 0101 0111");
1960 /// bf1 &= &BitField::from_bin_str("0101 0000 1100 0111 1010 1111 0001");
1961 /// assert_eq!(bf1, BitField::from_bin_str("0001 0000 0000 0111 1000 0101 0001"));
1962 ///```
1963 fn bitand_assign(&mut self, rhs: &BitField) {
1964 // Figure out the number of bytes for the shortest input and truncate `self` accordingly
1965 let min_len = std::cmp::min(self.len(), rhs.len());
1966 let end = min_len.ceil().byte();
1967 self.v.truncate(end);
1968
1969 // Perform the bitwise operation on all bytes
1970 for i in 0..end {
1971 self.v[i] &= rhs.v[i];
1972 }
1973 // No need to clear bits past the end of the length since the & operation should zero them out
1974
1975 // Update the length in case `self` was truncated
1976 self.length = min_len;
1977 }
1978}
1979
1980impl std::ops::BitOr for &BitField {
1981 type Output = BitField;
1982
1983 /// Returns the bitwise `|` operation on the two inputs. If the two inputs have different lengths,
1984 /// then the returned value will have the length of the shortest input.
1985 ///
1986 /// # Example
1987 ///```rust
1988 /// use bitutils2::{BitField, BitIndex};
1989 ///
1990 /// let bf1 = BitField::from_bin_str("0011 1010 0000 1111 1100 0101 0111");
1991 /// let bf2 = BitField::from_bin_str("0101 0000 1100 0111 1010 1111 0001");
1992 /// assert_eq!(&bf1 | &bf2, BitField::from_bin_str("0111 1010 1100 1111 1110 1111 0111"));
1993 ///```
1994 fn bitor(self, rhs: &BitField) -> BitField {
1995 let min_len = std::cmp::min(self.len(), rhs.len());
1996 let end = min_len.ceil().byte();
1997 let mut res = Vec::<u8>::with_capacity(end);
1998 for i in 0..end {
1999 res.push(self.v[i] | rhs.v[i]);
2000 }
2001 if min_len.bit() != 0 {
2002 let last = (res[end - 1] >> min_len.cbit()) << min_len.cbit();
2003 res[end - 1] = last;
2004 }
2005 BitField {v: res, length: min_len}
2006 }
2007}
2008
2009impl std::ops::BitOrAssign<&BitField> for BitField {
2010
2011 /// Transforms `self` to have the value of `self | rhs`. If the two inputs have different lengths,
2012 /// then the resulting value will have the length of the shortest input.
2013 ///
2014 /// # Example
2015 ///```rust
2016 /// use bitutils2::{BitField, BitIndex};
2017 ///
2018 /// let mut bf1 = BitField::from_bin_str("0011 1010 0000 1111 1100 0101 0111");
2019 /// bf1 |= &BitField::from_bin_str("0101 0000 1100 0111 1010 1111 0001");
2020 /// assert_eq!(bf1, BitField::from_bin_str("0111 1010 1100 1111 1110 1111 0111"));
2021 ///```
2022 fn bitor_assign(&mut self, rhs: &BitField) {
2023 // Figure out the number of bytes for the shortest input and truncate `self` accordingly
2024 let min_len = std::cmp::min(self.len(), rhs.len());
2025 let end = min_len.ceil().byte();
2026 self.v.truncate(end);
2027
2028 // Perform the bitwise operation on all bytes
2029 for i in 0..end {
2030 self.v[i] |= rhs.v[i];
2031 }
2032
2033 // Ensure that the bits past the end of the bitfield are zeroed
2034 if min_len.bit() != 0 {
2035 let last = (self.v[end - 1] >> min_len.cbit()) << min_len.cbit();
2036 self.v[end - 1] = last;
2037 }
2038
2039 // Update the length in case `self` was truncated
2040 self.length = min_len;
2041 }
2042}
2043
2044impl std::ops::BitXor for &BitField {
2045 type Output = BitField;
2046
2047 /// Returns the bitwise `^` operation on the two inputs. If the two inputs have different lengths,
2048 /// then the returned value will have the length of the shortest input.
2049 ///
2050 /// # Example
2051 ///```rust
2052 /// use bitutils2::{BitField, BitIndex};
2053 ///
2054 /// let bf1 = BitField::from_bin_str("0011 1010 0000 1111 1100 0101 0111");
2055 /// let bf2 = BitField::from_bin_str("0101 0000 1100 0111 1010 1111 0001");
2056 /// assert_eq!(&bf1 ^ &bf2, BitField::from_bin_str("0110 1010 1100 1000 0110 1010 0110"));
2057 ///```
2058 fn bitxor(self, rhs: &BitField) -> BitField {
2059 let min_len = std::cmp::min(self.len(), rhs.len());
2060 let end = min_len.ceil().byte();
2061 let mut res = Vec::<u8>::with_capacity(end);
2062 for i in 0..end {
2063 res.push(self.v[i] ^ rhs.v[i]);
2064 }
2065 if min_len.bit() != 0 {
2066 let last = (res[end - 1] >> min_len.cbit()) << min_len.cbit();
2067 res[end - 1] = last;
2068 }
2069 BitField {v: res, length: min_len}
2070 }
2071}
2072
2073impl std::ops::BitXorAssign<&BitField> for BitField {
2074
2075 /// Transforms `self` to have the value of `self ^ rhs`. If the two inputs have different lengths,
2076 /// then the resulting value will have the length of the shortest input.
2077 ///
2078 /// # Example
2079 ///```rust
2080 /// use bitutils2::{BitField, BitIndex};
2081 ///
2082 /// let mut bf1 = BitField::from_bin_str("0011 1010 0000 1111 1100 0101 0111");
2083 /// bf1 ^= &BitField::from_bin_str("0101 0000 1100 0111 1010 1111 0001");
2084 /// assert_eq!(bf1, BitField::from_bin_str("0110 1010 1100 1000 0110 1010 0110"));
2085 ///```
2086 fn bitxor_assign(&mut self, rhs: &BitField) {
2087 // Figure out the number of bytes for the shortest input and truncate `self` accordingly
2088 let min_len = std::cmp::min(self.len(), rhs.len());
2089 let end = min_len.ceil().byte();
2090 self.v.truncate(end);
2091
2092 // Perform the bitwise operation on all bytes
2093 for i in 0..end {
2094 self.v[i] ^= rhs.v[i];
2095 }
2096
2097 // Ensure that the bits past the end of the bitfield are zeroed
2098 if min_len.bit() != 0 {
2099 let last = (self.v[end - 1] >> min_len.cbit()) << min_len.cbit();
2100 self.v[end - 1] = last;
2101 }
2102
2103 // Update the length in case `self` was truncated
2104 self.length = min_len;
2105 }
2106}
2107
2108impl std::ops::Not for &BitField {
2109 type Output = BitField;
2110
2111 /// Returns the bitwise `!` operation on the input.
2112 ///
2113 /// # Example
2114 ///```rust
2115 /// use bitutils2::{BitField, BitIndex};
2116 ///
2117 /// let bf = BitField::from_bin_str("0011 1010 0000 1111 1100 0101 0111");
2118 /// assert_eq!(!&bf, BitField::from_bin_str("1100 0101 1111 0000 0011 1010 1000"));
2119 ///```
2120 fn not(self) -> BitField {
2121 let end = self.length.ceil().byte();
2122 let mut res = Vec::<u8>::with_capacity(end);
2123 for i in 0..end {
2124 res.push(!self.v[i]);
2125 }
2126 if self.length.bit() != 0 {
2127 let last = (res[end - 1] >> self.length.cbit()) << self.length.cbit();
2128 res[end - 1] = last;
2129 }
2130 BitField {v: res, length: self.len()}
2131 }
2132}
2133
2134impl std::ops::Shl<usize> for BitField {
2135 type Output = Self;
2136
2137 /// Returns a [`BitField`](crate::BitField) with the bits shifted left by `rhs` bits.
2138 /// Bits that are dropped off the left side are wrapped around to fill the right side.
2139 ///
2140 /// # Examples
2141 ///```rust
2142 /// use bitutils2::{BitField, BitIndex};
2143 ///
2144 /// let bf = BitField::from_bin_str("1100 0000 1111 00");
2145 /// let bf = bf << 2;
2146 /// assert_eq!(bf, BitField::from_bin_str("0000 0011 1100 11"));
2147 /// let bf = bf << 4;
2148 /// assert_eq!(bf, BitField::from_bin_str("0011 1100 1100 00"));
2149 ///```
2150 fn shl(self, rhs: usize) -> Self::Output {
2151 if rhs == 0 {
2152 return self;
2153 }
2154
2155 let shift = BitIndex::bits(rhs);
2156
2157 let mut v = Vec::<u8>::with_capacity(self.v.len());
2158
2159 for i in 0..self.v.len() {
2160 let bi = BitIndex::bytes(i) + shift;
2161 v.push(self.extract_u8_cyclical(bi));
2162 }
2163
2164 if !self.length.is_byte_boundary() {
2165 v[self.length.byte()] = (v[self.length.byte()] >> self.length.cbit()) << self.length.cbit();
2166 }
2167
2168 BitField {v: v, length: self.len()}
2169 }
2170
2171}
2172
2173impl std::ops::ShlAssign<usize> for BitField {
2174
2175 /// Transforms `self` by shifting all bits to the left by `rhs` bits.
2176 /// Bits that are dropped off the left side are wrapped around to fill the right side.
2177 ///
2178 /// # Examples
2179 ///```rust
2180 /// use bitutils2::{BitField, BitIndex};
2181 ///
2182 /// let mut bf = BitField::from_bin_str("1100 0000 1111 00");
2183 /// bf <<= 2;
2184 /// assert_eq!(bf, BitField::from_bin_str("0000 0011 1100 11"));
2185 /// bf <<= 4;
2186 /// assert_eq!(bf, BitField::from_bin_str("0011 1100 1100 00"));
2187 ///```
2188 fn shl_assign(&mut self, rhs: usize){
2189 *self = std::mem::take(self) << rhs;
2190 }
2191}
2192
2193impl std::ops::Shl<BitIndex> for BitField {
2194 type Output = Self;
2195
2196 /// Returns a [`BitField`](crate::BitField) with the bits shifted left by the magnitude of
2197 /// `rhs` if `rhs` is positive or shifted right if `rhs` is negative. Bits that are dropped
2198 /// off one side are wrapped around to fill the other side.
2199 ///
2200 /// # Examples
2201 ///```rust
2202 /// use bitutils2::{BitField, BitIndex, bx};
2203 ///
2204 /// let bf = BitField::from_bin_str("1100 0000 1111 00");
2205 /// let bf = bf << bx!(,2);
2206 /// assert_eq!(bf, BitField::from_bin_str("0000 0011 1100 11"));
2207 /// let bf = bf << bx!(1 ,4);
2208 /// assert_eq!(bf, BitField::from_bin_str("1100 0000 1111 00"));
2209 ///
2210 /// // Negative bit indexes will result in right shifts
2211 /// let bf = bf << -bx!(1 ,4);
2212 /// assert_eq!(bf, BitField::from_bin_str("0000 0011 1100 11"));
2213 ///```
2214 fn shl(self, rhs: BitIndex) -> Self::Output {
2215 let n = rhs.total_bits();
2216 if n < 0 {
2217 self >> (n.abs() as usize)
2218 } else {
2219 self << (n as usize)
2220 }
2221 }
2222}
2223
2224impl std::ops::ShlAssign<BitIndex> for BitField {
2225
2226 /// Transforms `self` by shifting all bits to the left by the magnitude of
2227 /// `rhs` if `rhs` is positive or shifted right if `rhs` is negative. Bits that are dropped
2228 /// off one side are wrapped around to fill the other side.
2229 ///
2230 /// # Examples
2231 ///```rust
2232 /// use bitutils2::{BitField, BitIndex, bx};
2233 ///
2234 /// let mut bf = BitField::from_bin_str("1100 0000 1111 00");
2235 /// bf <<= bx!(,2);
2236 /// assert_eq!(bf, BitField::from_bin_str("0000 0011 1100 11"));
2237 /// bf <<= bx!(1, 4);
2238 /// assert_eq!(bf, BitField::from_bin_str("1100 0000 1111 00"));
2239 ///
2240 /// // Negative bit indexes will result in right shifts
2241 /// bf <<= -bx!(1, 4);
2242 /// assert_eq!(bf, BitField::from_bin_str("0000 0011 1100 11"));
2243 ///```
2244 fn shl_assign(&mut self, rhs: BitIndex){
2245 *self = std::mem::take(self) << rhs;
2246 }
2247}
2248
2249
2250
2251impl std::ops::Shr<usize> for BitField {
2252 type Output = Self;
2253
2254 /// Returns a [`BitField`](crate::BitField) with the bits shifted right by `rhs` bits.
2255 /// Bits that are dropped off the right side are wrapped around to fill the left side.
2256 ///
2257 /// # Examples
2258 ///```rust
2259 /// use bitutils2::{BitField, BitIndex};
2260 ///
2261 /// let bf = BitField::from_bin_str("1100 0000 1111 00");
2262 /// let bf = bf >> 2;
2263 /// assert_eq!(bf, BitField::from_bin_str("0011 0000 0011 11"));
2264 /// let bf = bf >> 4;
2265 /// assert_eq!(bf, BitField::from_bin_str("1111 0011 0000 00"));
2266 ///```
2267 fn shr(self, rhs: usize) -> Self::Output {
2268 if rhs == 0 {
2269 return self;
2270 }
2271
2272 let shift = BitIndex::bits(rhs);
2273 // println!("{:?}", shift);
2274
2275 let mut v = Vec::<u8>::with_capacity(self.v.len());
2276
2277
2278 for i in 0..self.v.len() {
2279 let bi = BitIndex::bytes(i) - shift;
2280 v.push(self.extract_u8_cyclical(bi));
2281 }
2282
2283 if !self.length.is_byte_boundary() {
2284 v[self.length.byte()] = (v[self.length.byte()] >> self.length.cbit()) << self.length.cbit();
2285 }
2286
2287 BitField::new(v, self.length)
2288 }
2289
2290}
2291
2292impl std::ops::ShrAssign<usize> for BitField {
2293
2294 /// Transforms `self` by shifting all bits to the right by `rhs` bits.
2295 /// Bits that are dropped off the right side are wrapped around to fill the right side.
2296 ///
2297 /// # Examples
2298 ///```rust
2299 /// use bitutils2::{BitField, BitIndex};
2300 ///
2301 /// let mut bf = BitField::from_bin_str("1100 0000 1111 00");
2302 /// bf >>= 2;
2303 /// assert_eq!(bf, BitField::from_bin_str("0011 0000 0011 11"));
2304 /// bf >>= 4;
2305 /// assert_eq!(bf, BitField::from_bin_str("1111 0011 0000 00"));
2306 ///```
2307 fn shr_assign(&mut self, rhs: usize){
2308 *self = std::mem::take(self) >> rhs;
2309 }
2310}
2311
2312impl std::ops::Shr<BitIndex> for BitField {
2313 type Output = Self;
2314
2315 /// Returns a [`BitField`](crate::BitField) with the bits shifted right by the magnitude of
2316 /// `rhs` if `rhs` is positive or shifted left if `rhs` is negative. Bits that are dropped
2317 /// off one side are wrapped around to fill the other side.
2318 ///
2319 /// # Examples
2320 ///```rust
2321 /// use bitutils2::{BitField, BitIndex, bx};
2322 ///
2323 /// let bf = BitField::from_bin_str("1100 0000 1111 00");
2324 /// let bf = bf >> bx!(,2);
2325 /// assert_eq!(bf, BitField::from_bin_str("0011 0000 0011 11"));
2326 /// let bf = bf >> bx!(1 ,4);
2327 /// assert_eq!(bf, BitField::from_bin_str("1100 0000 1111 00"));
2328 ///
2329 /// // Negative bit indexes will result in left shifts
2330 /// let bf = bf >> -bx!(1 ,4);
2331 /// assert_eq!(bf, BitField::from_bin_str("0011 0000 0011 11"));
2332 ///```
2333 fn shr(self, rhs: BitIndex) -> Self::Output {
2334 let n = rhs.total_bits();
2335 if n < 0 {
2336 self << (n.abs() as usize)
2337 } else {
2338 self >> (n as usize)
2339 }
2340 }
2341}
2342
2343impl std::ops::ShrAssign<BitIndex> for BitField {
2344
2345 /// Transforms `self` by shifting all bits to the right by the magnitude of
2346 /// `rhs` if `rhs` is positive or shifted left if `rhs` is negative. Bits that are dropped
2347 /// off one side are wrapped around to fill the other side.
2348 ///
2349 /// # Examples
2350 ///```rust
2351 /// use bitutils2::{BitField, BitIndex, bx};
2352 ///
2353 /// let mut bf = BitField::from_bin_str("1100 0000 1111 00");
2354 /// bf >>= bx!(,2);
2355 /// assert_eq!(bf, BitField::from_bin_str("0011 0000 0011 11"));
2356 /// bf >>= bx!(1, 4);
2357 /// assert_eq!(bf, BitField::from_bin_str("1100 0000 1111 00"));
2358 ///
2359 /// // Negative bit indexes will result in left shifts
2360 /// bf >>= -bx!(1, 4);
2361 /// assert_eq!(bf, BitField::from_bin_str("0011 0000 0011 11"));
2362 ///```
2363 fn shr_assign(&mut self, rhs: BitIndex){
2364 *self = std::mem::take(self) >> rhs;
2365 }
2366}
2367
2368pub trait FromBitField {
2369 fn from_bf_be(bf: &BitField) -> Self;
2370 fn from_bf_le(bf: &BitField) -> Self;
2371}
2372
2373impl FromBitField for u8 {
2374
2375 fn from_bf_be(bf: &BitField) -> u8 {
2376 let b = bf.len().bit();
2377 if b == 0 {
2378 bf.v[0]
2379 } else {
2380 bf.v[0] >> (8 - b)
2381 }
2382 }
2383
2384 fn from_bf_le(bf: &BitField) -> u8 {
2385 let b = bf.len().bit();
2386 if b == 0 {
2387 bf.v[0]
2388 } else {
2389 bf.v[0] >> (8 - b)
2390 }
2391 }
2392}
2393
2394
2395impl FromBitField for u128 {
2396
2397 fn from_bf_be(bf: &BitField) -> u128 {
2398 let bits = BitIndex::bits(128);
2399 let mut new_bf: BitField;
2400 if bf.len() < bits {
2401 new_bf = bf.clone();
2402 new_bf.pad_unsigned_be(bits);
2403 } else {
2404 new_bf = bf.slice_be(&BitIndex::zero(), &bits);
2405 }
2406 u128::from_be_bytes(new_bf.into_array().unwrap())
2407 }
2408
2409 fn from_bf_le(bf: &BitField) -> u128 {
2410 let bits = BitIndex::bits(128);
2411 let mut new_bf: BitField;
2412 if bf.len() < bits {
2413 new_bf = bf.clone();
2414 new_bf.pad_unsigned_le(bits);
2415 } else {
2416 new_bf = bf.slice_be(&BitIndex::zero(), &bits);
2417 }
2418 u128::from_le_bytes(new_bf.into_array().unwrap())
2419 }
2420}
2421
2422impl FromBitField for i128 {
2423
2424 fn from_bf_be(bf: &BitField) -> i128 {
2425 let bits = BitIndex::bits(128);
2426 let mut new_bf: BitField;
2427 if bf.len() < bits {
2428 new_bf = bf.clone();
2429 new_bf.pad_twos_compliment_be(bits);
2430 } else {
2431 new_bf = bf.slice_be(&BitIndex::zero(), &bits);
2432 }
2433 i128::from_be_bytes(new_bf.into_array().unwrap())
2434 }
2435
2436 fn from_bf_le(bf: &BitField) -> i128 {
2437 let bits = BitIndex::bits(128);
2438 let mut new_bf: BitField;
2439 if bf.len() < bits {
2440 new_bf = bf.clone();
2441 new_bf.pad_twos_compliment_le(bits);
2442 } else {
2443 new_bf = bf.slice_be(&BitIndex::zero(), &bits);
2444 }
2445 i128::from_le_bytes(new_bf.into_array().unwrap())
2446 }
2447}
2448
2449
2450
2451#[cfg(test)]
2452mod bit_field_tests {
2453 use super::*;
2454
2455 #[test]
2456 fn zeros() {
2457 assert_eq!(BitField::zeros(BitIndex::new(2, 4)), BitField::from_bin_str("0000 0000 0000 0000 0000"));
2458 assert_eq!(BitField::zeros(BitIndex::new(3, 0)), BitField::from_bin_str("0000 0000 0000 0000 0000 0000"));
2459 assert_eq!(BitField::zeros(BitIndex::new(0, 0)), BitField::from_bin_str(""));
2460 }
2461
2462 #[test]
2463 fn ones() {
2464 assert_eq!(BitField::ones(BitIndex::new(2, 4)), BitField::from_bin_str("1111 1111 1111 1111 1111"));
2465 assert_eq!(BitField::ones(BitIndex::new(3, 0)), BitField::from_bin_str("1111 1111 1111 1111 1111 1111"));
2466 assert_eq!(BitField::ones(BitIndex::new(0, 0)), BitField::from_bin_str(""));
2467 }
2468
2469 #[test]
2470 fn indexing() {
2471 let bf = BitField::from_vec(vec![0x00, 0xFF, 0xAB, 0x0F]);
2472 assert_eq!(bf.max_index(), BitIndex::new(4, 0));
2473 assert_eq!(bf.bit_at(&BitIndex::new(0, 0)), 0);
2474 assert_eq!(bf.bit_at(&BitIndex::new(1, 0)), 1);
2475 assert_eq!(bf.bit_at(&BitIndex::new(2, 0)), 1);
2476 assert_eq!(bf.bit_at(&BitIndex::new(2, 1)), 0);
2477 assert_eq!(bf.bit_at(&BitIndex::new(2, 2)), 1);
2478 assert_eq!(bf.bit_at(&BitIndex::new(2, 3)), 0);
2479 assert_eq!(bf.bit_at(&BitIndex::new(2, 4)), 1);
2480 assert_eq!(bf.bit_at(&BitIndex::new(2, 5)), 0);
2481 assert_eq!(bf.bit_at(&BitIndex::new(2, 6)), 1);
2482 assert_eq!(bf.bit_at(&BitIndex::new(2, 7)), 1);
2483 }
2484
2485 #[test]
2486 fn equality() {
2487 assert_ne!(BitField::from_bin_str("0101 0111 0000 1111"), BitField::from_bin_str("0101 0111 0000 1110"));
2488 assert_ne!(BitField::from_bin_str("0101 0111 0000 1111 11"), BitField::from_bin_str("0101 0111 0000 1111 10"));
2489 assert_ne!(BitField::from_bin_str("0101 0111 0000 1111 1"), BitField::from_bin_str("0101 0111 0000 1111 10"));
2490 assert_ne!(BitField::from_bin_str("0101 0111 0000 1111 11"), BitField::from_bin_str("0101 0111 0000 1111 1"));
2491 }
2492
2493 #[test]
2494 fn parse() {
2495 assert_eq!(BitField::from_bin_str("0101 0111 0000 1111"), BitField::from_vec(vec![0x57, 0x0F]));
2496 assert_eq!(BitField::from_bin_str("0101_0111_0000_1111_0011_1100"), BitField::from_vec(vec![0x57, 0x0F, 0x3C]));
2497 assert_eq!(BitField::from_bin_str("0101_0111_0000_1").len(), BitIndex::new(1, 5));
2498
2499 assert_eq!(BitField::from_bin_str("0101_0111_0000_1111"), BitField::from_hex_str("57 0f"));
2500 assert_eq!(BitField::from_bin_str("0101 1010 0000 1111 1100 0011 0110"), BitField::from_hex_str("5a 0f C3 6"));
2501 }
2502
2503 #[test]
2504 fn truncate_be() {
2505 let mut bf = BitField::from_bin_str("0101 1111 0000 1011 1100 0001");
2506 bf.truncate_be(BitIndex::new(2, 2));
2507 assert_eq!(bf, BitField::from_bin_str("0101 1111 0000 1011 11"));
2508 bf.truncate_be(BitIndex::new(2, 0));
2509 assert_eq!(bf, BitField::from_bin_str("0101 1111 0000 1011"));
2510 bf.truncate_be(BitIndex::new(1, 6));
2511 assert_eq!(bf, BitField::from_bin_str("0101 1111 0000 10"));
2512 bf.truncate_be(BitIndex::new(1, 6));
2513 assert_eq!(bf, BitField::from_bin_str("0101 1111 0000 10"));
2514 bf.truncate_be(BitIndex::new(1, 7));
2515 assert_eq!(bf, BitField::from_bin_str("0101 1111 0000 10"));
2516 bf.truncate_be(BitIndex::new(1, 2));
2517 assert_eq!(bf, BitField::from_bin_str("0101 1111 00"));
2518 bf.truncate_be(BitIndex::new(0, 2));
2519 assert_eq!(bf, BitField::from_bin_str("01"));
2520 }
2521
2522 #[test]
2523 fn truncate_le() {
2524 let mut bf = BitField::from_bin_str("0101 1111 0000 1011 1100 0001");
2525 bf.truncate_le(BitIndex::new(2, 2));
2526 assert_eq!(bf, BitField::from_bin_str("0101 1111 0000 1011 01"));
2527 bf.truncate_le(BitIndex::new(2, 0));
2528 assert_eq!(bf, BitField::from_bin_str("0101 1111 0000 1011"));
2529 bf.truncate_le(BitIndex::new(1, 6));
2530 assert_eq!(bf, BitField::from_bin_str("0101 1111 0010 11"));
2531 bf.truncate_le(BitIndex::new(1, 6));
2532 assert_eq!(bf, BitField::from_bin_str("0101 1111 0010 11"));
2533 bf.truncate_le(BitIndex::new(1, 7));
2534 assert_eq!(bf, BitField::from_bin_str("0101 1111 0010 11"));
2535 bf.truncate_le(BitIndex::new(1, 2));
2536 assert_eq!(bf, BitField::from_bin_str("0101 1111 11"));
2537 bf.truncate_le(BitIndex::new(0, 2));
2538 assert_eq!(bf, BitField::from_bin_str("11"));
2539 }
2540
2541 #[test]
2542 fn extend_be() {
2543 let mut bf = BitField::from_bin_str("");
2544 bf.extend_be(&BitField::from_bin_str(""));
2545 assert_eq!(bf, BitField::from_bin_str(""));
2546 bf.extend_be(&BitField::from_bin_str("01"));
2547 assert_eq!(bf, BitField::from_bin_str("01"));
2548 bf.extend_be(&BitField::from_bin_str("11"));
2549 assert_eq!(bf, BitField::from_bin_str("0111"));
2550 bf.extend_be(&BitField::from_bin_str("1111 0000 1111 0000"));
2551 assert_eq!(bf, BitField::from_bin_str("0111 1111 0000 1111 0000"));
2552 bf.extend_be(&BitField::from_bin_str("0101 0"));
2553 assert_eq!(bf, BitField::from_bin_str("0111 1111 0000 1111 0000 0101 0"));
2554 bf.extend_be(&BitField::from_bin_str("0011 00"));
2555 assert_eq!(bf, BitField::from_bin_str("0111 1111 0000 1111 0000 0101 0001 100"));
2556 bf.extend_be(&BitField::from_bin_str("111"));
2557 assert_eq!(bf, BitField::from_bin_str("0111 1111 0000 1111 0000 0101 0001 1001 11"));
2558 bf.extend_be(&BitField::from_bin_str("0101 11"));
2559 assert_eq!(bf, BitField::from_bin_str("0111 1111 0000 1111 0000 0101 0001 1001 1101 0111"));
2560 bf.extend_be(&BitField::from_bin_str(""));
2561 assert_eq!(bf, BitField::from_bin_str("0111 1111 0000 1111 0000 0101 0001 1001 1101 0111"));
2562 }
2563
2564 #[test]
2565 fn extend_le() {
2566 let mut bf = BitField::from_bin_str("");
2567 bf.extend_le(&BitField::from_bin_str(""));
2568 assert_eq!(bf, BitField::from_bin_str(""));
2569 bf.extend_le(&BitField::from_bin_str("01"));
2570 assert_eq!(bf, BitField::from_bin_str("01"));
2571 bf.extend_le(&BitField::from_bin_str("11"));
2572 assert_eq!(bf, BitField::from_bin_str("1101"));
2573 bf.extend_le(&BitField::from_bin_str("1111 0000 1111 0000"));
2574 assert_eq!(bf, BitField::from_bin_str("0000 1101 0000 1111 1111"));
2575 bf.extend_le(&BitField::from_bin_str("0101 0"));
2576 assert_eq!(bf, BitField::from_bin_str("0000 1101 0000 1111 1010 1111 0"));
2577 bf.extend_le(&BitField::from_bin_str("0011 00"));
2578 assert_eq!(bf, BitField::from_bin_str("0000 1101 0000 1111 1010 1111 0011 000"));
2579 bf.extend_le(&BitField::from_bin_str("111"));
2580 assert_eq!(bf, BitField::from_bin_str("0000 1101 0000 1111 1010 1111 1001 1000 11"));
2581 bf.extend_le(&BitField::from_bin_str("0101 11"));
2582 assert_eq!(bf, BitField::from_bin_str("0000 1101 0000 1111 1010 1111 1001 1000 0101 1111"));
2583 bf.extend_le(&BitField::from_bin_str(""));
2584 assert_eq!(bf, BitField::from_bin_str("0000 1101 0000 1111 1010 1111 1001 1000 0101 1111"));
2585 // assert_eq!(bf, BitField::from_bin_str("0101 1111 0000 1111 0000 0101 0001 1001 1101 0111"));
2586 }
2587
2588 #[test]
2589 fn repeat_be() {
2590 let mut bf = BitField::from_bin_str("01");
2591 bf.repeat_be(1);
2592 assert_eq!(bf, BitField::from_bin_str("01"));
2593 bf.repeat_be(2);
2594 assert_eq!(bf, BitField::from_bin_str("0101"));
2595 bf.repeat_be(3);
2596 assert_eq!(bf, BitField::from_bin_str("0101 0101 0101"));
2597 bf.repeat_be(2);
2598 assert_eq!(bf, BitField::from_bin_str("0101 0101 0101 0101 0101 0101"));
2599 let mut bf2 = BitField::from_bin_str("01");
2600 bf.repeat_be(1000);
2601 bf2.repeat_be(12000);
2602 assert_eq!(bf, bf2);
2603 }
2604
2605 #[test]
2606 fn repeat_le() {
2607 let mut bf = BitField::from_bin_str("01");
2608 bf.repeat_le(1);
2609 assert_eq!(bf, BitField::from_bin_str("01"));
2610 bf.repeat_le(2);
2611 assert_eq!(bf, BitField::from_bin_str("0101"));
2612 bf.repeat_le(3);
2613 assert_eq!(bf, BitField::from_bin_str("0101 0101 0101"));
2614 bf.repeat_le(2);
2615 assert_eq!(bf, BitField::from_bin_str("0101 0101 0101 0101 0101 0101"));
2616 let mut bf2 = BitField::from_bin_str("01");
2617 bf.repeat_le(1000);
2618 bf2.repeat_le(12000);
2619 assert_eq!(bf, bf2);
2620 }
2621
2622 #[test]
2623 fn crc_test() {
2624 let bf = BitField::from_bin_str("11010011101100");
2625 assert_eq!(bf.crc_be(BitField::from_bin_str("000"), BitField::from_bin_str("011")), BitField::from_bin_str("100"));
2626 let bf = BitField::from_hex_str("E100CAFE");
2627 assert_eq!(bf.crc_be(BitField::from_bin_str("00000000"), BitField::from_bin_str("00110001")), BitField::from_bin_str("00100011"));
2628 assert_eq!(bf.crc_be(BitField::from_bin_str("0000000"), BitField::from_bin_str("0110001")), BitField::from_bin_str("0000001"));
2629 assert_eq!(bf.crc_be(BitField::from_bin_str("000000"), BitField::from_bin_str("011001")), BitField::from_bin_str("101100"));
2630 assert_eq!(bf.crc_be(BitField::from_bin_str("00000"), BitField::from_bin_str("01001")), BitField::from_bin_str("01010"));
2631
2632 let bf = BitField::from_hex_str("01E100CAFE");
2633 assert_eq!(bf.crc_be(BitField::from_bin_str("00000"), BitField::from_bin_str("01001")), BitField::from_bin_str("11000"));
2634
2635 let bf = BitField::from_hex_str("CAFE");
2636 assert_eq!(bf.crc_be(BitField::from_bin_str("00000000000000000"), BitField::from_bin_str("010 0101 1011 1011 01")), BitField::from_bin_str("1000 1001 1111 1111 0"));
2637
2638 let bf = BitField::from_bin_str("11101010");
2639 assert_eq!((bf.crc_be(BitField::from_bin_str("00000000"), BitField::from_bin_str("00000111"))), BitField::from_bin_str("10011000"));
2640
2641 // let bf = BitField::from_hex_str("49 48 44 52 00 00 00 20 00 00 00 20 08 02 00 00 00");
2642 // let bf = BitField::from_hex_str("92 12 22 4A 00 00 00 04 00 00 00 04 10 40 00 00 00");
2643 // let bf = BitField::from_hex_str("00 00 00 40 10 04 00 00 00 04 00 00 00 4A 22 12 92");
2644 // assert_eq!(!&(bf.crc(BitField::from_hex_str("04C11DB7"))), BitField::from_hex_str("FC18EDA3"));
2645 // assert_eq!((bf.crc(BitField::from_hex_str("2083B8ED"))), BitField::from_hex_str("FC18EDA3"));
2646 // assert_eq!((bf.crc(BitField::from_hex_str("EDB88320"))), BitField::from_hex_str("FC18EDA3"));
2647 }
2648
2649 #[test]
2650 fn bitwise() {
2651 let bf1 = BitField::from_bin_str("0101 1111 0000 1010 1100 0011");
2652 let bf2 = BitField::from_bin_str("1010 1100 1100 1001 1010 0011");
2653 assert_eq!(&bf1 & &bf2, BitField::from_bin_str("0000 1100 0000 1000 1000 0011"));
2654 assert_eq!(&bf1 | &bf2, BitField::from_bin_str("1111 1111 1100 1011 1110 0011"));
2655 assert_eq!(&bf1 ^ &bf2, BitField::from_bin_str("1111 0011 1100 0011 0110 0000"));
2656 assert_eq!(!&bf1, BitField::from_bin_str("1010 0000 1111 0101 0011 1100"));
2657 let bf1 = BitField::from_bin_str("0101 1111 0000 1010 1100");
2658 let bf2 = BitField::from_bin_str("1010 1100 1100 1001 1010 0011");
2659 assert_eq!(&bf1 & &bf2, BitField::from_bin_str("0000 1100 0000 1000 1000"));
2660 assert_eq!(&bf1 | &bf2, BitField::from_bin_str("1111 1111 1100 1011 1110"));
2661 assert_eq!(&bf1 ^ &bf2, BitField::from_bin_str("1111 0011 1100 0011 0110"));
2662 assert_eq!(!&bf1, BitField::from_bin_str("1010 0000 1111 0101 0011"));
2663 let bf1 = BitField::from_bin_str("0101 1111 0000 1010 1100 0011");
2664 let bf2 = BitField::from_bin_str("1010 1100 1100 1001 1010");
2665 assert_eq!(&bf1 & &bf2, BitField::from_bin_str("0000 1100 0000 1000 1000"));
2666 assert_eq!(&bf1 | &bf2, BitField::from_bin_str("1111 1111 1100 1011 1110"));
2667 assert_eq!(&bf1 ^ &bf2, BitField::from_bin_str("1111 0011 1100 0011 0110"));
2668 }
2669
2670 #[test]
2671 fn bitwise_assign() {
2672 let bf1 = BitField::from_bin_str("0101 1111 0000 1010 1100 0011");
2673 let bf2 = BitField::from_bin_str("1010 1100 1100 1001 1010 0011");
2674 let mut bf3 = bf1.clone();
2675 bf3 &= &bf2;
2676 assert_eq!(bf3, BitField::from_bin_str("0000 1100 0000 1000 1000 0011"));
2677 bf3 = bf1.clone();
2678 bf3 |= &bf2;
2679 assert_eq!(bf3, BitField::from_bin_str("1111 1111 1100 1011 1110 0011"));
2680 bf3 = bf1.clone();
2681 bf3 ^= &bf2;
2682 assert_eq!(bf3, BitField::from_bin_str("1111 0011 1100 0011 0110 0000"));
2683
2684 let bf1 = BitField::from_bin_str("0101 1111 0000 1010 1100");
2685 let bf2 = BitField::from_bin_str("1010 1100 1100 1001 1010 0011");
2686 bf3 = bf1.clone();
2687 bf3 &= &bf2;
2688 assert_eq!(bf3, BitField::from_bin_str("0000 1100 0000 1000 1000"));
2689 bf3 = bf1.clone();
2690 bf3 |= &bf2;
2691 assert_eq!(bf3, BitField::from_bin_str("1111 1111 1100 1011 1110"));
2692 bf3 = bf1.clone();
2693 bf3 ^= &bf2;
2694 assert_eq!(bf3, BitField::from_bin_str("1111 0011 1100 0011 0110"));
2695
2696 let bf1 = BitField::from_bin_str("0101 1111 0000 1010 1100 0011");
2697 let bf2 = BitField::from_bin_str("1010 1100 1100 1001 1010");
2698 bf3 = bf1.clone();
2699 bf3 &= &bf2;
2700 assert_eq!(bf3, BitField::from_bin_str("0000 1100 0000 1000 1000"));
2701 bf3 = bf1.clone();
2702 bf3 |= &bf2;
2703 assert_eq!(bf3, BitField::from_bin_str("1111 1111 1100 1011 1110"));
2704 bf3 = bf1.clone();
2705 bf3 ^= &bf2;
2706 assert_eq!(bf3, BitField::from_bin_str("1111 0011 1100 0011 0110"));
2707 }
2708
2709 #[test]
2710 fn shifts() {
2711 let bf = BitField::from_vec(vec![0x00, 0x00, 0xAB, 0x0F]);
2712 assert_eq!(bf.clone() << 2, BitField::from_vec(vec![0x00, 0x02, 0xAC, 0x3C]));
2713 assert_eq!(bf.clone() << 4, BitField::from_vec(vec![0x00, 0x0A, 0xB0, 0xF0]));
2714 assert_eq!(bf.clone() << 12, BitField::from_vec(vec![0x0A, 0xB0, 0xF0, 0x00]));
2715 assert_eq!(bf.clone() << 6, (bf.clone() << 4) << 2);
2716 assert_eq!(bf.clone() << 0, bf.clone());
2717
2718 assert_eq!(bf.clone() >> 2, BitField::from_vec(vec![0xC0, 0x00, 0x2A, 0xC3]));
2719 assert_eq!(bf.clone() >> 4, BitField::from_vec(vec![0xF0, 0x00, 0x0A, 0xB0]));
2720 assert_eq!(bf.clone() >> 6, (bf.clone() >> 4) >> 2);
2721 assert_eq!(bf.clone() >> 0, bf.clone());
2722
2723 // let bf = BitField::from_bin_str("1100 0000 1111 00");
2724 // let bf = bf >> 2;
2725 // assert_eq!(bf, BitField::from_bin_str("0011 0000 0011 11"));
2726 // let bf = bf >> 4;
2727 // assert_eq!(bf, BitField::from_bin_str("1100 1100 0000 11"));
2728 let bf = BitField::from_hex_str("AB CD EF 7");
2729 assert_eq!(bf.clone() >> 4, BitField::from_hex_str("7A BC DE F"));
2730 assert_eq!(bf.clone() >> 12, BitField::from_hex_str("EF 7A BC D"));
2731 }
2732
2733 #[test]
2734 fn left_shifts() {
2735 let bf = BitField::from_vec(vec![0x00, 0x00, 0xAB, 0x0F]);
2736 assert_eq!(bf.clone() << 2, BitField::from_vec(vec![0x00, 0x02, 0xAC, 0x3C]));
2737 assert_eq!(bf.clone() << 4, BitField::from_vec(vec![0x00, 0x0A, 0xB0, 0xF0]));
2738 assert_eq!(bf.clone() << 6, (bf.clone() << 4) << 2);
2739 assert_eq!(bf.clone() << 12, BitField::from_vec(vec![0x0A, 0xB0, 0xF0, 0x00]));
2740 assert_eq!(bf.clone() << 76, BitField::from_vec(vec![0x0A, 0xB0, 0xF0, 0x00]));
2741 assert_eq!(bf.clone() << 0, bf.clone());
2742 assert_eq!(bf.clone() << 64, bf.clone());
2743
2744 let bf = BitField::from_bin_str("1010 1111 0000 0101 0011");
2745 assert_eq!(bf.clone() << 2, BitField::from_bin_str("1011 1100 0001 0100 1110"));
2746 assert_eq!(bf.clone() << 4, BitField::from_bin_str("1111 0000 0101 0011 1010"));
2747 assert_eq!(bf.clone() << 6, BitField::from_bin_str("1100 0001 0100 1110 1011"));
2748 assert_eq!(bf.clone() << 26, BitField::from_bin_str("1100 0001 0100 1110 1011"));
2749 assert_eq!(bf.clone() << 46, BitField::from_bin_str("1100 0001 0100 1110 1011"));
2750 assert_eq!(bf.clone() << 206, BitField::from_bin_str("1100 0001 0100 1110 1011"));
2751 assert_eq!(bf.clone() << 20, bf.clone());
2752 assert_eq!(bf.clone() << 200, bf.clone());
2753
2754 let bf = BitField::from_bin_str("1010 1111 0000 0101 01");
2755 assert_eq!(bf.clone() << 1, BitField::from_bin_str("010 1111 0000 0101 011"));
2756 assert_eq!(bf.clone() << 3, BitField::from_bin_str("0 1111 0000 0101 01101"));
2757 assert_eq!(bf.clone() << 5, BitField::from_bin_str("111 0000 0101 011010 1"));
2758 assert_eq!(bf.clone() << 23, BitField::from_bin_str("111 0000 0101 011010 1"));
2759 assert_eq!(bf.clone() << 185, BitField::from_bin_str("111 0000 0101 011010 1"));
2760 assert_eq!(bf.clone() << 18, bf.clone());
2761 assert_eq!(bf.clone() << 180, bf.clone());
2762
2763 let bf = BitField::from_bin_str("1010 1111 0000 0101 0011 11");
2764 assert_eq!(bf.clone() << 2, BitField::from_bin_str("1011 1100 0001 0100 1111 10"));
2765 assert_eq!(bf.clone() << 4, BitField::from_bin_str("1111 0000 0101 0011 1110 10"));
2766 assert_eq!(bf.clone() << 6, BitField::from_bin_str("1100 0001 0100 1111 1010 11"));
2767 assert_eq!(bf.clone() << 28, BitField::from_bin_str("1100 0001 0100 1111 1010 11"));
2768 assert_eq!(bf.clone() << 446, BitField::from_bin_str("1100 0001 0100 1111 1010 11"));
2769 assert_eq!(bf.clone() << 22, bf.clone());
2770 assert_eq!(bf.clone() << 440, bf.clone());
2771
2772 let bf = BitField::from_bin_str("1010 1111 0000 0101 0011 110");
2773 assert_eq!(bf.clone() << 1 << 2 << 3 << 4 << 5 << 6 << 7, bf.clone() << 5);
2774 // println!("{:?}", bf.clone() << 6);
2775 // todo!();
2776 let bf = BitField::from_hex_str("AB CD EF 7");
2777 assert_eq!(bf.clone() << 4, BitField::from_hex_str("BC DE F7 A"));
2778 assert_eq!(bf.clone() << 12, BitField::from_hex_str("DE F7 AB C"));
2779 }
2780
2781 #[test]
2782 fn right_shifts() {
2783 let bf = BitField::from_vec(vec![0x00, 0x00, 0xAB, 0x0F]);
2784 assert_eq!(bf.clone() >> 2, BitField::from_vec(vec![0xC0, 0x00, 0x2A, 0xC3]));
2785 assert_eq!(bf.clone() >> 4, BitField::from_vec(vec![0xF0, 0x00, 0x0A, 0xB0]));
2786 assert_eq!(bf.clone() >> 6, (bf.clone() >> 4) >> 2);
2787 assert_eq!(bf.clone() >> 12, BitField::from_vec(vec![0xB0, 0xF0, 0x00, 0x0A]));
2788 assert_eq!(bf.clone() >> 76, BitField::from_vec(vec![0xB0, 0xF0, 0x00, 0x0A]));
2789 assert_eq!(bf.clone() >> 0, bf.clone());
2790 assert_eq!(bf.clone() >> 64, bf.clone());
2791
2792 let bf = BitField::from_bin_str("1010 1111 0000 0101 0011");
2793 assert_eq!(bf.clone() >> 2, BitField::from_bin_str("1110 1011 1100 0001 0100"));
2794 assert_eq!(bf.clone() >> 4, BitField::from_bin_str("0011 1010 1111 0000 0101"));
2795 assert_eq!(bf.clone() >> 6, BitField::from_bin_str("0100 1110 1011 1100 0001"));
2796 assert_eq!(bf.clone() >> 26, BitField::from_bin_str("0100 1110 1011 1100 0001"));
2797 assert_eq!(bf.clone() >> 46, BitField::from_bin_str("0100 1110 1011 1100 0001"));
2798 assert_eq!(bf.clone() >> 206, BitField::from_bin_str("0100 1110 1011 1100 0001"));
2799 assert_eq!(bf.clone() >> 20, bf.clone());
2800 assert_eq!(bf.clone() >> 200, bf.clone());
2801
2802 let bf = BitField::from_bin_str("1010 1111 0000 0101 01");
2803 assert_eq!(bf.clone() >> 1, BitField::from_bin_str("1101 0111 1000 0010 10"));
2804 assert_eq!(bf.clone() >> 3, BitField::from_bin_str("1011 0101 1110 0000 10"));
2805 assert_eq!(bf.clone() >> 5, BitField::from_bin_str("1010 1101 0111 1000 00"));
2806 assert_eq!(bf.clone() >> 23, BitField::from_bin_str("1010 1101 0111 1000 00"));
2807 assert_eq!(bf.clone() >> 185, BitField::from_bin_str("1010 1101 0111 1000 00"));
2808 assert_eq!(bf.clone() >> 18, bf.clone());
2809 assert_eq!(bf.clone() >> 180, bf.clone());
2810
2811 let bf = BitField::from_bin_str("1010 1111 0000 0101 0011 11");
2812 assert_eq!(bf.clone() >> 2, BitField::from_bin_str("1110 1011 1100 0001 0100 11"));
2813 assert_eq!(bf.clone() >> 4, BitField::from_bin_str("1111 1010 1111 0000 0101 00"));
2814 assert_eq!(bf.clone() >> 6, BitField::from_bin_str("0011 1110 1011 1100 0001 01"));
2815 assert_eq!(bf.clone() >> 28, BitField::from_bin_str("0011 1110 1011 1100 0001 01"));
2816 assert_eq!(bf.clone() >> 446, BitField::from_bin_str("0011 1110 1011 1100 0001 01"));
2817 assert_eq!(bf.clone() >> 22, bf.clone());
2818 assert_eq!(bf.clone() >> 440, bf.clone());
2819
2820 let bf = BitField::from_bin_str("1010 1111 0000 0101 0011 110");
2821 assert_eq!(bf.clone() >> 1 >> 2 >> 3 >> 4 >> 5 >> 6 >> 7, bf.clone() >> 5);
2822 // println!("{:?}", bf.clone() << 6);
2823 // todo!();
2824 let bf = BitField::from_hex_str("AB CD EF 7");
2825 assert_eq!(bf.clone() >> 4, BitField::from_hex_str("7A BC DE F"));
2826 assert_eq!(bf.clone() >> 12, BitField::from_hex_str("EF 7A BC D"));
2827 }
2828
2829 #[test]
2830 fn slice_le() {
2831 let mut bf = BitField::from_bin_str("0101 1100 1010 0110 0101 1001 1111 0000");
2832 // CBA KJIH GFED RQP ONML
2833 //
2834 let bf2 = bf.slice_le(&BitIndex::new(0, 5), &BitIndex::new(2, 7));
2835
2836 // HGFE DCBA PONM LKJI RQ
2837 assert_eq!(bf2, BitField::from_bin_str("0011 0010 1100 1101 10"));
2838
2839 let mut bf = BitField::from_bin_str("0101 1100 1010 0110 0101 1001 1011 0");
2840 let bf2 = bf.slice_le(&BitIndex::new(0, 5), &BitIndex::new(3, 3));
2841
2842 assert_eq!(bf2, BitField::from_bin_str("0011 0010 1100 1101 1100 10"));
2843 }
2844
2845 #[test]
2846 fn slices() {
2847 let bf = BitField::from_vec(vec![0xAB, 0xC0, 0xAB, 0xFF, 0x02]);
2848
2849 let bx1 = BitIndex::new(2, 4);
2850 let bx2 = BitIndex::new(3, 4);
2851 let s = bf.bit_slice(&bx1, &bx2);
2852 assert_eq!(s, BitField::from_vec(vec![0xBF]));
2853
2854 let bx1 = BitIndex::new(2, 0);
2855 let bx2 = BitIndex::new(3, 0);
2856 let s = bf.bit_slice(&bx1, &bx2);
2857 assert_eq!(s, BitField::from_vec(vec![0xAB]));
2858
2859 let bx1 = BitIndex::new(2, 0);
2860 let bx2 = BitIndex::new(3, 2);
2861 let s = bf.bit_slice(&bx1, &bx2);
2862 assert_eq!(s, BitField::from_bin_str("1010 1011 11"));
2863
2864 let bx1 = BitIndex::new(1, 6);
2865 let bx2 = BitIndex::new(2, 2);
2866 let s = bf.bit_slice(&bx1, &bx2);
2867 assert_eq!(s, BitField::from_bin_str("0010"));
2868
2869 let bx1 = BitIndex::new(2, 2);
2870 let bx2 = BitIndex::new(2, 6);
2871 let s = bf.bit_slice(&bx1, &bx2);
2872 assert_eq!(s, BitField::from_bin_str("1010"));
2873
2874 let bx1 = BitIndex::new(3, 4);
2875 let bx2 = BitIndex::new(5, 0);
2876 let s = bf.bit_slice(&bx1, &bx2);
2877 assert_eq!(s, BitField::from_bin_str("1111 0000 0010"));
2878 }
2879
2880 #[test]
2881 fn slices2() {
2882 let bf = BitField::from_bin_str("1100 0011 1010 01");
2883
2884 let bx1 = BitIndex::new(0, 4);
2885 let bx2 = BitIndex::new(1, 4);
2886 let s = bf.bit_slice(&bx1, &bx2);
2887 assert_eq!(s, BitField::from_bin_str("0011 1010"));
2888
2889 let bx1 = BitIndex::new(1, 2);
2890 let bx2 = BitIndex::new(1, 6);
2891 let s = bf.bit_slice(&bx1, &bx2);
2892 assert_eq!(s, BitField::from_bin_str("1001"));
2893
2894 let bx1 = BitIndex::new(0, 0);
2895 let bx2 = BitIndex::new(1, 6);
2896 let s = bf.bit_slice(&bx1, &bx2);
2897 assert_eq!(s, BitField::from_bin_str("1100 0011 1010 01"));
2898 }
2899
2900 /*
2901 #[test]
2902 fn slices_le() {
2903 let bf1 = BitField::from_bin_str("0101 1111 0000 1010 1100 0011 0110 1001");
2904 let bf2 = BitField::from_bin_str("0110 1001 1100 0011 0000 1010 0101 1111");
2905 for i in 0..32 {
2906 for j in i..32 {
2907 let start = BitIndex::bits(i);
2908 let end = BitIndex::bits(j+1);
2909 let mut be_slice = bf1.slice_be(&start, &end);
2910 be_slice.pad_unsigned_be(BitIndex::bits(32));
2911 let mut le_slice = bf2.slice_le2(&start, &end);
2912 le_slice.pad_unsigned_le(BitIndex::bits(32));
2913 assert_eq!(u32::from_be_bytes(be_slice.into_array().unwrap()), u32::from_le_bytes(le_slice.into_array().unwrap()))
2914
2915 }
2916 }
2917
2918 // let bf1 = BitField::from_bin_str("0101 1111 0000 1010 1100 0011 0110 1001 011");
2919 // let mut bf2 = bf1.clone();
2920 // bf2.swap_be_to_le();
2921 // for i in 0..35 {
2922 // for j in i..35 {
2923 // let start = BitIndex::bits(i);
2924 // let end = BitIndex::bits(j+1);
2925 // let mut be_slice = bf1.slice_be(&start, &end);
2926 // be_slice.pad_unsigned_be(BitIndex::bits(32));
2927 // let mut le_slice = bf2.slice_le2(&start, &end);
2928 // le_slice.pad_unsigned_le(BitIndex::bits(32));
2929 // assert_eq!(u32::from_be_bytes(be_slice.into_array().unwrap()), u32::from_le_bytes(le_slice.into_array().unwrap()))
2930
2931 // }
2932 // }
2933 }
2934 */
2935
2936 #[test]
2937 fn float_tests() {
2938 let frac: u32 = 4788187;
2939 let exp: u8 = 128;
2940
2941 let bf = BitField::from_vec(frac.to_be_bytes().to_vec());
2942 let mut bf2 = BitField::zeros(BitIndex::new(0, 1));
2943 bf2.extend_be(&BitField::from_vec(vec![exp]));
2944 bf2.extend_be(&BitField::zeros(BitIndex::bits(23)));
2945 bf2 = &bf2 | &bf;
2946 let result = f32::from_be_bytes(bf2.clone().into_array().unwrap());
2947 assert_eq!(result, std::f32::consts::PI);
2948 let mut frac_slice = bf2.slice_be(&BitIndex::bits(9), &BitIndex::bits(32));
2949 frac_slice.pad_unsigned_be(BitIndex::bits(32));
2950 assert_eq!(u32::from_be_bytes(frac_slice.into_array().unwrap()), frac);
2951 let exp_slice = bf2.slice_be(&BitIndex::bits(1), &BitIndex::bits(9));
2952 assert_eq!(u8::from_be_bytes(exp_slice.into_array().unwrap()), exp);
2953 // panic!("{}", result)
2954 }
2955
2956 #[test]
2957 fn extract_u8() {
2958 let bf = BitField::from_bin_str("0011 1000 1010 0101 1110");
2959 assert_eq!(bf.extract_u8(BitIndex::new(0, 0)), 0x38);
2960 assert_eq!(bf.extract_u8(BitIndex::new(0, 1)), 0x71);
2961 assert_eq!(bf.extract_u8(BitIndex::new(0, 2)), 0xe2);
2962 assert_eq!(bf.extract_u8(BitIndex::new(0, 3)), 0xc5);
2963 assert_eq!(bf.extract_u8(BitIndex::new(0, 4)), 0x8a);
2964 assert_eq!(bf.extract_u8(BitIndex::new(0, 5)), 0x14);
2965 assert_eq!(bf.extract_u8(BitIndex::new(0, 6)), 0x29);
2966 assert_eq!(bf.extract_u8(BitIndex::new(0, 7)), 0x52);
2967 assert_eq!(bf.extract_u8(BitIndex::new(1, 0)), 0xa5);
2968
2969 let bf = BitField::from_bin_str("0011 1000 1010 0101 11");
2970 assert_eq!(bf.extract_u8_cyclical(BitIndex::new(0, 0)), 0x38);
2971 assert_eq!(bf.extract_u8_cyclical(BitIndex::new(0, 2)), 0xe2);
2972 assert_eq!(bf.extract_u8_cyclical(BitIndex::new(0, 4)), 0x8a);
2973 assert_eq!(bf.extract_u8_cyclical(BitIndex::new(0, 6)), 0x29);
2974 assert_eq!(bf.extract_u8_cyclical(BitIndex::new(1, 0)), 0xa5);
2975 assert_eq!(bf.extract_u8_cyclical(BitIndex::new(1, 2)), 0x97);
2976 assert_eq!(bf.extract_u8_cyclical(BitIndex::new(1, 4)), 0x5c);
2977 assert_eq!(bf.extract_u8_cyclical(BitIndex::new(1, 6)), 0x73);
2978 assert_eq!(bf.extract_u8_cyclical(BitIndex::new(2, 0)), 0xce);
2979
2980 assert_eq!(bf.extract_u8_cyclical(BitIndex::new(2, 2)), 0x38);
2981 assert_eq!(bf.extract_u8_cyclical(BitIndex::new(3, 4)), 0x97);
2982
2983 assert_eq!(bf.extract_u8_cyclical(-BitIndex::new(0, 4)), 0x73);
2984 }
2985
2986 #[test]
2987 fn pad_unsigned() {
2988 let mut bf = BitField::from_bin_str("1010 0011 10");
2989 bf.pad_unsigned_le(BitIndex::new(1, 3));
2990 assert_eq!(bf, BitField::from_bin_str("1010 0011 010"));
2991 bf.pad_unsigned_le(BitIndex::new(1, 4));
2992 assert_eq!(bf, BitField::from_bin_str("1010 0011 0010"));
2993 bf.pad_unsigned_le(BitIndex::new(1, 5));
2994 assert_eq!(bf, BitField::from_bin_str("1010 0011 0001 0"));
2995 bf.pad_unsigned_le(BitIndex::new(1, 6));
2996 assert_eq!(bf, BitField::from_bin_str("1010 0011 0000 10"));
2997 bf.pad_unsigned_le(BitIndex::new(1, 7));
2998 assert_eq!(bf, BitField::from_bin_str("1010 0011 0000 010"));
2999 bf.pad_unsigned_le(BitIndex::new(2, 0));
3000 assert_eq!(bf, BitField::from_bin_str("1010 0011 0000 0010"));
3001
3002 bf.pad_unsigned_le(BitIndex::new(2, 4));
3003 assert_eq!(bf, BitField::from_bin_str("1010 0011 0000 0010 0000"));
3004 bf.pad_unsigned_le(BitIndex::new(3, 0));
3005 assert_eq!(bf, BitField::from_bin_str("1010 0011 0000 0010 0000 0000"));
3006
3007 let mut bf = BitField::from_bin_str("1010 0011");
3008 bf.pad_unsigned_le(BitIndex::new(1, 4));
3009 assert_eq!(bf, BitField::from_bin_str("1010 0011 0000"));
3010
3011 let mut bf = BitField::from_bin_str("1010 0011 10");
3012 bf.pad_unsigned_be(BitIndex::new(1, 3));
3013 assert_eq!(bf, BitField::from_bin_str("0101 0001 110"));
3014 bf.pad_unsigned_be(BitIndex::new(1, 4));
3015 assert_eq!(bf, BitField::from_bin_str("0010 1000 1110"));
3016 bf.pad_unsigned_be(BitIndex::new(1, 5));
3017 assert_eq!(bf, BitField::from_bin_str("0001 0100 0111 0"));
3018 bf.pad_unsigned_be(BitIndex::new(1, 6));
3019 assert_eq!(bf, BitField::from_bin_str("0000 1010 0011 10"));
3020 bf.pad_unsigned_be(BitIndex::new(1, 7));
3021 assert_eq!(bf, BitField::from_bin_str("0000 0101 0001 110"));
3022 bf.pad_unsigned_be(BitIndex::new(2, 0));
3023 assert_eq!(bf, BitField::from_bin_str("0000 0010 1000 1110"));
3024
3025 bf.pad_unsigned_be(BitIndex::new(2, 4));
3026 assert_eq!(bf, BitField::from_bin_str("0000 0000 0010 1000 1110"));
3027 bf.pad_unsigned_be(BitIndex::new(3, 0));
3028 assert_eq!(bf, BitField::from_bin_str("0000 0000 0000 0010 1000 1110"));
3029
3030 let mut bf = BitField::from_bin_str("1010 0011");
3031 bf.pad_unsigned_be(BitIndex::new(1, 4));
3032 assert_eq!(bf, BitField::from_bin_str("0000 1010 0011"));
3033 }
3034
3035 #[test]
3036 fn pad_twos_compliment() {
3037 // Negative little-endian
3038 let mut bf = BitField::from_bin_str("1010 0011 10");
3039 bf.pad_twos_compliment_le(BitIndex::new(1, 3));
3040 assert_eq!(bf, BitField::from_bin_str("1010 0011 110"));
3041 bf.pad_twos_compliment_le(BitIndex::new(1, 4));
3042 assert_eq!(bf, BitField::from_bin_str("1010 0011 1110"));
3043 bf.pad_twos_compliment_le(BitIndex::new(1, 5));
3044 assert_eq!(bf, BitField::from_bin_str("1010 0011 1111 0"));
3045 bf.pad_twos_compliment_le(BitIndex::new(1, 6));
3046 assert_eq!(bf, BitField::from_bin_str("1010 0011 1111 10"));
3047 bf.pad_twos_compliment_le(BitIndex::new(1, 7));
3048 assert_eq!(bf, BitField::from_bin_str("1010 0011 1111 110"));
3049 bf.pad_twos_compliment_le(BitIndex::new(2, 0));
3050 assert_eq!(bf, BitField::from_bin_str("1010 0011 1111 1110"));
3051
3052 bf.pad_twos_compliment_le(BitIndex::new(2, 4));
3053 assert_eq!(bf, BitField::from_bin_str("1010 0011 1111 1110 1111"));
3054 bf.pad_twos_compliment_le(BitIndex::new(3, 0));
3055 assert_eq!(bf, BitField::from_bin_str("1010 0011 1111 1110 1111 1111"));
3056
3057 let mut bf = BitField::from_bin_str("1010 0011");
3058 bf.pad_twos_compliment_le(BitIndex::new(1, 4));
3059 assert_eq!(bf, BitField::from_bin_str("1010 0011 1111"));
3060
3061 // Positive little-endian
3062 let mut bf = BitField::from_bin_str("1010 0011 01");
3063 bf.pad_twos_compliment_le(BitIndex::new(1, 3));
3064 assert_eq!(bf, BitField::from_bin_str("1010 0011 001"));
3065 bf.pad_twos_compliment_le(BitIndex::new(1, 4));
3066 assert_eq!(bf, BitField::from_bin_str("1010 0011 0001"));
3067 bf.pad_twos_compliment_le(BitIndex::new(1, 5));
3068 assert_eq!(bf, BitField::from_bin_str("1010 0011 0000 1"));
3069 bf.pad_twos_compliment_le(BitIndex::new(1, 6));
3070 assert_eq!(bf, BitField::from_bin_str("1010 0011 0000 01"));
3071 bf.pad_twos_compliment_le(BitIndex::new(1, 7));
3072 assert_eq!(bf, BitField::from_bin_str("1010 0011 0000 001"));
3073 bf.pad_twos_compliment_le(BitIndex::new(2, 0));
3074 assert_eq!(bf, BitField::from_bin_str("1010 0011 0000 0001"));
3075
3076 bf.pad_twos_compliment_le(BitIndex::new(2, 4));
3077 assert_eq!(bf, BitField::from_bin_str("1010 0011 0000 0001 0000"));
3078 bf.pad_twos_compliment_le(BitIndex::new(3, 0));
3079 assert_eq!(bf, BitField::from_bin_str("1010 0011 0000 0001 0000 0000"));
3080
3081 let mut bf = BitField::from_bin_str("0110 0011");
3082 bf.pad_twos_compliment_le(BitIndex::new(1, 4));
3083 assert_eq!(bf, BitField::from_bin_str("0110 0011 0000"));
3084 }
3085
3086 #[test]
3087 fn pad_sign_magnitude() {
3088 // Negative big-endian
3089 let mut bf = BitField::from_bin_str("1010 0011 10");
3090 bf.pad_sign_magnitude_be(BitIndex::new(1, 3));
3091 assert_eq!(bf, BitField::from_bin_str("1001 0001 110"));
3092 bf.pad_sign_magnitude_be(BitIndex::new(1, 4));
3093 assert_eq!(bf, BitField::from_bin_str("1000 1000 1110"));
3094 bf.pad_sign_magnitude_be(BitIndex::new(1, 5));
3095 assert_eq!(bf, BitField::from_bin_str("1000 0100 0111 0"));
3096 bf.pad_sign_magnitude_be(BitIndex::new(1, 6));
3097 assert_eq!(bf, BitField::from_bin_str("1000 0010 0011 10"));
3098 bf.pad_sign_magnitude_be(BitIndex::new(1, 7));
3099 assert_eq!(bf, BitField::from_bin_str("1000 0001 0001 110"));
3100 bf.pad_sign_magnitude_be(BitIndex::new(2, 0));
3101 assert_eq!(bf, BitField::from_bin_str("1000 0000 1000 1110"));
3102
3103 bf.pad_sign_magnitude_be(BitIndex::new(2, 4));
3104 assert_eq!(bf, BitField::from_bin_str("1000 0000 0000 1000 1110"));
3105 bf.pad_sign_magnitude_be(BitIndex::new(3, 0));
3106 assert_eq!(bf, BitField::from_bin_str("1000 0000 0000 0000 1000 1110"));
3107
3108 let mut bf = BitField::from_bin_str("1010 0011");
3109 bf.pad_sign_magnitude_be(BitIndex::new(1, 4));
3110 assert_eq!(bf, BitField::from_bin_str("1000 0010 0011"));
3111
3112 // Positive big-endian
3113 let mut bf = BitField::from_bin_str("0110 0011 10");
3114 bf.pad_sign_magnitude_be(BitIndex::new(1, 3));
3115 assert_eq!(bf, BitField::from_bin_str("0011 0001 110"));
3116 bf.pad_sign_magnitude_be(BitIndex::new(1, 4));
3117 assert_eq!(bf, BitField::from_bin_str("0001 1000 1110"));
3118 bf.pad_sign_magnitude_be(BitIndex::new(1, 5));
3119 assert_eq!(bf, BitField::from_bin_str("0000 1100 0111 0"));
3120 bf.pad_sign_magnitude_be(BitIndex::new(1, 6));
3121 assert_eq!(bf, BitField::from_bin_str("0000 0110 0011 10"));
3122 bf.pad_sign_magnitude_be(BitIndex::new(1, 7));
3123 assert_eq!(bf, BitField::from_bin_str("0000 0011 0001 110"));
3124 bf.pad_sign_magnitude_be(BitIndex::new(2, 0));
3125 assert_eq!(bf, BitField::from_bin_str("0000 0001 1000 1110"));
3126
3127 bf.pad_sign_magnitude_be(BitIndex::new(2, 4));
3128 assert_eq!(bf, BitField::from_bin_str("0000 0000 0001 1000 1110"));
3129 bf.pad_sign_magnitude_be(BitIndex::new(3, 0));
3130 assert_eq!(bf, BitField::from_bin_str("0000 0000 0000 0001 1000 1110"));
3131
3132 let mut bf = BitField::from_bin_str("0110 0011");
3133 bf.pad_sign_magnitude_be(BitIndex::new(1, 4));
3134 assert_eq!(bf, BitField::from_bin_str("0000 0110 0011"));
3135
3136 // Negative little-endian
3137 let mut bf = BitField::from_bin_str("1010 0011 10");
3138 bf.pad_sign_magnitude_le(BitIndex::new(1, 3));
3139 assert_eq!(bf, BitField::from_bin_str("1010 0011 100"));
3140 bf.pad_sign_magnitude_le(BitIndex::new(1, 4));
3141 assert_eq!(bf, BitField::from_bin_str("1010 0011 1000"));
3142 bf.pad_sign_magnitude_le(BitIndex::new(1, 5));
3143 assert_eq!(bf, BitField::from_bin_str("1010 0011 1000 0"));
3144 bf.pad_sign_magnitude_le(BitIndex::new(1, 6));
3145 assert_eq!(bf, BitField::from_bin_str("1010 0011 1000 00"));
3146 bf.pad_sign_magnitude_le(BitIndex::new(1, 7));
3147 assert_eq!(bf, BitField::from_bin_str("1010 0011 1000 000"));
3148 bf.pad_sign_magnitude_le(BitIndex::new(2, 0));
3149 assert_eq!(bf, BitField::from_bin_str("1010 0011 1000 0000"));
3150
3151 bf.pad_sign_magnitude_le(BitIndex::new(2, 4));
3152 assert_eq!(bf, BitField::from_bin_str("1010 0011 0000 0000 1000"));
3153 bf.pad_sign_magnitude_le(BitIndex::new(3, 0));
3154 assert_eq!(bf, BitField::from_bin_str("1010 0011 0000 0000 1000 0000"));
3155
3156 let mut bf = BitField::from_bin_str("1010 0011");
3157 bf.pad_sign_magnitude_le(BitIndex::new(1, 4));
3158 assert_eq!(bf, BitField::from_bin_str("0010 0011 1000"));
3159
3160 // Positive little-endian
3161 let mut bf = BitField::from_bin_str("1010 0011 01");
3162 bf.pad_sign_magnitude_le(BitIndex::new(1, 3));
3163 assert_eq!(bf, BitField::from_bin_str("1010 0011 001"));
3164 bf.pad_sign_magnitude_le(BitIndex::new(1, 4));
3165 assert_eq!(bf, BitField::from_bin_str("1010 0011 0001"));
3166 bf.pad_sign_magnitude_le(BitIndex::new(1, 5));
3167 assert_eq!(bf, BitField::from_bin_str("1010 0011 0000 1"));
3168 bf.pad_sign_magnitude_le(BitIndex::new(1, 6));
3169 assert_eq!(bf, BitField::from_bin_str("1010 0011 0000 01"));
3170 bf.pad_sign_magnitude_le(BitIndex::new(1, 7));
3171 assert_eq!(bf, BitField::from_bin_str("1010 0011 0000 001"));
3172 bf.pad_sign_magnitude_le(BitIndex::new(2, 0));
3173 assert_eq!(bf, BitField::from_bin_str("1010 0011 0000 0001"));
3174
3175 bf.pad_sign_magnitude_le(BitIndex::new(2, 4));
3176 assert_eq!(bf, BitField::from_bin_str("1010 0011 0000 0001 0000"));
3177 bf.pad_sign_magnitude_le(BitIndex::new(3, 0));
3178 assert_eq!(bf, BitField::from_bin_str("1010 0011 0000 0001 0000 0000"));
3179
3180 let mut bf = BitField::from_bin_str("0110 0011");
3181 bf.pad_sign_magnitude_le(BitIndex::new(1, 4));
3182 assert_eq!(bf, BitField::from_bin_str("0110 0011 0000"));
3183 }
3184
3185 #[test]
3186 fn int_conversions_be() {
3187 let mut bf = BitField::from_hex_str("00 01 e2 40"); // +123456 in sign-magnitude
3188 assert_eq!(bf.convert_unsigned_be(IntFormat::SignMagnitude), false);
3189 assert_eq!(u32::from_be_bytes(bf.into_array().unwrap()), 123456);
3190
3191 for i in 32..64 {
3192 let mut bf = BitField::from_hex_str("00 01 e2 40"); // +123456 in sign-magnitude
3193 bf.pad_sign_magnitude_be(BitIndex::bits(i));
3194 assert_eq!(bf.convert_unsigned_be(IntFormat::SignMagnitude), false);
3195 bf.pad_unsigned_be(BitIndex::new(8, 0));
3196 assert_eq!(u64::from_be_bytes(bf.into_array().unwrap()), 123456);
3197 }
3198
3199 let mut bf = BitField::from_hex_str("80 01 e2 40"); // -123456 in sign-magnitude
3200 assert_eq!(bf.convert_unsigned_be(IntFormat::SignMagnitude), true);
3201 assert_eq!(u32::from_be_bytes(bf.into_array().unwrap()), 123456);
3202
3203 for i in 32..64 {
3204 let mut bf = BitField::from_hex_str("80 01 e2 40"); // -123456 in sign-magnitude
3205 bf.pad_sign_magnitude_be(BitIndex::bits(i));
3206 assert_eq!(bf.convert_unsigned_be(IntFormat::SignMagnitude), true);
3207 bf.pad_unsigned_be(BitIndex::new(8, 0));
3208 assert_eq!(u64::from_be_bytes(bf.into_array().unwrap()), 123456);
3209 }
3210
3211 let mut bf = BitField::from_hex_str("00 01 e2 40"); // +123456 in two's complement
3212 assert_eq!(bf.convert_unsigned_be(IntFormat::TwosCompliment), false);
3213 assert_eq!(u32::from_be_bytes(bf.into_array().unwrap()), 123456);
3214
3215 for i in 32..64 {
3216 let mut bf = BitField::from_hex_str("00 01 e2 40"); // +123456 in two's complement
3217 bf.pad_twos_compliment_be(BitIndex::bits(i));
3218 assert_eq!(bf.convert_unsigned_be(IntFormat::TwosCompliment), false);
3219 bf.pad_unsigned_be(BitIndex::new(8, 0));
3220 assert_eq!(u64::from_be_bytes(bf.into_array().unwrap()), 123456);
3221 }
3222
3223 let mut bf = BitField::from_hex_str("ff fe 1d c0"); // -123456 in two's complement
3224 assert_eq!(bf.convert_unsigned_be(IntFormat::TwosCompliment), true);
3225 assert_eq!(u32::from_be_bytes(bf.into_array().unwrap()), 123456);
3226
3227 for i in 32..64 {
3228 let mut bf = BitField::from_hex_str("ff fe 1d c0"); // -123456 in two's complement
3229 bf.pad_twos_compliment_be(BitIndex::bits(i));
3230 assert_eq!(bf.convert_unsigned_be(IntFormat::TwosCompliment), true);
3231 bf.pad_unsigned_be(BitIndex::new(8, 0));
3232 assert_eq!(u64::from_be_bytes(bf.into_array().unwrap()), 123456);
3233 }
3234
3235 let mut bf = BitField::from_hex_str("00 01 e2 40"); // +123456 in one's complement
3236 assert_eq!(bf.convert_unsigned_be(IntFormat::OnesCompliment), false);
3237 assert_eq!(u32::from_be_bytes(bf.into_array().unwrap()), 123456);
3238
3239 for i in 32..64 {
3240 let mut bf = BitField::from_hex_str("00 01 e2 40"); // +123456 in one's complement
3241 bf.pad_twos_compliment_be(BitIndex::bits(i));
3242 assert_eq!(bf.convert_unsigned_be(IntFormat::OnesCompliment), false);
3243 bf.pad_unsigned_be(BitIndex::new(8, 0));
3244 assert_eq!(u64::from_be_bytes(bf.into_array().unwrap()), 123456);
3245 }
3246
3247 let mut bf = BitField::from_hex_str("ff fe 1d bf"); // -123456 in one's complement
3248 assert_eq!(bf.convert_unsigned_be(IntFormat::OnesCompliment), true);
3249 assert_eq!(u32::from_be_bytes(bf.into_array().unwrap()), 123456);
3250
3251 for i in 32..64 {
3252 let mut bf = BitField::from_hex_str("ff fe 1d bf"); // -123456 in one's complement
3253 bf.pad_twos_compliment_be(BitIndex::bits(i));
3254 assert_eq!(bf.convert_unsigned_be(IntFormat::OnesCompliment), true);
3255 bf.pad_unsigned_be(BitIndex::new(8, 0));
3256 assert_eq!(u64::from_be_bytes(bf.into_array().unwrap()), 123456);
3257 }
3258
3259 let mut bf = BitField::from_hex_str("00 06 26 40"); // +123456 in base -2
3260 assert_eq!(bf.convert_unsigned_be(IntFormat::BaseMinusTwo), false);
3261 assert_eq!(u32::from_be_bytes(bf.into_array().unwrap()), 123456);
3262
3263
3264 for i in 32..64 {
3265 let mut bf = BitField::from_hex_str("00 06 26 40"); // +123456 in base -2
3266 bf.pad_unsigned_be(BitIndex::bits(i));
3267 assert_eq!(bf.convert_unsigned_be(IntFormat::BaseMinusTwo), false);
3268 bf.pad_unsigned_be(BitIndex::new(8, 0));
3269 assert_eq!(u64::from_be_bytes(bf.into_array().unwrap()), 123456);
3270 }
3271
3272 let mut bf = BitField::from_hex_str("00 02 62 c0"); // -123456 in base -2
3273 assert_eq!(bf.convert_unsigned_be(IntFormat::BaseMinusTwo), true);
3274 assert_eq!(u32::from_be_bytes(bf.into_array().unwrap()), 123456);
3275
3276 for i in 32..64 {
3277 let mut bf = BitField::from_hex_str("00 02 62 c0"); // -123456 in base -2
3278 bf.pad_unsigned_be(BitIndex::bits(i));
3279 assert_eq!(bf.convert_unsigned_be(IntFormat::BaseMinusTwo), true);
3280 bf.pad_unsigned_be(BitIndex::new(8, 0));
3281 assert_eq!(u64::from_be_bytes(bf.into_array().unwrap()), 123456);
3282 }
3283 }
3284
3285 #[test]
3286 fn int_conversions_le() {
3287 let mut bf = BitField::from_hex_str("40 e2 01 00"); // +123456 in sign-magnitude
3288 assert_eq!(bf.convert_unsigned_le(IntFormat::SignMagnitude), false);
3289 assert_eq!(u32::from_le_bytes(bf.into_array().unwrap()), 123456);
3290
3291 for i in 32..64 {
3292 let mut bf = BitField::from_hex_str("40 e2 01 00"); // +123456 in sign-magnitude
3293 bf.pad_sign_magnitude_le(BitIndex::bits(i));
3294 assert_eq!(bf.convert_unsigned_le(IntFormat::SignMagnitude), false);
3295 bf.pad_unsigned_le(BitIndex::new(8, 0));
3296 assert_eq!(u64::from_le_bytes(bf.into_array().unwrap()), 123456);
3297 }
3298
3299 let mut bf = BitField::from_hex_str("40 e2 01 80"); // -123456 in sign-magnitude
3300 assert_eq!(bf.convert_unsigned_le(IntFormat::SignMagnitude), true);
3301 assert_eq!(u32::from_le_bytes(bf.into_array().unwrap()), 123456);
3302
3303 for i in 32..64 {
3304 let mut bf = BitField::from_hex_str("40 e2 01 80"); // -123456 in sign-magnitude
3305 bf.pad_sign_magnitude_le(BitIndex::bits(i));
3306 assert_eq!(bf.convert_unsigned_le(IntFormat::SignMagnitude), true);
3307 bf.pad_unsigned_le(BitIndex::new(8, 0));
3308 assert_eq!(u64::from_le_bytes(bf.into_array().unwrap()), 123456);
3309 }
3310
3311 let mut bf = BitField::from_hex_str("40 e2 01 00"); // +123456 in two's complement
3312 assert_eq!(bf.convert_unsigned_le(IntFormat::TwosCompliment), false);
3313 assert_eq!(u32::from_le_bytes(bf.into_array().unwrap()), 123456);
3314
3315 for i in 32..64 {
3316 let mut bf = BitField::from_hex_str("40 e2 01 00"); // +123456 in two's complement
3317 bf.pad_twos_compliment_le(BitIndex::bits(i));
3318 assert_eq!(bf.convert_unsigned_le(IntFormat::TwosCompliment), false);
3319 bf.pad_unsigned_le(BitIndex::new(8, 0));
3320 assert_eq!(u64::from_le_bytes(bf.into_array().unwrap()), 123456);
3321 }
3322
3323 let mut bf = BitField::from_hex_str("c0 1d fe ff"); // -123456 in two's complement
3324 assert_eq!(bf.convert_unsigned_le(IntFormat::TwosCompliment), true);
3325 assert_eq!(u32::from_le_bytes(bf.into_array().unwrap()), 123456);
3326
3327 for i in 32..64 {
3328 let mut bf = BitField::from_hex_str("c0 1d fe ff"); // -123456 in two's complement
3329 bf.pad_twos_compliment_le(BitIndex::bits(i));
3330 assert_eq!(bf.convert_unsigned_le(IntFormat::TwosCompliment), true);
3331 bf.pad_unsigned_le(BitIndex::new(8, 0));
3332 assert_eq!(u64::from_le_bytes(bf.into_array().unwrap()), 123456);
3333 }
3334
3335 let mut bf = BitField::from_hex_str("40 e2 01 00"); // +123456 in one's complement
3336 assert_eq!(bf.convert_unsigned_le(IntFormat::OnesCompliment), false);
3337 assert_eq!(u32::from_le_bytes(bf.into_array().unwrap()), 123456);
3338
3339 for i in 32..64 {
3340 let mut bf = BitField::from_hex_str("40 e2 01 00"); // +123456 in one's complement
3341 bf.pad_twos_compliment_le(BitIndex::bits(i));
3342 assert_eq!(bf.convert_unsigned_le(IntFormat::OnesCompliment), false);
3343 bf.pad_unsigned_le(BitIndex::new(8, 0));
3344 assert_eq!(u64::from_le_bytes(bf.into_array().unwrap()), 123456);
3345 }
3346
3347 let mut bf = BitField::from_hex_str("bf 1d fe ff"); // -123456 in one's complement
3348 assert_eq!(bf.convert_unsigned_le(IntFormat::OnesCompliment), true);
3349 assert_eq!(u32::from_le_bytes(bf.into_array().unwrap()), 123456);
3350
3351 for i in 32..64 {
3352 let mut bf = BitField::from_hex_str("bf 1d fe ff"); // -123456 in one's complement
3353 bf.pad_twos_compliment_le(BitIndex::bits(i));
3354 assert_eq!(bf.convert_unsigned_le(IntFormat::OnesCompliment), true);
3355 bf.pad_unsigned_le(BitIndex::new(8, 0));
3356 assert_eq!(u64::from_le_bytes(bf.into_array().unwrap()), 123456);
3357 }
3358
3359 let mut bf = BitField::from_hex_str("40 26 06 00"); // +123456 in base -2
3360 assert_eq!(bf.convert_unsigned_le(IntFormat::BaseMinusTwo), false);
3361 assert_eq!(u32::from_le_bytes(bf.into_array().unwrap()), 123456);
3362
3363
3364 for i in 32..64 {
3365 let mut bf = BitField::from_hex_str("40 26 06 00"); // +123456 in base -2
3366 bf.pad_unsigned_le(BitIndex::bits(i));
3367 assert_eq!(bf.convert_unsigned_le(IntFormat::BaseMinusTwo), false);
3368 bf.pad_unsigned_le(BitIndex::new(8, 0));
3369 assert_eq!(u64::from_le_bytes(bf.into_array().unwrap()), 123456);
3370 }
3371
3372 let mut bf = BitField::from_hex_str("c0 62 02 00"); // -123456 in base -2
3373 assert_eq!(bf.convert_unsigned_le(IntFormat::BaseMinusTwo), true);
3374 assert_eq!(u32::from_le_bytes(bf.into_array().unwrap()), 123456);
3375
3376 for i in 32..64 {
3377 let mut bf = BitField::from_hex_str("c0 62 02 00"); // -123456 in base -2
3378 bf.pad_unsigned_le(BitIndex::bits(i));
3379 assert_eq!(bf.convert_unsigned_le(IntFormat::BaseMinusTwo), true);
3380 bf.pad_unsigned_le(BitIndex::new(8, 0));
3381 assert_eq!(u64::from_le_bytes(bf.into_array().unwrap()), 123456);
3382 }
3383 }
3384}