/
bitstring.rs
1819 lines (1611 loc) · 54.6 KB
/
bitstring.rs
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
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::immix::Heap;
use crate::process::RcProcess;
use crate::servo_arc::Arc;
use crate::value::{self, CastFrom, Term};
use std::cmp::Ordering;
use std::hash::{Hash, Hasher};
// use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering};
// use std::cell::UnsafeCell;
/// make_mask(n) constructs a mask with n bits.
/// Example: make_mask!(3) returns the binary number 00000111.
macro_rules! make_mask {
($n:expr) => {
// we use u16 then go down to u8 because (1 << 8) overflows
(((1 as u16) << $n) - 1) as u8
};
}
/// mask_bits assigns src to dst, but preserves the dst bits outside the mask.
macro_rules! mask_bits {
($src:expr, $dst:expr, $mask:expr) => {
($src & $mask) | ($dst & !$mask)
};
}
/// nbytes!(x) returns the number of bytes needed to store x bits.
macro_rules! nbytes {
($x:expr) => {
(($x as u64 + 7) >> 3) as usize
};
}
macro_rules! byte_offset {
($ofs:expr) => {
$ofs as usize >> 3
};
}
macro_rules! bit_offset {
($ofs:expr) => {
$ofs & 7
};
}
// TODO: replace RcBinary by a binary that keeps Bytes/BytesMut
#[derive(Debug)]
pub struct Binary {
// pub flags: AtomicUsize, // TODO use AtomicU8 once integer_atomics lands in rust 1.33
pub is_writable: bool,
/// The actual underlying bits.
pub data: Vec<u8>,
}
pub type RcBinary = Arc<Binary>;
impl Binary {
pub fn new() -> Self {
Binary {
// flags: AtomicUsize::new(0),
// WRITABLE | ACTIVE_WRITER
is_writable: true,
data: Vec::new(),
}
}
pub fn with_capacity(cap: usize) -> Self {
Binary {
// flags: AtomicUsize::new(0),
// WRITABLE | ACTIVE_WRITER
is_writable: true,
data: Vec::with_capacity(cap),
}
}
pub fn with_size(size: usize) -> Self {
Binary {
// flags: AtomicUsize::new(0),
// WRITABLE | ACTIVE_WRITER
is_writable: true,
data: vec![0; size],
}
}
#[allow(clippy::mut_from_ref)]
pub fn get_mut(&self) -> &mut Vec<u8> {
// :( we want to avoid locks so this method is for specifically when we know we're the only writer.
unsafe { &mut *(&self.data as *const Vec<u8> as *mut Vec<u8>) }
}
}
impl From<Vec<u8>> for Binary {
fn from(value: Vec<u8>) -> Self {
Binary {
// flags: AtomicUsize::new(0),
// WRITABLE | ACTIVE_WRITER
is_writable: true,
data: value,
}
}
}
impl From<&[u8]> for Binary {
fn from(value: &[u8]) -> Self {
Binary {
// flags: AtomicUsize::new(0),
// WRITABLE | ACTIVE_WRITER
is_writable: true,
data: value.to_vec(),
}
}
}
impl AsRef<[u8]> for Binary {
#[inline]
fn as_ref(&self) -> &[u8] {
self.data.as_ref()
}
}
impl AsRef<[u8]> for Arc<Binary> {
#[inline]
fn as_ref(&self) -> &[u8] {
self.data.as_ref()
}
}
impl Ord for Binary {
fn cmp(&self, other: &Binary) -> Ordering {
self.data.cmp(&other.data)
}
}
impl PartialOrd for Binary {
fn partial_cmp(&self, other: &Binary) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl PartialEq for Binary {
fn eq(&self, other: &Binary) -> bool {
self.data == other.data
}
}
impl Eq for Binary {}
impl Hash for Binary {
fn hash<H: Hasher>(&self, state: &mut H) {
self.data.hash(state)
}
}
impl CastFrom<Term> for RcBinary {
type Error = value::WrongBoxError;
#[inline]
fn cast_from(value: &Term) -> Result<&Self, value::WrongBoxError> {
if let value::Variant::Pointer(ptr) = value.into_variant() {
unsafe {
if *ptr == value::BOXED_BINARY {
return Ok(&(*(ptr as *const value::Boxed<Self>)).value);
}
}
}
Err(value::WrongBoxError)
}
}
/// Binaries are bitstrings by default, byte aligned ones are binaries.
#[derive(Clone, Debug)]
pub struct SubBinary {
// TODO: wrap into value
/// Binary size in bytes
pub size: usize,
/// Offset into binary in bytes
pub offset: usize,
/// Bit size
pub bitsize: usize,
/// Bit offset
pub bit_offset: u8,
/// Is the underlying binary writable?
pub is_writable: bool,
/// Original binary (refc or heap)
pub original: RcBinary,
} // TODO: I don't like pub here, have a method (binary_data()) or something
impl CastFrom<Term> for SubBinary {
type Error = value::WrongBoxError;
#[inline]
fn cast_from(value: &Term) -> Result<&Self, value::WrongBoxError> {
if let value::Variant::Pointer(ptr) = value.into_variant() {
unsafe {
if *ptr == value::BOXED_SUBBINARY {
return Ok(&(*(ptr as *const value::Boxed<Self>)).value);
}
}
}
Err(value::WrongBoxError)
}
}
impl SubBinary {
pub fn new(original: RcBinary, num_bits: usize, offset: usize, is_writable: bool) -> Self {
SubBinary {
original,
size: byte_offset!(num_bits),
bitsize: bit_offset!(num_bits),
offset: byte_offset!(offset),
bit_offset: bit_offset!(offset as u8), // TODO looks wrong
is_writable,
}
}
pub fn is_binary(&self) -> bool {
self.bitsize & 7 == 0
}
}
// TODO: let's use nom to handle offsets & matches, and keep a reference to the binary
// TODO: implement io::Read/io::Write
#[derive(Debug)]
pub struct MatchBuffer {
/// Original binary
pub original: RcBinary,
/// Current position in binary
// base: usize, // TODO: actually a ptr?
/// Offset in bits
pub offset: usize, // TODO: maybe don't make these pub, add a remainder method
/// Size of binary in bits
pub size: usize,
}
impl From<RcBinary> for MatchBuffer {
fn from(original: RcBinary) -> Self {
let len = original.data.len();
MatchBuffer {
original,
//base: binary_bytes(original),
offset: 0,
size: len * 8,
}
}
}
impl From<SubBinary> for MatchBuffer {
fn from(binary: SubBinary) -> Self {
// let len = binary.original.data.len();
let len = binary.size;
let offset = 8 * binary.offset + binary.bit_offset as usize;
MatchBuffer {
original: binary.original,
//base: binary_bytes(original),
offset,
size: len * 8 + offset + binary.bitsize, // + offset so that we get correct remaining()
}
}
}
impl CastFrom<Term> for MatchBuffer {
type Error = value::WrongBoxError;
#[inline]
fn cast_from(value: &Term) -> Result<&Self, value::WrongBoxError> {
if let value::Variant::Pointer(ptr) = value.into_variant() {
unsafe {
if *ptr == value::BOXED_MATCHBUFFER {
return Ok(&(*(ptr as *const value::Boxed<Self>)).value);
}
}
}
Err(value::WrongBoxError)
}
}
bitflags! {
/// Flags for bs_get_* / bs_put_* / bs_init* instructions.
pub struct Flag: u8 {
const BSF_NONE = 0;
/// Field is guaranteed to be byte-aligned. TODO: seems unused?
const BSF_ALIGNED = 1;
/// Field is little-endian (otherwise big-endian).
const BSF_LITTLE = 2;
/// Field is signed (otherwise unsigned).
const BSF_SIGNED = 4;
/// Size in bs_init is exact. TODO: seems unused?
const BSF_EXACT = 8;
/// Native endian.
const BSF_NATIVE = 16;
}
}
#[cfg(target_endian = "little")]
const NATIVE_ENDIAN: Flag = Flag::BSF_LITTLE;
#[cfg(target_endian = "big")]
const NATIVE_ENDIAN: Flag = Flag::BSF_NONE;
macro_rules! bit_is_machine_endian {
($x:expr) => {
$x & Flag::BSF_LITTLE == NATIVE_ENDIAN
};
}
#[cfg(target_endian = "little")]
macro_rules! native_endian {
($x:expr) => {
if $x.contains(Flag::BSF_NATIVE) {
$x.remove(Flag::BSF_NATIVE);
$x.insert(Flag::BSF_LITTLE);
}
};
}
#[cfg(target_endian = "big")]
macro_rules! native_endian {
($x:expr) => {
if $x.contains(Flag::BSF_NATIVE) {
$x.remove(Flag::BSF_NATIVE);
$x.remove(Flag::BSF_LITTLE);
}
};
}
macro_rules! binary_size {
($str:expr) => {
// TODO: use a trait
match $str.get_boxed_header() {
Ok(value::BOXED_BINARY) => $str.get_boxed_value::<RcBinary>().unwrap().data.len(),
Ok(value::BOXED_SUBBINARY) => {
let sub = $str.get_boxed_value::<SubBinary>().unwrap();
let mut size = sub.size;
if sub.bitsize > 0 {
// round up
size += 1;
}
size
}
_ => unreachable!(),
}
};
}
pub fn start_match_3(heap: &Heap, binary: Term) -> Option<Term> {
assert!(binary.is_bitstring());
// TODO: BEAM allocates size on all binary types right after the header so we can grab it
// without needing the binary subtype.
let total_bin_size = binary_size!(binary);
if (total_bin_size >> (8 * std::mem::size_of::<usize>() - 3)) != 0 {
// Uint => maybe u8??
return None;
}
// TODO: this is not nice
let mb = match binary.get_boxed_header() {
Ok(value::BOXED_BINARY) => {
let value = binary.get_boxed_value::<RcBinary>().unwrap().clone();
MatchBuffer::from(value)
}
Ok(value::BOXED_SUBBINARY) => {
let value = binary.get_boxed_value::<SubBinary>().unwrap().clone();
MatchBuffer::from(value)
}
_ => unreachable!(),
};
// TODO: toggle is_writable to false for rcbinary!
// pb = (ProcBin *) boxed_val(Orig);
// if (pb->thing_word == HEADER_PROC_BIN && pb->flags != 0) {
// erts_emasculate_writable_binary(pb);
// }
Some(Term::matchbuffer(heap, mb))
}
// #ifdef DEBUG
// # define CHECK_MATCH_BUFFER(MB) check_match_buffer(MB)
// static void check_match_buffer(ErlBinMatchBuffer* mb)
// {
// Eterm realbin;
// Uint byteoffs;
// byte* bytes, bitoffs, bitsz;
// ProcBin* pb;
// ERTS_GET_REAL_BIN(mb->orig, realbin, byteoffs, bitoffs, bitsz);
// bytes = binary_bytes(realbin) + byteoffs;
// ERTS_ASSERT(mb->base >= bytes && mb->base <= (bytes + binary_size(mb->orig)));
// pb = (ProcBin *) boxed_val(realbin);
// if (pb->thing_word == HEADER_PROC_BIN)
// ERTS_ASSERT(pb->flags == 0);
// }
// #else
// # define CHECK_MATCH_BUFFER(MB)
// #endif
const SMALL_BITS: usize = 64;
impl MatchBuffer {
#[inline(always)]
pub fn remaining(&self) -> usize {
self.size - self.offset
}
/// This function returns a Cow so we do zero-copy fetching if it's aligned.
pub fn get_bytes(&mut self, num_bytes: usize) -> Option<std::borrow::Cow<[u8]>> {
let num_bits = num_bytes * 8;
if self.remaining() < num_bits {
// Asked for too many bits.
return None;
}
let byte_offset = byte_offset!(self.offset);
if self.offset % 8 == 0 {
// aligned, advance cursor and return as a borrowed
self.offset += num_bits;
return Some(std::borrow::Cow::Borrowed(
&self.original.data[byte_offset..byte_offset + num_bytes],
));
}
// unaligned, copy and return as owned
let mut buf = vec![0; num_bytes];
unsafe {
copy_bits(
self.original.data.as_ptr(),
byte_offset,
1,
buf.as_mut_ptr(),
0,
1,
num_bits,
)
};
self.offset += num_bits;
Some(std::borrow::Cow::Owned(buf))
}
pub fn get_integer(&mut self, heap: &Heap, num_bits: usize, flags: Flag) -> Option<Term> {
// Uint bytes;
// Uint bits;
// Uint offs;
// byte bigbuf[64];
// byte* LSB;
// byte* MSB;
// Uint* hp;
// Uint words_needed;
// Uint actual;
// Uint v32;
// int sgn = 0;
// Eterm res = THE_NON_VALUE;
if num_bits == 0 {
return Some(Term::from(0));
}
// CHECK_MATCH_BUFFER(mb);
if self.remaining() < num_bits {
// Asked for too many bits.
return None;
}
// Special cases for field sizes up to the size of Uint.
let offs = bit_offset!(self.offset);
if num_bits <= 8 - offs {
// All bits are in one byte in the binary. We only need shift them right and mask them.
let mut b: u8 = self.original.data[byte_offset!(self.offset)];
let mask = make_mask!(num_bits);
self.offset += num_bits;
b >>= 8 - offs - num_bits;
b &= mask;
// need to transmute to signed (i8)
// if ((flags & BSF_SIGNED) && b >> (num_bits-1)) {
// b |= ~mask;
// }
return Some(Term::int(i32::from(b)));
} else if num_bits <= 8 {
/*
* The bits are in two different bytes. It is easiest to
* combine the bytes to a word first, and then shift right and
* mask to extract the bits.
*/
let byte_offset = byte_offset!(self.offset);
let mut w: u16 = (self.original.data[byte_offset] as u16) << 8
| (self.original.data[byte_offset + 1] as u16);
let mask = make_mask!(num_bits) as u16;
self.offset += num_bits;
w >>= 16 - offs - num_bits;
w &= mask;
// if ((flags & BSF_SIGNED) && w >> (num_bits-1)) {
// w |= ~mask;
// }
return Some(Term::int(i32::from(w)));
} else if num_bits < SMALL_BITS && !flags.contains(Flag::BSF_LITTLE) {
/*
* Handle field sizes from 9 up to SMALL_BITS-1 bits, big-endian,
* stored in at least two bytes.
*/
let mut byte_offset = byte_offset!(self.offset);
let mut n = num_bits;
self.offset += num_bits;
/*
* Handle the most signicant byte if it contains 1 to 7 bits.
* It only needs to be masked, not shifted.
*/
let mut w: u32;
if offs == 0 {
w = 0;
} else {
let num_bits_in_msb = 8 - offs;
w = self.original.data[byte_offset] as u32;
byte_offset += 1;
n -= num_bits_in_msb;
w &= make_mask!(num_bits_in_msb) as u32;
}
// Simply shift whole bytes into the result.
for _ in 0..byte_offset!(n) {
w = (w << 8) | (self.original.data[byte_offset] as u32);
byte_offset += 1;
}
n = bit_offset!(n);
/*
* Handle the 1 to 7 bits remaining in the last byte (if any).
* They need to be shifted right, but there is no need to mask;
* then they can be shifted into the word.
*/
if n > 0 {
let mut b: u8 = self.original.data[byte_offset];
b >>= 8 - n;
w = (w << n) | (b as u32);
}
/*
* Sign extend the result if the field type is 'signed' and the
* most significant bit is 1.
*/
// if ((flags & BSF_SIGNED) != 0 && (w >> (num_bits-1) != 0)) {
// w |= ~MAKE_MASK(num_bits);
// }
return Some(Term::uint(heap, w));
}
// TODO: this is not nice
/*
* Handle everything else, that is:
*
* Big-endian fields >= SMALL_BITS (potentially bignums).
* Little-endian fields with 9 or more bits.
*/
// bytes = NBYTES(num_bits);
// if ((bits = BIT_OFFSET(num_bits)) == 0) { /* number of bits in MSB */
// bits = 8;
// }
// offs = 8 - bits; /* adjusted offset in MSB */
//
// if (bytes <= sizeof bigbuf) {
// LSB = bigbuf;
// } else {
// LSB = erts_alloc(ERTS_ALC_T_TMP, bytes);
// }
// MSB = LSB + bytes - 1;
/*
* Move bits to temporary buffer. We want the buffer to be stored in
* little-endian order, since bignums are little-endian.
*/
// if (flags & BSF_LITTLE) {
// erts_copy_bits(mb->base, mb->offset, 1, LSB, 0, 1, num_bits);
// *MSB >>= offs; /* adjust msb */
// } else {
// *MSB = 0;
// erts_copy_bits(mb->base, mb->offset, 1, MSB, offs, -1, num_bits);
// }
// mb->offset += num_bits;
/*
* Get the sign bit.
*/
// sgn = 0;
// if ((flags & BSF_SIGNED) && (*MSB & (1<<(bits-1)))) {
// byte* ptr = LSB;
// byte c = 1;
//
// /* sign extend MSB */
// *MSB |= ~MAKE_MASK(bits);
//
// /* two's complement */
// while (ptr <= MSB) {
// byte pd = ~(*ptr);
// byte d = pd + c;
// c = (d < pd);
// *ptr++ = d;
// }
// sgn = 1;
// }
/* normalize */
// while ((*MSB == 0) && (MSB > LSB)) {
// MSB--;
// bytes--;
// }
/* check for guaranteed small num */
// switch (bytes) {
// case 1:
// v32 = LSB[0];
// goto big_small;
// case 2:
// v32 = LSB[0] + (LSB[1]<<8);
// goto big_small;
// case 3:
// v32 = LSB[0] + (LSB[1]<<8) + (LSB[2]<<16);
// goto big_small;
//#if !defined(ARCH_64)
// case 4:
// v32 = (LSB[0] + (LSB[1]<<8) + (LSB[2]<<16) + (LSB[3]<<24));
// if (!IS_USMALL(sgn, v32)) {
// goto make_big;
// }
//#else
// case 4:
// ReadToVariable(v32, LSB, 4);
// goto big_small;
// case 5:
// ReadToVariable(v32, LSB, 5);
// goto big_small;
// case 6:
// ReadToVariable(v32, LSB, 6);
// goto big_small;
// case 7:
// ReadToVariable(v32, LSB, 7);
// goto big_small;
// case 8:
// ReadToVariable(v32, LSB, 8);
// if (!IS_USMALL(sgn, v32)) {
// goto make_big;
// }
//#endif
// big_small: /* v32 loaded with value which fits in fixnum */
// if (sgn) {
// res = make_small(-((Sint)v32));
// } else {
// res = make_small(v32);
// }
// break;
// make_big:
// hp = HeapOnlyAlloc(p, BIG_UINT_HEAP_SIZE);
// if (sgn) {
// hp[0] = make_neg_bignum_header(1);
// } else {
// hp[0] = make_pos_bignum_header(1);
// }
// BIG_DIGIT(hp,0) = v32;
// res = make_big(hp);
// break;
// default:
// words_needed = 1+WSIZE(bytes);
// hp = HeapOnlyAlloc(p, words_needed);
// res = bytes_to_big(LSB, bytes, sgn, hp);
// if (is_nil(res)) {
// p->htop = hp;
// res = THE_NON_VALUE;
// } else if (is_small(res)) {
// p->htop = hp;
// } else if ((actual = bignum_header_arity(*hp)+1) < words_needed) {
// p->htop = hp + actual;
// }
// break;
// }
//
// if (LSB != bigbuf) {
// erts_free(ERTS_ALC_T_TMP, (void *) LSB);
// }
// return res;
unimplemented!(
"get_integer {:?}, num_bits {}, flags: {:?}",
self,
num_bits,
flags
);
// get_integer MatchBuffer { original: Binary { is_writable: true, data: [204, 0, 0, 0, 63, 0, 0, 0] }, offset: 0, size: 64 }, num_bits 32, flags: BSF_LITTLE'
// <<W:32/native,H:32/native>> = list_to_binary(List),
}
pub fn get_float(&mut self, _heap: &Heap, num_bits: usize, flags: Flag) -> Option<Term> {
let mut fl32: f32 = 0.0;
let mut fl64: f64 = 0.0;
// CHECK_MATCH_BUFFER(mb);
if num_bits == 0 {
return Some(Term::from(0.0));
}
if self.remaining() < num_bits {
// Asked for too many bits.
return None;
}
let fptr: *mut u8 = match num_bits {
32 => &mut fl32 as *mut f32 as *mut u8,
64 => &mut fl64 as *mut f64 as *mut u8,
_ => return None,
};
if bit_is_machine_endian!(flags) {
unsafe {
copy_bits(
self.original.data.as_ptr(),
self.offset,
1,
fptr,
0,
1,
num_bits,
)
};
} else {
unsafe {
copy_bits(
self.original.data.as_ptr(),
self.offset,
1,
fptr.add(nbytes!(num_bits) - 1),
0,
-1,
num_bits,
)
};
}
let f = if num_bits == 32 {
f64::from(fl32)
} else {
// #ifdef DOUBLE_MIDDLE_ENDIAN
// FloatDef ftmp;
// ftmp.fd = f64;
// f.fw[0] = ftmp.fw[1];
// f.fw[1] = ftmp.fw[0];
// ERTS_FP_ERROR_THOROUGH(p, f.fd, return THE_NON_VALUE);
// #else
// ...
// #endif
fl64
};
if !f.is_finite() {
return None;
}
self.offset += num_bits;
Some(Term::from(f))
}
pub fn get_binary(&mut self, heap: &Heap, num_bits: usize, _flags: Flag) -> Option<Term> {
// CHECK_MATCH_BUFFER(mb);
// Reduce the use of none by using Result.
if self.remaining() < num_bits {
// Asked for too many bits.
return None;
}
// From now on, we can't fail.
let binary = Term::subbinary(
heap,
SubBinary::new(self.original.clone(), num_bits, self.offset, false),
);
self.offset += num_bits;
Some(binary)
}
pub fn get_binary_all(&mut self, heap: &Heap, _flags: Flag) -> Option<Term> {
// CHECK_MATCH_BUFFER(mb);
let size = self.remaining();
let binary = Term::subbinary(
heap,
SubBinary::new(self.original.clone(), size, self.offset, false),
);
self.offset = size;
Some(binary)
}
/// Copy up to 4 bytes into the supplied buffer.
#[inline]
fn align_utf8_bytes(&self, buf: *mut u8) {
let bits = match self.remaining() {
0..=7 => unreachable!(),
8..=15 => 8,
16..=23 => 24,
24..=31 => 24,
_ => 32,
};
unsafe { copy_bits(self.original.data.as_ptr(), self.offset, 1, buf, 0, 1, bits) }
}
pub fn get_utf8(&mut self) -> Option<Term> {
// Number of trailing bytes for each value of the first byte.
const TRAILING_BYTES_FOR_UTF8: [u8; 256] = [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 9, 9, 9, 9, 9, 9, 9, 9,
];
// CHECK_MATCH_BUFFER(mb);
let remaining_bits = self.remaining();
if remaining_bits < 8 {
return None;
}
let mut tmp_buf: [u8; 4] = [0; 4];
let pos: &[u8] = if bit_offset!(self.offset) == 0 {
let offset = byte_offset!(self.offset);
&self.original.data[offset..]
} else {
self.align_utf8_bytes(tmp_buf.as_mut_ptr());
&tmp_buf[..]
};
let result = pos[0] as usize;
let result = match TRAILING_BYTES_FOR_UTF8[result] {
0 => {
// One byte only
self.offset += 8;
result
}
1 => {
// Two bytes
if remaining_bits < 16 {
return None;
}
let a = pos[1] as usize;
if (a & 0xC0) != 0x80 {
return None;
}
let result = (result << 6) + a - 0x0000_3080;
self.offset += 16;
result
}
2 => {
// Three bytes
if remaining_bits < 24 {
return None;
}
let a = pos[1] as usize;
let b = pos[2] as usize;
if (a & 0xC0) != 0x80 || (b & 0xC0) != 0x80 || (result == 0xE0 && a < 0xA0) {
return None;
}
let result = (((result << 6) + a) << 6) + b - 0x000E_2080;
if 0xD800 <= result && result <= 0xDFFF {
return None;
}
self.offset += 24;
result
}
3 => {
// Four bytes
if remaining_bits < 32 {
return None;
}
let a = pos[1] as usize;
let b = pos[2] as usize;
let c = pos[3] as usize;
if (a & 0xC0) != 0x80
|| (b & 0xC0) != 0x80
|| (c & 0xC0) != 0x80
|| (result == 0xF0 && a < 0x90)
{
return None;
}
let result = (((((result << 6) + a) << 6) + b) << 6) + c - 0x03C8_2080;
if result > 0x0010_FFFF {
return None;
}
self.offset += 32;
result
}
_ => unreachable!(),
};
Some(Term::int(result as i32)) // potentionally unsafe?
}
pub fn get_utf16(&mut self, flags: Flag) -> Option<Term> {
let remaining_bits = self.remaining();
if remaining_bits < 16 {
return None;
}
let mut tmp_buf: [u8; 4] = [0; 4];
// CHECK_MATCH_BUFFER(mb);
// Set up the pointer to the source bytes.
let src: &[u8] = if bit_offset!(self.offset) == 0 {
/* We can access the binary directly because the bytes are aligned. */
let offset = byte_offset!(self.offset);
&self.original.data[offset..]
} else {
/*
* We must copy the data to a temporary buffer. If possible,
* get 4 bytes, otherwise two bytes.
*/
let n = if remaining_bits < 32 { 16 } else { 32 };
unsafe {
copy_bits(
self.original.data.as_ptr(),
self.offset,
1,
tmp_buf.as_mut_ptr(),
0,
1,
n,
)
};
&tmp_buf[..]
};
// Get the first (and maybe only) 16-bit word. See if we are done.
let w1: u16 = if flags.contains(Flag::BSF_LITTLE) {
u16::from(src[0]) | (u16::from(src[1]) << 8)
} else {
(u16::from(src[0]) << 8) | u16::from(src[1])
};
if w1 < 0xD800 || w1 > 0xDFFF {
self.offset += 16;
return Some(Term::int(i32::from(w1)));
} else if w1 > 0xDBFF {
return None;
}
// Get the second 16-bit word and combine it with the first.
let w2: u16 = if remaining_bits < 32 {
return None;
} else if flags.contains(Flag::BSF_LITTLE) {
u16::from(src[2]) | (u16::from(src[3]) << 8)
} else {
(u16::from(src[2]) << 8) | u16::from(src[3])
};
if !(0xDC00 <= w2 && w2 <= 0xDFFF) {
return None;
}
self.offset += 32;
Some(Term::int(
((((w1 as u32 & 0x3FF) << 10) | (w2 as u32 & 0x3FF)) + 0x10000) as i32, // potentially unsafe
))
}
}
// Stores data on the process heap. Small, but expensive to copy.
// HeapBin(len + ptr)
// Stores data off the process heap, in an Arc<>. Cheap to copy around.
// RefBin(Arc<String/Vec<u8?>>)
// ^^ start with just RefBin since Rust already will do the String management for us
// SubBin(len (original?), offset, bitsize,bitoffset,is_writable, orig_ptr -> Bin/RefBin)
// consider using an Arc<RwLock<>> to make the inner string mutable? is the overhead worth it?
// data is always append only, so maybe have an atomic bool for the writable bit and keep the
// normal structure lockless.
macro_rules! copy_binary {
($dst:expr, $dst_offset:expr, $src:expr, $src_offset:expr, $num_bits:expr) => {
// TODO: isn't this already implemented inside copy_bits??
unsafe {
if bit_offset!($dst_offset) == 0
&& ($src_offset == 0)
&& (bit_offset!($num_bits) == 0)
&& ($num_bits != 0)
{
let byte_size = nbytes!($num_bits);
let src_slice = std::slice::from_raw_parts($src, byte_size);
let dst_slice =
std::slice::from_raw_parts_mut($dst.add(byte_offset!($dst_offset)), byte_size);
dst_slice.copy_from_slice(src_slice);
} else {
copy_bits($src, $src_offset, 1, $dst, $dst_offset, 1, $num_bits);
}