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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
//! This is the main model for our ByteArray Object
use super::common::Utils;
use crate::errors::ByteArrayError;
use crate::errors::ByteArrayError::{InvalidBinaryChar, InvalidHexChar};
use crate::errors::ByteArraySecurityError::DataRemnanceRisk;
use alloc::vec;
use alloc::vec::Vec;
use core::ops::{Index, IndexMut, Range, RangeFrom, RangeFull, RangeInclusive, RangeTo};
/// Debug derive and Display is intentionally left out to avoid any intentional data leakages through formatters
#[derive(Default, Clone)] // TODO analyze security side effects of debug
pub struct ByteArray {
pub(crate) bytes: Vec<u8>,
}
impl ByteArray {
/// Standard constructor, use [`Self::with_capacity`] if you already know the capacity of your bytes for performance
/// reasons
pub fn new() -> Self {
ByteArray { bytes: vec![] }
}
/// reserves memory for a certain number of bytes for efficiency purposes
pub fn with_capacity(size_in_bytes: usize) -> Self {
Self {
bytes: Vec::with_capacity(size_in_bytes),
}
}
/// fills the byte array with zeros to capacity
/// this is usually only useful in the rare case where an odd word padding needs to be set
/// in all other cases use [`ByteArray::init_zeros`]. This function does nothing if the ByteArray
/// capacity has not been set (is 0)
///
/// # Example
/// ```
/// use byte_array_ops::model::ByteArray;
/// let arr = ByteArray::default().fill_zeros(); // does nothing on an array with zero capacity
/// assert!(arr.as_bytes().is_empty());
///
/// let arr = ByteArray::with_capacity(5).fill_zeros();
/// assert_eq!(arr.as_bytes(),[0u8,0,0,0,0]);
///
/// // or in the rare cases where a different odd word padding is set
///
/// let arr = ByteArray::with_capacity(7)
/// .fill_zeros();
///
/// assert_eq!(arr.as_bytes(),[0u8,0,0,0,0,0,0])
///
///
/// ```
///
///
#[deprecated(
since = "0.3.3",
note = "This will be renamed to with_zeros at a future version"
)]
pub fn fill_zeros(self) -> Self {
if self.bytes.capacity() == 0 {
self
} else {
ByteArray {
bytes: vec![0u8; self.bytes.capacity()],
}
}
}
/// fills the byte array with the given `value` to capacity
/// this is usually only useful in the rare case where an odd word padding needs to be set
/// in all other cases use [`ByteArray::init_value`].
///
/// # Note
/// This function does nothing (noop) if the ByteArray capacity has not been set (is 0)
///
/// # Example
/// ```
/// use byte_array_ops::model::ByteArray;
/// let arr = ByteArray::default().fill_zeros(); // does nothing on an array with zero capacity
/// assert!(arr.as_bytes().is_empty());
///
/// let arr = ByteArray::with_capacity(5).fill_with(126);
/// assert_eq!(arr.as_bytes(),[126u8,126,126,126,126]);
///
/// // or in the rare cases where a different odd word padding is set
///
/// let arr = ByteArray::with_capacity(7)
/// .fill_with(5);
///
/// assert_eq!(arr.as_bytes(),[5u8,5,5,5,5,5,5]);
///
///
/// ```
///
///
#[deprecated(
since = "0.3.3",
note = "This will be renamed to with_value at a future version"
)]
pub fn fill_with(self, value: u8) -> Self {
if self.bytes.capacity() == 0 {
self
} else {
ByteArray {
bytes: vec![value; self.bytes.capacity()],
}
}
}
/// Create a byte array from a hex string (without 0x prefix)
///
/// # Example
/// ```
/// use byte_array_ops::ByteArray;
/// let arr = ByteArray::from_hex("deadbeef")?;
/// assert_eq!(arr.as_bytes(), [0xde, 0xad, 0xbe, 0xef]);
/// # Ok::<(), byte_array_ops::errors::ByteArrayError>(())
/// ```
pub fn from_hex(hex_str: &str) -> Result<Self, ByteArrayError> {
if hex_str.is_empty() {
return Err(ByteArrayError::EmptyInput);
}
// Filter out underscores and collect
let bytes: Vec<u8> = hex_str.bytes().filter(|&b| b != b'_').collect();
// Validate characters
if let Some(&invalid) = bytes.iter().find(|&&b| !b.is_ascii_hexdigit()) {
return Err(InvalidHexChar(invalid as char));
}
let hex_count = bytes.len();
let byte_count = hex_count / 2 + hex_count % 2;
let mut ret = ByteArray::with_capacity(byte_count);
let mut start = 0;
// Handle odd length - process first char alone (LEFT padding for network byte order)
if hex_count % 2 == 1 {
ret.bytes
.push(Utils::hex_char_to_nibble_unchecked(bytes[0]));
start = 1;
}
// Process remaining pairs
for i in (start..hex_count).step_by(2) {
let byte_val = Utils::hex_char_to_nibble_unchecked(bytes[i]) << 4
| Utils::hex_char_to_nibble_unchecked(bytes[i + 1]);
ret.bytes.push(byte_val);
}
Ok(ret)
}
/// Create a byte array from a binary string (without 0b prefix)
///
/// # Example
/// ```
/// use byte_array_ops::ByteArray;
/// let arr = ByteArray::from_bin("1010010")?;
/// assert_eq!(arr.as_bytes(), [0x52]);
/// # Ok::<(), byte_array_ops::errors::ByteArrayError>(())
/// ```
pub fn from_bin(bin_str: &str) -> Result<Self, ByteArrayError> {
if bin_str.is_empty() {
return Err(ByteArrayError::EmptyInput);
}
// Filter out underscores and collect
let bytes: Vec<u8> = bin_str.bytes().filter(|&b| b != b'_').collect();
// Validate characters
if let Some(&invalid) = bytes.iter().find(|&&b| b != b'0' && b != b'1') {
return Err(InvalidBinaryChar(invalid as char));
}
let bit_count = bytes.len();
let byte_count = bit_count.div_ceil(8);
let mut ret = ByteArray::with_capacity(byte_count);
let rem = bit_count % 8;
// Handle partial first byte (left padding) OR entire input if < 8 bits
let start = if rem != 0 {
let mut byte = 0u8;
#[allow(clippy::needless_range_loop)] // our version is more readable than clippy's
for i in 0..rem {
let bit_value = bytes[i] - b'0';
byte |= bit_value << (rem - 1 - i);
}
ret.bytes.push(byte);
rem
} else {
0
};
// Process remaining full bytes (only if there are any left)
for i in (start..bit_count).step_by(8) {
let mut byte = 0u8;
for j in 0..8 {
let bit_value = bytes[i + j] - b'0';
byte |= bit_value << (7 - j);
}
ret.bytes.push(byte);
}
Ok(ret)
}
/// initialize the array with a certain amount of zeros
/// internally this creates the byte array representation with `vec![0u8;count]`
/// the rest is default initialized
pub fn init_zeros(count: usize) -> Self {
ByteArray {
bytes: vec![0u8; count],
}
}
/// initialize the array with a certain amount of `value`
/// internally this creates the byte array representation with `vec![value;count]`
/// the rest is default initialized
pub fn init_value(value: u8, count: usize) -> Self {
ByteArray {
bytes: vec![value; count],
}
}
/// returns a slices to the interior bytes
///
/// # NOTE
/// There is another method that provides a zero-cost move of the interior bytes using the
/// [`Vec::from::<ByteArray>`] implementation. Please check the [`ByteArray`]'s [`From<ByteArray>`] implementation
/// documentation
///
/// # Example
/// ```
/// use byte_array_ops::model::ByteArray;
///
/// let arr : ByteArray = "0xff2569".parse().unwrap();
///
/// let slice = arr.as_bytes();
///
/// assert_eq!(slice, [0xff,0x25,0x69]);
/// ```
///
pub fn as_bytes(&self) -> &[u8] {
&self.bytes
}
/// internal Utility to combine two bytearrays while ensuring secure reallocation
#[doc(hidden)]
#[inline(always)]
fn combine(
lhs: ByteArray,
rhs: ByteArray,
prealloc_cap: usize,
) -> Result<Self, ByteArrayError> {
const CAP_SAFETY_EXTENSION: usize = 10;
let total_cap = prealloc_cap + CAP_SAFETY_EXTENSION;
let mut buf = Vec::<u8>::with_capacity(total_cap);
let addr_pre_extend = buf.as_ptr();
buf.extend_from_slice(lhs.as_bytes());
if addr_pre_extend != buf.as_ptr() {
return Err(DataRemnanceRisk.into());
}
buf.extend_from_slice(rhs.as_bytes());
if addr_pre_extend != buf.as_ptr() {
return Err(DataRemnanceRisk.into());
}
// drop old byte buffers before creating a new byte array to avoid leaking information in case the from method was interrupted
// Note: we implement zeroize on drop
drop(lhs);
drop(rhs);
Ok(ByteArray::from(buf))
}
/// Chained constructor helper for concatening ByteArrays together into one while ensuring to unintended reallocations happens
/// to avoid data remnance.
/// Preallocate the correct size with `ByteArray::with_capacity` then unintended reallocations might happen)
///
/// # Capacity allocation caveat
/// this function adjusts the inner bytes capacity according to the sum of the lengths of the actual data of both ByteArrays,
/// if you want to preserve the capacity to be the sum of the total capacities of both arrays; then use [`ByteArray::with_extend_preserve_cap`]
///
/// # Errors
///
/// This function fails if a reallocation happens with [`crate::errors::ByteArraySecurityError::DataRemnanceRisk`]
///
/// # Example
/// ```
/// use byte_array_ops::ByteArray;
///
/// let arr1 = ByteArray::from_hex("dead")?;
/// let arr2 = ByteArray::from_hex("beef")?;
/// let result = arr1.try_extend(arr2)?;
///
/// assert_eq!(result.as_bytes(), [0xde, 0xad, 0xbe, 0xef]);
/// # Ok::<(), byte_array_ops::errors::ByteArrayError>(())
/// ```
#[inline]
pub fn try_extend(self, other: ByteArray) -> Result<Self, ByteArrayError> {
let cap = self.bytes.len() + other.bytes.len();
Self::combine(self, other, cap)
}
/// Same as [`ByteArray::try_extend`] but instead of reserving actual lengths, this reserves the
/// sum of capacities of both bytearrays
///
/// # Warning
/// For Bytearrays with very large capacities but whose actual length is very small this tends to be
/// very inefficient and might allocate too much memory on constrained environments.
/// For these cases use [`ByteArray::try_extend`] chained , this might be safer at the cost of more
/// secure reallocations
///
/// # Example
/// ```
/// use byte_array_ops::ByteArray;
///
/// let arr1 = ByteArray::with_capacity(100);
/// let arr2 = ByteArray::from_hex("ff")?;
/// let result = arr1.try_extend_with_preserve_cap(arr2)?;
///
/// // Result has the data from arr2
/// assert_eq!(result.as_bytes(), [0xff]);
/// assert_eq!(result.len(), 1);
/// # Ok::<(), byte_array_ops::errors::ByteArrayError>(())
/// ```
#[inline]
pub fn try_extend_with_preserve_cap(self, other: ByteArray) -> Result<Self, ByteArrayError> {
let cap = self.bytes.capacity() + other.bytes.capacity();
Self::combine(self, other, cap)
}
}
// index handling
impl Index<usize> for ByteArray {
type Output = u8;
/// index accessor for ByteArray
/// # Panics
/// When out of bounds. Use `ByteArray::get()` for a checked getter that returns `Option<&u8>`
fn index(&self, index: usize) -> &Self::Output {
&self.bytes[index]
}
}
impl IndexMut<usize> for ByteArray {
/// Mutable index accessor for ByteArray
/// # Panics
/// When out of bounds. Use `ByteArray::get()` for a checked getter that returns `Option<&u8>`
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
&mut self.bytes[index]
}
}
impl Index<Range<usize>> for ByteArray {
type Output = [u8];
fn index(&self, range: Range<usize>) -> &Self::Output {
&self.bytes[range]
}
}
impl Index<RangeFrom<usize>> for ByteArray {
type Output = [u8];
fn index(&self, range: RangeFrom<usize>) -> &Self::Output {
&self.bytes[range] // [2..]
}
}
impl Index<RangeTo<usize>> for ByteArray {
type Output = [u8];
fn index(&self, range: RangeTo<usize>) -> &Self::Output {
&self.bytes[range] // [..5]
}
}
impl Index<RangeInclusive<usize>> for ByteArray {
type Output = [u8];
fn index(&self, range: RangeInclusive<usize>) -> &Self::Output {
&self.bytes[range] // [2..=5]
}
}
impl Index<RangeFull> for ByteArray {
type Output = [u8];
fn index(&self, range: RangeFull) -> &Self::Output {
&self.bytes[range] // [..]
}
}
impl IndexMut<Range<usize>> for ByteArray {
fn index_mut(&mut self, range: Range<usize>) -> &mut Self::Output {
&mut self.bytes[range]
}
}
impl IndexMut<RangeFrom<usize>> for ByteArray {
fn index_mut(&mut self, range: RangeFrom<usize>) -> &mut Self::Output {
&mut self.bytes[range]
}
}
impl IndexMut<RangeTo<usize>> for ByteArray {
fn index_mut(&mut self, range: RangeTo<usize>) -> &mut Self::Output {
&mut self.bytes[range]
}
}
impl IndexMut<RangeInclusive<usize>> for ByteArray {
fn index_mut(&mut self, range: RangeInclusive<usize>) -> &mut Self::Output {
&mut self.bytes[range] // [2..=5]
}
}
impl IndexMut<RangeFull> for ByteArray {
fn index_mut(&mut self, range: RangeFull) -> &mut Self::Output {
&mut self.bytes[range] // [..]
}
}
impl AsRef<[u8]> for ByteArray {
fn as_ref(&self) -> &[u8] {
self.as_bytes()
}
}
impl AsMut<[u8]> for ByteArray {
fn as_mut(&mut self) -> &mut [u8] {
&mut self.bytes
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::try_hex;
use alloc::vec;
use core::str::FromStr;
fn is_normal<T: Sized + Send + Sync + Unpin>() {}
#[test]
fn test_thread_safety_autotraits() {
is_normal::<ByteArray>();
}
#[test]
fn test_hex_string_constructor() {
let b1: ByteArray = "0xfe81eabd5".parse().unwrap();
assert_eq!(b1.len(), 5);
assert_eq!(b1.bytes, vec![0x0f, 0xe8, 0x1e, 0xab, 0xd5]);
}
#[test]
fn test_ba_with_capacity() {
let arr = ByteArray::with_capacity(10);
assert_eq!(arr.bytes.capacity(), 10);
assert!(ByteArray::try_from(arr).is_ok());
}
#[test]
fn test_with_hex() {
let arr = ByteArray::from_hex("ffabc");
assert_eq!(arr.unwrap().bytes, vec![0x0f, 0xfa, 0xbc]);
}
#[test]
fn test_with_bin_less_than_8() {
let arr = ByteArray::from_bin("1101111").unwrap();
assert_eq!(arr.bytes, vec![0x6f]);
}
#[test]
fn test_with_bin_more_than_8() {
let arr = ByteArray::from_bin("110111010110111").unwrap();
assert_eq!(arr.bytes, vec![0x6e, 0xb7]);
}
#[test]
fn test_equality_derives() {
let arr: ByteArray = "0xffab12345ffaf".parse().unwrap();
let arr_2 = ByteArray::from_hex("ffab12345ffafdeadbeef").unwrap();
let arr_3 = arr.clone();
assert_ne!(arr.bytes, arr_2.bytes);
assert_eq!(arr.bytes, arr_3.bytes);
}
#[test]
fn test_init_zeros() {
let arr = ByteArray::init_zeros(8);
assert_eq!(arr.bytes, [0u8, 0, 0, 0, 0, 0, 0, 0]);
}
#[test]
fn test_init_value() {
let arr = ByteArray::init_value(254, 8);
assert_eq!(arr.bytes, [254, 254, 254, 254, 254, 254, 254, 254]);
}
#[test]
fn test_mutable_idx_accessor() {
let mut arr: ByteArray = "0xffab1245".parse().unwrap();
arr[3] = 0xbe;
arr[1] = 0xfa;
assert_eq!(arr.bytes, ByteArray::from_str("0xfffa12be").unwrap().bytes);
}
#[test]
#[allow(deprecated)]
fn test_fill_zeros() {
let arr = ByteArray::default().fill_zeros();
assert!(arr.as_bytes().is_empty());
let arr = ByteArray::with_capacity(5).fill_zeros();
assert_eq!(arr.as_bytes(), [0u8, 0, 0, 0, 0]);
let arr = ByteArray::with_capacity(7).fill_zeros();
assert_eq!(arr.as_bytes(), [0u8, 0, 0, 0, 0, 0, 0])
}
#[test]
#[allow(deprecated)]
fn test_fill_with() {
let arr = ByteArray::default().fill_zeros();
assert!(arr.as_bytes().is_empty());
let arr = ByteArray::with_capacity(5).fill_with(126);
assert_eq!(arr.as_bytes(), [126u8, 126, 126, 126, 126]);
let arr = ByteArray::with_capacity(7).fill_with(5);
assert_eq!(arr.as_bytes(), [5u8, 5, 5, 5, 5, 5, 5]);
}
#[test]
fn test_hex_with_underscores() {
let arr = ByteArray::from_hex("de_ad_be_ef").unwrap();
assert_eq!(arr.as_bytes(), [0xde, 0xad, 0xbe, 0xef]);
}
#[test]
fn test_bin_with_underscores() {
let arr = ByteArray::from_bin("1010_0101").unwrap();
assert_eq!(arr.as_bytes(), [0xa5]);
}
#[test]
fn test_bin_with_underscores_odd_length() {
let arr = ByteArray::from_bin("110_1111").unwrap();
assert_eq!(arr.as_bytes(), [0x6f]);
}
#[test]
#[should_panic]
fn test_as_mut_empty() {
let mut bytes = ByteArray::default();
let mut_ref = bytes.as_mut();
mut_ref[0] = 0x00;
}
#[test]
fn test_ranges() {
let bytes = try_hex!("ff_aa_fa_b8_ca_12_15_5a_5c_6f").unwrap();
assert_eq!(bytes[1..2], [0xaa]);
assert_eq!(bytes[0..=2], [0xff, 0xaa, 0xfa]);
assert_eq!(bytes[6..], [0x15, 0x5a, 0x5c, 0x6f]);
assert_eq!(bytes[..3], [0xff, 0xaa, 0xfa]);
assert_eq!(
bytes[..],
[0xff, 0xaa, 0xfa, 0xb8, 0xca, 0x12, 0x15, 0x5a, 0x5c, 0x6f]
);
}
#[test]
fn test_ranges_mut() {
let mut bytes = try_hex!("ff_aa_fa_b8_ca_12_15_5a_5c_6f").unwrap();
let slice = &mut bytes[1..3];
slice[0] = 0x00;
slice[1] = 0x01;
let expected: ByteArray = "0xff_00_01_b8_ca_12_15_5a_5c_6f".parse().unwrap();
assert_eq!(bytes, expected);
let slice = &mut bytes[0..=2];
slice[0] = 0x12;
slice[1] = 0xab;
slice[2] = 0xbc;
let expected: ByteArray = "0x12_ab_bc_b8_ca_12_15_5a_5c_6f".parse().unwrap();
assert_eq!(bytes, expected);
let slice = &mut bytes[6..];
slice[0] = 0x01;
slice[1] = 0x02;
slice[2] = 0x03;
slice[3] = 0x04;
let expected: ByteArray = "0x12_ab_bc_b8_ca_12_01_02_03_04".parse().unwrap();
assert_eq!(bytes, expected);
let slice = &mut bytes[..3];
slice[0] = 0x00;
slice[1] = 0x02;
slice[2] = 0x03;
let expected: ByteArray = "0x00_02_03_b8_ca_12_01_02_03_04".parse().unwrap();
assert_eq!(bytes, expected);
let slice = &mut bytes[..];
slice.iter_mut().for_each(|e| *e = 0x01);
let expected: ByteArray = "0x01_01_01_01_01_01_01_01_01_01".parse().unwrap();
assert_eq!(bytes, expected);
}
#[test]
fn test_as_ref() {
let bytes: ByteArray = "0x01_02_03_04_05_06_07_08".parse().unwrap();
let bytes_ref = bytes.as_ref();
assert_eq!(bytes.as_bytes(), bytes_ref);
}
#[test]
fn test_as_mut() {
let mut bytes: ByteArray = "0x01_02_03_04_05_06_07_08".parse().unwrap();
let mut_ref = bytes.as_mut();
mut_ref[0] = 0xFF;
mut_ref[5] = 0xab;
mut_ref[7] = 0x1a;
assert_eq!(
bytes.as_bytes(),
[0xff, 0x02, 0x03, 0x04, 0x05, 0xab, 0x07, 0x1a]
)
}
// try_extend edge case tests
#[test]
fn test_try_extend_both_empty() {
let arr1 = ByteArray::default();
let arr2 = ByteArray::default();
let result = arr1.try_extend(arr2).unwrap();
assert_eq!(result.len(), 0);
}
#[test]
fn test_try_extend_first_empty() {
let arr1 = ByteArray::default();
let arr2 = ByteArray::from_hex("beef").unwrap();
let result = arr1.try_extend(arr2).unwrap();
assert_eq!(result.as_bytes(), [0xbe, 0xef]);
}
#[test]
fn test_try_extend_second_empty() {
let arr1 = ByteArray::from_hex("dead").unwrap();
let arr2 = ByteArray::default();
let result = arr1.try_extend(arr2).unwrap();
assert_eq!(result.as_bytes(), [0xde, 0xad]);
}
#[test]
fn test_try_extend_small_arrays() {
let arr1 = ByteArray::from_hex("aa").unwrap();
let arr2 = ByteArray::from_hex("bb").unwrap();
let result = arr1.try_extend(arr2).unwrap();
assert_eq!(result.as_bytes(), [0xaa, 0xbb]);
assert_eq!(result.len(), 2);
}
#[test]
fn test_try_extend_preserve_cap_empty_with_capacity() {
let arr1 = ByteArray::with_capacity(50); // capacity 50, length 0
let arr2 = ByteArray::with_capacity(30); // capacity 30, length 0
let result = arr1.try_extend_with_preserve_cap(arr2).unwrap();
assert_eq!(result.len(), 0);
assert_eq!(result.bytes.capacity(), 90); // 50 + 30 + 10 safety
}
#[test]
fn test_try_extend_capacity_based_on_length() {
let arr1 = ByteArray::from_hex("aa").unwrap(); // length = 1
let arr2 = ByteArray::from_hex("bb").unwrap(); // length = 1
let result = arr1.try_extend(arr2).unwrap();
// Capacity should be based on lengths: 1 + 1 + 10 = 12
assert_eq!(result.bytes.capacity(), 12);
assert_eq!(result.as_bytes(), [0xaa, 0xbb]);
}
#[test]
fn test_try_extend_chaining() {
let arr1 = ByteArray::from_hex("aa").unwrap();
let arr2 = ByteArray::from_hex("bb").unwrap();
let arr3 = ByteArray::from_hex("cc").unwrap();
let result = arr1.try_extend(arr2).unwrap().try_extend(arr3).unwrap();
assert_eq!(result.as_bytes(), [0xaa, 0xbb, 0xcc]);
}
}