rxing 0.8.5

A rust port of the zxing barcode library.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
/*
 * Copyright 2007 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// package com.google.zxing.common;

// import java.util.Arrays;

use std::{cmp, fmt};

use num::traits::ops::overflowing::OverflowingSub;

use crate::Exceptions;
use crate::common::Result;

type BaseType = super::BitFieldBaseType;
const BASE_BITS: usize = super::BIT_FIELD_BASE_BITS;
const SHIFT_BITS: usize = super::BIT_FIELD_SHIFT_BITS;

// replace your f32 LOAD_FACTOR with two integers:
const LF_NUM: usize = 3; // numerator of load‐factor
const LF_DEN: usize = 4; // denominator

/**
 * <p>A simple, fast array of bits, represented compactly by an array of ints internally.</p>
 *
 * @author Sean Owen
 */
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct BitArray {
    bits: Vec<BaseType>,
    size: usize,
    read_offset: usize,
    reversed: Option<Vec<BaseType>>,
}

impl BitArray {
    pub const fn new() -> Self {
        Self {
            bits: Vec::new(),
            size: 0,
            read_offset: 0,
            reversed: None,
        }
    }

    pub fn with_size(size: usize) -> Self {
        Self {
            bits: makeArray(size),
            size,
            read_offset: 0,
            reversed: None,
        }
    }

    pub fn with_capacity(size: usize) -> Self {
        Self {
            bits: makeArray(size),
            size: 0,
            read_offset: 0,
            reversed: None,
        }
    }

    /// For testing only
    #[cfg(test)]
    pub const fn with_initial_values(bits: Vec<BaseType>, size: usize) -> Self {
        Self {
            bits,
            size,
            read_offset: 0,
            reversed: None,
        }
    }

    pub const fn get_size(&self) -> usize {
        self.size
    }

    pub const fn getSizeInBytes(&self) -> usize {
        self.size.div_ceil(8)
    }

    #[inline]
    fn ensure_capacity(&mut self, new_size: usize) {
        // 1) compute target_size = ceil(new_size / (LF_NUM/LF_DEN))
        //    = ceil(new_size * LF_DEN / LF_NUM)
        let target_size = (new_size * LF_DEN).div_ceil(LF_NUM);

        // 2) compute how many BASE_BITS blocks we need, rounding up
        let array_desired_length = target_size.div_ceil(BASE_BITS);

        // 3) grow if necessary
        if self.bits.len() < array_desired_length {
            // either of these work; `resize` is a bit more direct:
            // let additional = array_desired_length - self.bits.len();
            // self.bits.extend(std::iter::repeat(0).take(additional));
            self.bits.resize(array_desired_length, 0);
        }
    }

    /**
     * @param i bit to get
     * @return true iff bit i is set
     */
    pub fn get(&self, i: usize) -> bool {
        (self.bits[i / BASE_BITS] & (1 << (i & SHIFT_BITS))) != 0
    }

    pub fn try_get(&self, i: usize) -> Option<bool> {
        if (i / BASE_BITS) >= self.bits.len() {
            None
        } else {
            Some(self.get(i))
        }
    }

    /**
     * Sets bit i.
     *
     * @param i bit to set
     */
    pub fn set(&mut self, i: usize) {
        self.reversed = None;
        self.bits[i / BASE_BITS] |= 1 << (i & SHIFT_BITS);
    }

    /**
     * Sets bit i.
     *
     * @param i bit to set
     */
    pub fn unset(&mut self, i: usize) {
        self.reversed = None;
        // self.bits[i / BASE_BITS] |= 0 << (i & SHIFT_BITS);
        self.bits[i / BASE_BITS] &= !(1 << (i & SHIFT_BITS));
    }

    /**
     * Flips bit i.
     *
     * @param i bit to set
     */
    pub fn flip(&mut self, i: usize) {
        self.reversed = None;
        self.bits[i / BASE_BITS] ^= 1 << (i & SHIFT_BITS);
    }

    /**
     * @param from first bit to check
     * @return index of first bit that is set, starting from the given index, or size if none are set
     *  at or beyond this given index
     * @see #getNextUnset(int)
     */
    pub fn getNextSet(&self, from: usize) -> usize {
        if from >= self.size {
            return self.size;
        }
        let mut bitsOffset = from / BASE_BITS;
        let mut currentBits = self.bits[bitsOffset];
        // mask off lesser bits first
        currentBits &= !((1 << (from % BASE_BITS)) - 1);
        while currentBits == 0 {
            bitsOffset += 1;
            if bitsOffset == self.bits.len() {
                return self.size;
            }
            currentBits = self.bits[bitsOffset];
        }
        let result = (bitsOffset * BASE_BITS) + currentBits.trailing_zeros() as usize;
        cmp::min(result, self.size)
    }

    /**
     * @param from index to start looking for unset bit
     * @return index of next unset bit, or {@code size} if none are unset until the end
     * @see #getNextSet(int)
     */
    pub fn getNextUnset(&self, from: usize) -> usize {
        if from >= self.size {
            return self.size;
        }
        let mut bitsOffset = from / BASE_BITS;
        let mut currentBits = !self.bits[bitsOffset];
        // mask off lesser bits first
        currentBits &= !((1 << (from % BASE_BITS)) - 1);
        while currentBits == 0 {
            bitsOffset += 1;
            if bitsOffset == self.bits.len() {
                return self.size;
            }
            currentBits = !self.bits[bitsOffset];
        }
        let result = (bitsOffset * BASE_BITS) + currentBits.trailing_zeros() as usize;
        cmp::min(result, self.size)
    }

    /**
     * Sets a block of 32 bits, starting at bit i.
     *
     * @param i first bit to set
     * @param newBits the new value of the next 32 bits. Note again that the least-significant bit
     * corresponds to bit i, the next-least-significant to i+1, and so on.
     */
    pub fn setBulk(&mut self, i: usize, newBits: BaseType) {
        self.reversed = None;
        let bits = if i % BASE_BITS != 0 {
            newBits << i
        } else {
            newBits
        };
        self.bits[i / BASE_BITS] = bits;
    }

    /**
     * Sets a range of bits.
     *
     * @param start start of range, inclusive.
     * @param end end of range, exclusive
     */
    pub fn setRange(&mut self, start: usize, end: usize) -> Result<()> {
        self.reversed = None;
        let mut end = end;
        if end < start || end > self.size {
            return Err(Exceptions::ILLEGAL_ARGUMENT);
        }
        if end == start {
            return Ok(());
        }
        end -= 1; // will be easier to treat this as the last actually set bit -- inclusive
        let firstInt = start / BASE_BITS;
        let lastInt = end / BASE_BITS;
        for i in firstInt..=lastInt {
            //for (int i = firstInt; i <= lastInt; i++) {
            let firstBit = if i > firstInt { 0 } else { start & SHIFT_BITS };
            let lastBit = if i < lastInt {
                SHIFT_BITS
            } else {
                end & SHIFT_BITS
            };
            // Ones from firstBit to lastBit, inclusive
            let mask: u64 = (2 << lastBit) - (1 << firstBit);
            self.bits[i] |= mask as BaseType;
        }
        Ok(())
    }

    /**
     * Clears all bits (sets to false).
     */
    #[inline]
    pub fn clear(&mut self) {
        self.reversed = None;
        self.bits.fill(0);
    }

    /**
     * Efficient method to check if a range of bits is set, or not set.
     *
     * @param start start of range, inclusive.
     * @param end end of range, exclusive
     * @param value if true, checks that bits in range are set, otherwise checks that they are not set
     * @return true iff all bits are set or not set in range, according to value argument
     * @throws IllegalArgumentException if end is less than start or the range is not contained in the array
     */
    pub fn isRange(&self, start: usize, end: usize, value: bool) -> Result<bool> {
        let mut end = end;
        if end < start || end > self.size {
            return Err(Exceptions::ILLEGAL_ARGUMENT);
        }
        if end == start {
            return Ok(true); // empty range matches
        }
        end -= 1; // will be easier to treat this as the last actually set bit -- inclusive
        let firstInt = start / BASE_BITS;
        let lastInt = end / BASE_BITS;
        for i in firstInt..=lastInt {
            //for (int i = firstInt; i <= lastInt; i++) {
            let firstBit = if i > firstInt { 0 } else { start & SHIFT_BITS };
            let lastBit = if i < lastInt {
                SHIFT_BITS
            } else {
                end & SHIFT_BITS
            };
            // Ones from firstBit to lastBit, inclusive
            let (mask, _): (BaseType, _) = (2 << lastBit).overflowing_sub(&(1 << firstBit));
            // let mask: u128 = (2 << lastBit) - (1 << firstBit);

            // Return false if we're looking for 1s and the masked bits[i] isn't all 1s (that is,
            // equals the mask, or we're looking for 0s and the masked portion is not all 0s
            if (self.bits[i] & mask as BaseType) != (if value { mask as BaseType } else { 0 }) {
                return Ok(false);
            }
        }
        Ok(true)
    }

    pub fn appendBit(&mut self, bit: bool) {
        self.reversed = None;
        self.ensure_capacity(self.size + 1);
        if bit {
            self.bits[self.size / BASE_BITS] |= 1 << (self.size & SHIFT_BITS);
        }
        self.size += 1;
    }

    /**
     * Appends the least-significant bits, from value, in order from most-significant to
     * least-significant. For example, appending 6 bits from 0x000001E will append the bits
     * 0, 1, 1, 1, 1, 0 in that order.
     *
     * @param value {@code int} containing bits to append
     * @param numBits bits from value to append
     */
    pub fn appendBits(&mut self, value: BaseType, num_bits: usize) -> Result<()> {
        self.reversed = None;
        if num_bits > BASE_BITS {
            return Err(Exceptions::illegal_argument_with(format!(
                "num bits must be between 0 and {}",
                BaseType::BITS
            )));
        }

        if num_bits == 0 {
            return Ok(());
        }

        let mut next_size = self.size;
        self.ensure_capacity(next_size + num_bits);
        for numBitsLeft in (0..num_bits).rev() {
            if (value & (1 << numBitsLeft)) != 0 {
                self.bits[next_size / BASE_BITS] |= 1 << (next_size & SHIFT_BITS);
            }
            next_size += 1;
        }
        self.size = next_size;
        Ok(())
    }

    pub fn appendBitArray(&mut self, other: BitArray) {
        self.appendBitArrayRef(&other)
    }

    pub fn appendBitArrayRef(&mut self, other: &BitArray) {
        let otherSize = other.size;
        self.ensure_capacity(self.size + otherSize);

        for i in 0..otherSize {
            self.appendBit(other.get(i));
        }
    }

    pub fn xor(&mut self, other: &BitArray) -> Result<()> {
        self.reversed = None;
        if self.size != other.size {
            return Err(Exceptions::illegal_argument_with("Sizes don't match"));
        }
        for (lhs, rhs) in self.bits.iter_mut().zip(other.bits.iter()) {
            //for (int i = 0; i < bits.length; i++) {
            // The last int could be incomplete (i.e. not have 32 bits in
            // it) but there is no problem since 0 XOR 0 == 0.
            *lhs ^= rhs;
        }
        Ok(())
    }

    /**
     *
     * @param bitOffset first bit to start writing
     * @param array array to write into. Bytes are written most-significant byte first. This is the opposite
     *  of the internal representation, which is exposed by {@link #getBitArray()}
     * @param offset position in array to start writing
     * @param numBytes how many bytes to write
     */
    pub fn toBytes(&self, bitOffset: usize, array: &mut [u8], offset: usize, numBytes: usize) {
        let mut bitOffset = bitOffset;
        for i in 0..numBytes {
            //for (int i = 0; i < numBytes; i++) {
            let mut the_byte = 0;
            for j in 0..8 {
                //for (int j = 0; j < 8; j++) {
                if self.get(bitOffset) {
                    the_byte |= 1 << (7 - j);
                }
                bitOffset += 1;
            }
            array[offset + i] = the_byte;
        }
    }

    /**
     * @return underlying array of ints. The first element holds the first 32 bits, and the least
     *         significant bit is bit 0.
     */
    pub fn getBitArray(&self) -> &[BaseType] {
        &self.bits
    }

    /**
     * Reverses all bits in the array.
     */
    pub fn reverse(&mut self) {
        // check if we've already done the rever operation once
        if self.reversed.is_some() {
            self.bits = self.reversed.replace(self.bits.clone()).unwrap();
            return;
        }

        // first we save off the current version as the reversed version
        self.reversed = Some(self.bits.clone());

        // reverse all int's first
        let len = (self.size - 1) / BASE_BITS;
        let oldBitsLen = len + 1;

        self.bits[..oldBitsLen].reverse();
        self.bits[..oldBitsLen]
            .iter_mut()
            .for_each(|bit_store| *bit_store = bit_store.reverse_bits());
        self.bits[oldBitsLen..].fill(0);

        // now correct the int's if the bit size isn't a multiple of 32
        if self.size != oldBitsLen * BASE_BITS {
            let leftOffset = oldBitsLen * BASE_BITS - self.size;
            let mut currentInt = self.bits[0] >> leftOffset;
            for i in 1..oldBitsLen {
                //for (int i = 1; i < oldBitsLen; i++) {
                let nextInt = self.bits[i];
                currentInt |= nextInt << (BASE_BITS - leftOffset);
                self.bits[i - 1] = currentInt;
                currentInt = nextInt >> leftOffset;
            }
            self.bits[oldBitsLen - 1] = currentInt;
        }
    }
}

impl fmt::Display for BitArray {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut _str = String::with_capacity(self.size + (self.size / 8) + 1);
        for i in 0..self.size {
            //for (int i = 0; i < size; i++) {
            if (i & 0x07) == 0 {
                _str.push(' ');
            }
            _str.push_str(if self.get(i) { "X" } else { "." });
        }
        write!(f, "{_str}")
    }
}

impl Default for BitArray {
    fn default() -> Self {
        Self::new()
    }
}

impl From<BitArray> for Vec<u8> {
    fn from(value: BitArray) -> Self {
        (&value).into()
    }
}

impl From<&BitArray> for Vec<u8> {
    fn from(value: &BitArray) -> Self {
        let mut array = vec![0; value.getSizeInBytes()];
        value.toBytes(0, &mut array, 0, value.getSizeInBytes());
        array
    }
}

impl From<BitArray> for Vec<bool> {
    fn from(value: BitArray) -> Self {
        Self::from(&value)
    }
}

impl From<&BitArray> for Vec<bool> {
    fn from(value: &BitArray) -> Self {
        let mut array = vec![false; value.size];

        for (pixel, element) in array.iter_mut().enumerate().take(value.size) {
            *element = value.get(pixel);
        }

        array
    }
}

impl From<Vec<u8>> for BitArray {
    fn from(val: Vec<u8>) -> Self {
        let mut new_array = BitArray::with_capacity(val.len());
        for (pos, byte) in val.into_iter().enumerate() {
            if byte == 0 {
                new_array.set(pos)
            }
        }
        new_array
    }
}

fn makeArray(size: usize) -> Vec<BaseType> {
    vec![0; size.div_ceil(BASE_BITS)]
}

impl std::io::Read for BitArray {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        let size = self.size;
        let desired = buf.len();
        let current_offset = self.read_offset;

        let available = size - current_offset;

        let to_read = if desired <= available {
            desired
        } else {
            available
        };

        self.toBytes(current_offset, buf, 0, to_read);

        self.read_offset = current_offset + to_read;

        Ok(to_read)
    }
}

impl std::io::Write for BitArray {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        for byte in buf {
            self.appendBits(*byte as BaseType, 8)
                .map_err(|e| std::io::Error::other(e.to_string()))?
        }
        Ok(buf.len())
    }

    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}

impl std::io::Seek for BitArray {
    fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result<u64> {
        self.read_offset = match pos {
            std::io::SeekFrom::Start(s) => s as usize,
            std::io::SeekFrom::End(e) => self.size - e as usize,
            std::io::SeekFrom::Current(c) => self.read_offset + c as usize,
        };
        Ok(self.read_offset as u64)
    }
}