/
row.rs
2866 lines (2640 loc) · 95.7 KB
/
row.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
// Copyright Materialize, Inc. and contributors. All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0.
use std::borrow::Borrow;
use std::cell::RefCell;
use std::cmp::Ordering;
use std::convert::{TryFrom, TryInto};
use std::fmt::{self, Debug};
use std::mem::{size_of, transmute};
use std::rc::Rc;
use std::str;
use chrono::{DateTime, Datelike, NaiveDate, NaiveDateTime, NaiveTime, Timelike, Utc};
use compact_bytes::CompactBytes;
use mz_ore::cast::{CastFrom, ReinterpretCast};
use mz_ore::soft_assert_no_log;
use mz_ore::vec::Vector;
use mz_persist_types::Codec64;
use num_enum::{IntoPrimitive, TryFromPrimitive};
use ordered_float::OrderedFloat;
use proptest::prelude::*;
use proptest::strategy::{BoxedStrategy, Strategy};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::adt::array::{
Array, ArrayDimension, ArrayDimensions, InvalidArrayError, MAX_ARRAY_DIMENSIONS,
};
use crate::adt::date::Date;
use crate::adt::interval::Interval;
use crate::adt::mz_acl_item::{AclItem, MzAclItem};
use crate::adt::numeric;
use crate::adt::numeric::Numeric;
use crate::adt::range::{
self, InvalidRangeError, Range, RangeBound, RangeInner, RangeLowerBound, RangeUpperBound,
};
use crate::adt::timestamp::CheckedTimestamp;
use crate::scalar::{arb_datum, DatumKind};
use crate::{Datum, Timestamp};
pub(crate) mod encoding;
include!(concat!(env!("OUT_DIR"), "/mz_repr.row.rs"));
/// A packed representation for `Datum`s.
///
/// `Datum` is easy to work with but very space inefficient. A `Datum::Int32(42)`
/// is laid out in memory like this:
///
/// tag: 3
/// padding: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
/// data: 0 0 0 42
/// padding: 0 0 0 0 0 0 0 0 0 0 0 0
///
/// For a total of 32 bytes! The second set of padding is needed in case we were
/// to write a 16-byte datum into this location. The first set of padding is
/// needed to align that hypothetical decimal to a 16 bytes boundary.
///
/// A `Row` stores zero or more `Datum`s without any padding. We avoid the need
/// for the first set of padding by only providing access to the `Datum`s via
/// calls to `ptr::read_unaligned`, which on modern x86 is barely penalized. We
/// avoid the need for the second set of padding by not providing mutable access
/// to the `Datum`. Instead, `Row` is append-only.
///
/// A `Row` can be built from a collection of `Datum`s using `Row::pack`, but it
/// is more efficient to use `Row::pack_slice` so that a right-sized allocation
/// can be created. If that is not possible, consider using the row buffer
/// pattern: allocate one row, pack into it, and then call [`Row::clone`] to
/// receive a copy of that row, leaving behind the original allocation to pack
/// future rows.
///
/// Creating a row via [`Row::pack_slice`]:
///
/// ```
/// # use mz_repr::{Row, Datum};
/// let row = Row::pack_slice(&[Datum::Int32(0), Datum::Int32(1), Datum::Int32(2)]);
/// assert_eq!(row.unpack(), vec![Datum::Int32(0), Datum::Int32(1), Datum::Int32(2)])
/// ```
///
/// `Row`s can be unpacked by iterating over them:
///
/// ```
/// # use mz_repr::{Row, Datum};
/// let row = Row::pack_slice(&[Datum::Int32(0), Datum::Int32(1), Datum::Int32(2)]);
/// assert_eq!(row.iter().nth(1).unwrap(), Datum::Int32(1));
/// ```
///
/// If you want random access to the `Datum`s in a `Row`, use `Row::unpack` to create a `Vec<Datum>`
/// ```
/// # use mz_repr::{Row, Datum};
/// let row = Row::pack_slice(&[Datum::Int32(0), Datum::Int32(1), Datum::Int32(2)]);
/// let datums = row.unpack();
/// assert_eq!(datums[1], Datum::Int32(1));
/// ```
///
/// # Performance
///
/// Rows are dynamically sized, but up to a fixed size their data is stored in-line.
/// It is best to re-use a `Row` across multiple `Row` creation calls, as this
/// avoids the allocations involved in `Row::new()`.
#[derive(Default, Eq, PartialEq, Hash, Serialize, Deserialize)]
pub struct Row {
data: CompactBytes,
}
// Nothing depends on Row being exactly 24, we just want to add visibility to the size.
static_assertions::const_assert_eq!(std::mem::size_of::<Row>(), 24);
impl Clone for Row {
fn clone(&self) -> Self {
Row {
data: self.data.clone(),
}
}
fn clone_from(&mut self, source: &Self) {
self.data.clone_from(&source.data);
}
}
impl Arbitrary for Row {
type Parameters = prop::collection::SizeRange;
type Strategy = BoxedStrategy<Row>;
fn arbitrary_with(size: Self::Parameters) -> Self::Strategy {
prop::collection::vec(arb_datum(), size)
.prop_map(|items| {
let mut row = Row::default();
let mut packer = row.packer();
for item in items.iter() {
let datum: Datum<'_> = item.into();
packer.push(datum);
}
row
})
.boxed()
}
}
impl Row {
const SIZE: usize = CompactBytes::MAX_INLINE;
/// A variant of `Row::from_proto` that allows for reuse of internal allocs.
pub fn decode_from_proto(&mut self, proto: &ProtoRow) -> Result<(), String> {
let mut packer = self.packer();
for d in proto.datums.iter() {
packer.try_push_proto(d)?;
}
Ok(())
}
}
/// These implementations order first by length, and then by slice contents.
/// This allows many comparisons to complete without dereferencing memory.
/// Warning: These order by the u8 array representation, and NOT by Datum::cmp.
impl PartialOrd for Row {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Row {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
match self.data.len().cmp(&other.data.len()) {
std::cmp::Ordering::Less => std::cmp::Ordering::Less,
std::cmp::Ordering::Greater => std::cmp::Ordering::Greater,
std::cmp::Ordering::Equal => self.data.cmp(&other.data),
}
}
}
#[allow(missing_debug_implementations)]
mod columnation {
use columnation::{Columnation, Region};
use mz_ore::region::LgAllocRegion;
use crate::Row;
/// Region allocation for `Row` data.
///
/// Content bytes are stored in stable contiguous memory locations,
/// and then a `Row` referencing them is falsified.
pub struct RowStack {
region: LgAllocRegion<u8>,
}
impl RowStack {
const LIMIT: usize = 2 << 20;
}
// Implement `Default` manually to specify a region allocation limit.
impl Default for RowStack {
fn default() -> Self {
Self {
// Limit the region size to 2MiB.
region: LgAllocRegion::with_limit(Self::LIMIT),
}
}
}
impl Columnation for Row {
type InnerRegion = RowStack;
}
impl Region for RowStack {
type Item = Row;
#[inline]
fn clear(&mut self) {
self.region.clear();
}
#[inline(always)]
unsafe fn copy(&mut self, item: &Row) -> Row {
if item.data.spilled() {
let bytes = self.region.copy_slice(&item.data[..]);
Row {
data: compact_bytes::CompactBytes::from_raw_parts(
bytes.as_mut_ptr(),
item.data.len(),
item.data.capacity(),
),
}
} else {
item.clone()
}
}
fn reserve_items<'a, I>(&mut self, items: I)
where
Self: 'a,
I: Iterator<Item = &'a Self::Item> + Clone,
{
let size = items
.filter(|row| row.data.spilled())
.map(|row| row.data.len())
.sum();
let size = std::cmp::min(size, Self::LIMIT);
self.region.reserve(size);
}
fn reserve_regions<'a, I>(&mut self, regions: I)
where
Self: 'a,
I: Iterator<Item = &'a Self> + Clone,
{
let size = regions.map(|r| r.region.len()).sum();
let size = std::cmp::min(size, Self::LIMIT);
self.region.reserve(size);
}
fn heap_size(&self, callback: impl FnMut(usize, usize)) {
self.region.heap_size(callback)
}
}
}
/// Packs datums into a [`Row`].
///
/// Creating a `RowPacker` via [`Row::packer`] starts a packing operation on the
/// row. A packing operation always starts from scratch: the existing contents
/// of the underlying row are cleared.
///
/// To complete a packing operation, drop the `RowPacker`.
#[derive(Debug)]
pub struct RowPacker<'a> {
row: &'a mut Row,
}
#[derive(Debug, Clone)]
pub struct DatumListIter<'a> {
data: &'a [u8],
offset: usize,
}
#[derive(Debug, Clone)]
pub struct DatumDictIter<'a> {
data: &'a [u8],
offset: usize,
prev_key: Option<&'a str>,
}
/// `RowArena` is used to hold on to temporary `Row`s for functions like `eval` that need to create complex `Datum`s but don't have a `Row` to put them in yet.
#[derive(Debug)]
pub struct RowArena {
// Semantically, this field would be better represented by a `Vec<Box<[u8]>>`,
// as once the arena takes ownership of a byte vector the vector is never
// modified. But `RowArena::push_bytes` takes ownership of a `Vec<u8>`, so
// storing that `Vec<u8>` directly avoids an allocation. The cost is
// additional memory use, as the vector may have spare capacity, but row
// arenas are short lived so this is the better tradeoff.
inner: RefCell<Vec<Vec<u8>>>,
}
// DatumList and DatumDict defined here rather than near Datum because we need private access to the unsafe data field
/// A sequence of Datums
#[derive(Clone, Copy, Eq, PartialEq, Hash)]
pub struct DatumList<'a> {
/// Points at the serialized datums
data: &'a [u8],
}
impl<'a> Debug for DatumList<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.iter()).finish()
}
}
impl Ord for DatumList<'_> {
fn cmp(&self, other: &DatumList) -> Ordering {
self.iter().cmp(other.iter())
}
}
impl PartialOrd for DatumList<'_> {
fn partial_cmp(&self, other: &DatumList) -> Option<Ordering> {
Some(self.cmp(other))
}
}
/// A mapping from string keys to Datums
#[derive(Clone, Copy, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct DatumMap<'a> {
/// Points at the serialized datums, which should be sorted in key order
data: &'a [u8],
}
/// Represents a single `Datum`, appropriate to be nested inside other
/// `Datum`s.
#[derive(Clone, Copy, Eq, PartialEq, Hash)]
pub struct DatumNested<'a> {
val: &'a [u8],
}
impl<'a> std::fmt::Display for DatumNested<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
std::fmt::Display::fmt(&self.datum(), f)
}
}
impl<'a> std::fmt::Debug for DatumNested<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("DatumNested")
.field("val", &self.datum())
.finish()
}
}
impl<'a> DatumNested<'a> {
// Figure out which bytes `read_datum` returns (e.g. including the tag),
// and then store a reference to those bytes, so we can "replay" this same
// call later on without storing the datum itself.
pub fn extract(data: &'a [u8], offset: &mut usize) -> DatumNested<'a> {
let start = *offset;
let _ = unsafe { read_datum(data, offset) };
DatumNested {
val: &data[start..*offset],
}
}
/// Returns the datum `self` contains.
pub fn datum(&self) -> Datum<'a> {
unsafe { read_datum(self.val, &mut 0) }
}
}
impl<'a> Ord for DatumNested<'a> {
fn cmp(&self, other: &Self) -> Ordering {
self.datum().cmp(&other.datum())
}
}
impl<'a> PartialOrd for DatumNested<'a> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
// Prefer adding new tags to the end of the enum. Certain behavior, like row ordering and EXPLAIN
// PHYSICAL PLAN, rely on the ordering of this enum. Neither of these are breaking changes, but
// it's annoying when they change.
#[derive(Debug, Clone, Copy, PartialEq, Eq, IntoPrimitive, TryFromPrimitive)]
#[repr(u8)]
enum Tag {
Null,
False,
True,
Int16,
Int32,
Int64,
UInt8,
UInt32,
Float32,
Float64,
Date,
Time,
Timestamp,
TimestampTz,
Interval,
BytesTiny,
BytesShort,
BytesLong,
BytesHuge,
StringTiny,
StringShort,
StringLong,
StringHuge,
Uuid,
Array,
List,
Dict,
JsonNull,
Dummy,
Numeric,
UInt16,
UInt64,
MzTimestamp,
Range,
MzAclItem,
AclItem,
// Everything except leap seconds and times beyond the range of
// i64 nanoseconds. (Note that Materialize does not support leap
// seconds, but this module does).
CheapTimestamp,
// Everything except leap seconds and times beyond the range of
// i64 nanoseconds. (Note that Materialize does not support leap
// seconds, but this module does).
CheapTimestampTz,
// The next several tags are for variable-length signed integer encoding.
// The basic idea is that `NonNegativeIntN_K` is used to encode a datum of type
// IntN whose actual value is positive or zero and fits in K bits, and similarly for
// NegativeIntN_K with negative values.
//
// The order of these tags matters, because we want to be able to choose the
// tag for a given datum quickly, with arithmetic, rather than slowly, with a
// stack of `if` statements.
//
// Separate tags for non-negative and negative numbers are used to avoid having to
// waste one bit in the actual data space to encode the sign.
NonNegativeInt16_0, // i.e., 0
NonNegativeInt16_8,
NonNegativeInt16_16,
NonNegativeInt32_0,
NonNegativeInt32_8,
NonNegativeInt32_16,
NonNegativeInt32_24,
NonNegativeInt32_32,
NonNegativeInt64_0,
NonNegativeInt64_8,
NonNegativeInt64_16,
NonNegativeInt64_24,
NonNegativeInt64_32,
NonNegativeInt64_40,
NonNegativeInt64_48,
NonNegativeInt64_56,
NonNegativeInt64_64,
NegativeInt16_0, // i.e., -1
NegativeInt16_8,
NegativeInt16_16,
NegativeInt32_0,
NegativeInt32_8,
NegativeInt32_16,
NegativeInt32_24,
NegativeInt32_32,
NegativeInt64_0,
NegativeInt64_8,
NegativeInt64_16,
NegativeInt64_24,
NegativeInt64_32,
NegativeInt64_40,
NegativeInt64_48,
NegativeInt64_56,
NegativeInt64_64,
// These are like the ones above, but for unsigned types. The
// situation is slightly simpler as we don't have negatives.
UInt8_0, // i.e., 0
UInt8_8,
UInt16_0,
UInt16_8,
UInt16_16,
UInt32_0,
UInt32_8,
UInt32_16,
UInt32_24,
UInt32_32,
UInt64_0,
UInt64_8,
UInt64_16,
UInt64_24,
UInt64_32,
UInt64_40,
UInt64_48,
UInt64_56,
UInt64_64,
}
impl Tag {
fn actual_int_length(self) -> Option<usize> {
use Tag::*;
let val = match self {
NonNegativeInt16_0 | NonNegativeInt32_0 | NonNegativeInt64_0 | UInt8_0 | UInt16_0
| UInt32_0 | UInt64_0 => 0,
NonNegativeInt16_8 | NonNegativeInt32_8 | NonNegativeInt64_8 | UInt8_8 | UInt16_8
| UInt32_8 | UInt64_8 => 1,
NonNegativeInt16_16 | NonNegativeInt32_16 | NonNegativeInt64_16 | UInt16_16
| UInt32_16 | UInt64_16 => 2,
NonNegativeInt32_24 | NonNegativeInt64_24 | UInt32_24 | UInt64_24 => 3,
NonNegativeInt32_32 | NonNegativeInt64_32 | UInt32_32 | UInt64_32 => 4,
NonNegativeInt64_40 | UInt64_40 => 5,
NonNegativeInt64_48 | UInt64_48 => 6,
NonNegativeInt64_56 | UInt64_56 => 7,
NonNegativeInt64_64 | UInt64_64 => 8,
NegativeInt16_0 | NegativeInt32_0 | NegativeInt64_0 => 0,
NegativeInt16_8 | NegativeInt32_8 | NegativeInt64_8 => 1,
NegativeInt16_16 | NegativeInt32_16 | NegativeInt64_16 => 2,
NegativeInt32_24 | NegativeInt64_24 => 3,
NegativeInt32_32 | NegativeInt64_32 => 4,
NegativeInt64_40 => 5,
NegativeInt64_48 => 6,
NegativeInt64_56 => 7,
NegativeInt64_64 => 8,
_ => return None,
};
Some(val)
}
}
// --------------------------------------------------------------------------------
// reading data
/// Read a byte slice starting at byte `offset`.
///
/// Updates `offset` to point to the first byte after the end of the read region.
fn read_untagged_bytes<'a>(data: &'a [u8], offset: &mut usize) -> &'a [u8] {
let len = u64::from_le_bytes(read_byte_array(data, offset));
let len = usize::cast_from(len);
let bytes = &data[*offset..(*offset + len)];
*offset += len;
bytes
}
/// Read a data whose length is encoded in the row before its contents.
///
/// Updates `offset` to point to the first byte after the end of the read region.
///
/// # Safety
///
/// This function is safe if the datum's length and contents were previously written by `push_lengthed_bytes`,
/// and it was only written with a `String` tag if it was indeed UTF-8.
unsafe fn read_lengthed_datum<'a>(data: &'a [u8], offset: &mut usize, tag: Tag) -> Datum<'a> {
let len = match tag {
Tag::BytesTiny | Tag::StringTiny => usize::from(read_byte(data, offset)),
Tag::BytesShort | Tag::StringShort => {
usize::from(u16::from_le_bytes(read_byte_array(data, offset)))
}
Tag::BytesLong | Tag::StringLong => {
usize::cast_from(u32::from_le_bytes(read_byte_array(data, offset)))
}
Tag::BytesHuge | Tag::StringHuge => {
usize::cast_from(u64::from_le_bytes(read_byte_array(data, offset)))
}
_ => unreachable!(),
};
let bytes = &data[*offset..(*offset + len)];
*offset += len;
match tag {
Tag::BytesTiny | Tag::BytesShort | Tag::BytesLong | Tag::BytesHuge => Datum::Bytes(bytes),
Tag::StringTiny | Tag::StringShort | Tag::StringLong | Tag::StringHuge => {
Datum::String(str::from_utf8_unchecked(bytes))
}
_ => unreachable!(),
}
}
fn read_byte(data: &[u8], offset: &mut usize) -> u8 {
let byte = data[*offset];
*offset += 1;
byte
}
/// Read `length` bytes from `data` at `offset`, updating the
/// latter. Extend the resulting buffer to an array of `N` bytes by
/// inserting `FILL` in the k most significant bytes, where k = N - length.
///
/// SAFETY:
/// * length <= N
/// * offset + length <= data.len()
unsafe fn read_byte_array_sign_extending<const N: usize, const FILL: u8>(
data: &[u8],
offset: &mut usize,
length: usize,
) -> [u8; N] {
let mut raw = [FILL; N];
for i in 0..length {
debug_assert!(i < raw.len());
debug_assert!(*offset + i < data.len());
*raw.get_unchecked_mut(i) = *data.get_unchecked(*offset + i);
}
*offset += length;
raw
}
/// Read `length` bytes from `data` at `offset`, updating the
/// latter. Extend the resulting buffer to a negative `N`-byte
/// twos complement integer by filling the remaining bits with 1.
///
/// SAFETY:
/// * length <= N
/// * offset + length <= data.len()
unsafe fn read_byte_array_extending_negative<const N: usize>(
data: &[u8],
offset: &mut usize,
length: usize,
) -> [u8; N] {
read_byte_array_sign_extending::<N, 255>(data, offset, length)
}
/// Read `length` bytes from `data` at `offset`, updating the
/// latter. Extend the resulting buffer to a positive or zero `N`-byte
/// twos complement integer by filling the remaining bits with 0.
///
/// SAFETY:
/// * length <= N
/// * offset + length <= data.len()
unsafe fn read_byte_array_extending_nonnegative<const N: usize>(
data: &[u8],
offset: &mut usize,
length: usize,
) -> [u8; N] {
read_byte_array_sign_extending::<N, 0>(data, offset, length)
}
pub(super) fn read_byte_array<const N: usize>(data: &[u8], offset: &mut usize) -> [u8; N] {
let mut raw = [0; N];
raw.copy_from_slice(&data[*offset..*offset + N]);
*offset += N;
raw
}
pub(super) fn read_date(data: &[u8], offset: &mut usize) -> Date {
let days = i32::from_le_bytes(read_byte_array(data, offset));
Date::from_pg_epoch(days).expect("unexpected date")
}
pub(super) fn read_naive_date(data: &[u8], offset: &mut usize) -> NaiveDate {
let year = i32::from_le_bytes(read_byte_array(data, offset));
let ordinal = u32::from_le_bytes(read_byte_array(data, offset));
NaiveDate::from_yo_opt(year, ordinal).unwrap()
}
pub(super) fn read_time(data: &[u8], offset: &mut usize) -> NaiveTime {
let secs = u32::from_le_bytes(read_byte_array(data, offset));
let nanos = u32::from_le_bytes(read_byte_array(data, offset));
NaiveTime::from_num_seconds_from_midnight_opt(secs, nanos).unwrap()
}
/// Read a datum starting at byte `offset`.
///
/// Updates `offset` to point to the first byte after the end of the read region.
///
/// # Safety
///
/// This function is safe if a `Datum` was previously written at this offset by `push_datum`.
/// Otherwise it could return invalid values, which is Undefined Behavior.
pub unsafe fn read_datum<'a>(data: &'a [u8], offset: &mut usize) -> Datum<'a> {
let tag = Tag::try_from_primitive(read_byte(data, offset)).expect("unknown row tag");
match tag {
Tag::Null => Datum::Null,
Tag::False => Datum::False,
Tag::True => Datum::True,
Tag::UInt8_0 | Tag::UInt8_8 => {
let i = u8::from_le_bytes(read_byte_array_extending_nonnegative(
data,
offset,
tag.actual_int_length()
.expect("returns a value for variable-length-encoded integer tags"),
));
Datum::UInt8(i)
}
Tag::Int16 => {
let i = i16::from_le_bytes(read_byte_array(data, offset));
Datum::Int16(i)
}
Tag::NonNegativeInt16_0 | Tag::NonNegativeInt16_16 | Tag::NonNegativeInt16_8 => {
// SAFETY:`tag.actual_int_length()` is <= 16 for these tags,
// and `data` is big enough because it was encoded validly. These assumptions
// are checked in debug asserts.
let i = i16::from_le_bytes(read_byte_array_extending_nonnegative(
data,
offset,
tag.actual_int_length()
.expect("returns a value for variable-length-encoded integer tags"),
));
Datum::Int16(i)
}
Tag::UInt16_0 | Tag::UInt16_8 | Tag::UInt16_16 => {
let i = u16::from_le_bytes(read_byte_array_extending_nonnegative(
data,
offset,
tag.actual_int_length()
.expect("returns a value for variable-length-encoded integer tags"),
));
Datum::UInt16(i)
}
Tag::Int32 => {
let i = i32::from_le_bytes(read_byte_array(data, offset));
Datum::Int32(i)
}
Tag::NonNegativeInt32_0
| Tag::NonNegativeInt32_32
| Tag::NonNegativeInt32_8
| Tag::NonNegativeInt32_16
| Tag::NonNegativeInt32_24 => {
// SAFETY:`tag.actual_int_length()` is <= 32 for these tags,
// and `data` is big enough because it was encoded validly. These assumptions
// are checked in debug asserts.
let i = i32::from_le_bytes(read_byte_array_extending_nonnegative(
data,
offset,
tag.actual_int_length()
.expect("returns a value for variable-length-encoded integer tags"),
));
Datum::Int32(i)
}
Tag::UInt32_0 | Tag::UInt32_8 | Tag::UInt32_16 | Tag::UInt32_24 | Tag::UInt32_32 => {
let i = u32::from_le_bytes(read_byte_array_extending_nonnegative(
data,
offset,
tag.actual_int_length()
.expect("returns a value for variable-length-encoded integer tags"),
));
Datum::UInt32(i)
}
Tag::Int64 => {
let i = i64::from_le_bytes(read_byte_array(data, offset));
Datum::Int64(i)
}
Tag::NonNegativeInt64_0
| Tag::NonNegativeInt64_64
| Tag::NonNegativeInt64_8
| Tag::NonNegativeInt64_16
| Tag::NonNegativeInt64_24
| Tag::NonNegativeInt64_32
| Tag::NonNegativeInt64_40
| Tag::NonNegativeInt64_48
| Tag::NonNegativeInt64_56 => {
// SAFETY:`tag.actual_int_length()` is <= 64 for these tags,
// and `data` is big enough because it was encoded validly. These assumptions
// are checked in debug asserts.
let i = i64::from_le_bytes(read_byte_array_extending_nonnegative(
data,
offset,
tag.actual_int_length()
.expect("returns a value for variable-length-encoded integer tags"),
));
Datum::Int64(i)
}
Tag::UInt64_0
| Tag::UInt64_8
| Tag::UInt64_16
| Tag::UInt64_24
| Tag::UInt64_32
| Tag::UInt64_40
| Tag::UInt64_48
| Tag::UInt64_56
| Tag::UInt64_64 => {
let i = u64::from_le_bytes(read_byte_array_extending_nonnegative(
data,
offset,
tag.actual_int_length()
.expect("returns a value for variable-length-encoded integer tags"),
));
Datum::UInt64(i)
}
Tag::NegativeInt16_0 | Tag::NegativeInt16_16 | Tag::NegativeInt16_8 => {
// SAFETY:`tag.actual_int_length()` is <= 16 for these tags,
// and `data` is big enough because it was encoded validly. These assumptions
// are checked in debug asserts.
let i = i16::from_le_bytes(read_byte_array_extending_negative(
data,
offset,
tag.actual_int_length()
.expect("returns a value for variable-length-encoded integer tags"),
));
Datum::Int16(i)
}
Tag::NegativeInt32_0
| Tag::NegativeInt32_32
| Tag::NegativeInt32_8
| Tag::NegativeInt32_16
| Tag::NegativeInt32_24 => {
// SAFETY:`tag.actual_int_length()` is <= 32 for these tags,
// and `data` is big enough because it was encoded validly. These assumptions
// are checked in debug asserts.
let i = i32::from_le_bytes(read_byte_array_extending_negative(
data,
offset,
tag.actual_int_length()
.expect("returns a value for variable-length-encoded integer tags"),
));
Datum::Int32(i)
}
Tag::NegativeInt64_0
| Tag::NegativeInt64_64
| Tag::NegativeInt64_8
| Tag::NegativeInt64_16
| Tag::NegativeInt64_24
| Tag::NegativeInt64_32
| Tag::NegativeInt64_40
| Tag::NegativeInt64_48
| Tag::NegativeInt64_56 => {
// SAFETY:`tag.actual_int_length()` is <= 64 for these tags,
// and `data` is big enough because the row was encoded validly. These assumptions
// are checked in debug asserts.
let i = i64::from_le_bytes(read_byte_array_extending_negative(
data,
offset,
tag.actual_int_length()
.expect("returns a value for variable-length-encoded integer tags"),
));
Datum::Int64(i)
}
Tag::UInt8 => {
let i = u8::from_le_bytes(read_byte_array(data, offset));
Datum::UInt8(i)
}
Tag::UInt16 => {
let i = u16::from_le_bytes(read_byte_array(data, offset));
Datum::UInt16(i)
}
Tag::UInt32 => {
let i = u32::from_le_bytes(read_byte_array(data, offset));
Datum::UInt32(i)
}
Tag::UInt64 => {
let i = u64::from_le_bytes(read_byte_array(data, offset));
Datum::UInt64(i)
}
Tag::Float32 => {
let f = f32::from_bits(u32::from_le_bytes(read_byte_array(data, offset)));
Datum::Float32(OrderedFloat::from(f))
}
Tag::Float64 => {
let f = f64::from_bits(u64::from_le_bytes(read_byte_array(data, offset)));
Datum::Float64(OrderedFloat::from(f))
}
Tag::Date => Datum::Date(read_date(data, offset)),
Tag::Time => Datum::Time(read_time(data, offset)),
Tag::CheapTimestamp => {
let ts = i64::from_le_bytes(read_byte_array(data, offset));
let secs = ts.div_euclid(1_000_000_000);
let nsecs: u32 = ts.rem_euclid(1_000_000_000).try_into().unwrap();
let ndt = DateTime::from_timestamp(secs, nsecs)
.expect("We only write round-trippable timestamps")
.naive_utc();
Datum::Timestamp(
CheckedTimestamp::from_timestamplike(ndt).expect("unexpected timestamp"),
)
}
Tag::CheapTimestampTz => {
let ts = i64::from_le_bytes(read_byte_array(data, offset));
let secs = ts.div_euclid(1_000_000_000);
let nsecs: u32 = ts.rem_euclid(1_000_000_000).try_into().unwrap();
let dt = DateTime::from_timestamp(secs, nsecs)
.expect("We only write round-trippable timestamps");
Datum::TimestampTz(
CheckedTimestamp::from_timestamplike(dt).expect("unexpected timestamp"),
)
}
Tag::Timestamp => {
let date = read_naive_date(data, offset);
let time = read_time(data, offset);
Datum::Timestamp(
CheckedTimestamp::from_timestamplike(date.and_time(time))
.expect("unexpected timestamp"),
)
}
Tag::TimestampTz => {
let date = read_naive_date(data, offset);
let time = read_time(data, offset);
Datum::TimestampTz(
CheckedTimestamp::from_timestamplike(DateTime::from_naive_utc_and_offset(
date.and_time(time),
Utc,
))
.expect("unexpected timestamptz"),
)
}
Tag::Interval => {
let months = i32::from_le_bytes(read_byte_array(data, offset));
let days = i32::from_le_bytes(read_byte_array(data, offset));
let micros = i64::from_le_bytes(read_byte_array(data, offset));
Datum::Interval(Interval {
months,
days,
micros,
})
}
Tag::BytesTiny
| Tag::BytesShort
| Tag::BytesLong
| Tag::BytesHuge
| Tag::StringTiny
| Tag::StringShort
| Tag::StringLong
| Tag::StringHuge => read_lengthed_datum(data, offset, tag),
Tag::Uuid => Datum::Uuid(Uuid::from_bytes(read_byte_array(data, offset))),
Tag::Array => {
// See the comment in `Row::push_array` for details on the encoding
// of arrays.
let ndims = read_byte(data, offset);
let dims_size = usize::from(ndims) * size_of::<u64>() * 2;
let dims = &data[*offset..*offset + dims_size];
*offset += dims_size;
let data = read_untagged_bytes(data, offset);
Datum::Array(Array {
dims: ArrayDimensions { data: dims },
elements: DatumList { data },
})
}
Tag::List => {
let bytes = read_untagged_bytes(data, offset);
Datum::List(DatumList { data: bytes })
}
Tag::Dict => {
let bytes = read_untagged_bytes(data, offset);
Datum::Map(DatumMap { data: bytes })
}
Tag::JsonNull => Datum::JsonNull,
Tag::Dummy => Datum::Dummy,
Tag::Numeric => {
let digits = read_byte(data, offset).into();
let exponent = i8::reinterpret_cast(read_byte(data, offset));
let bits = read_byte(data, offset);
let lsu_u16_len = Numeric::digits_to_lsu_elements_len(digits);
let lsu_u8_len = lsu_u16_len * 2;
let lsu_u8 = &data[*offset..(*offset + lsu_u8_len)];
*offset += lsu_u8_len;
// TODO: if we refactor the decimal library to accept the owned
// array as a parameter to `from_raw_parts` below, we could likely
// avoid a copy because it is exactly the value we want
let mut lsu = [0; numeric::NUMERIC_DATUM_WIDTH_USIZE];
for (i, c) in lsu_u8.chunks(2).enumerate() {
lsu[i] = u16::from_le_bytes(c.try_into().unwrap());
}
let d = Numeric::from_raw_parts(digits, exponent.into(), bits, lsu);
Datum::from(d)
}
Tag::MzTimestamp => {
let t = Timestamp::decode(read_byte_array(data, offset));
Datum::MzTimestamp(t)
}
Tag::Range => {
// See notes on `push_range_with` for details about encoding.
let flag_byte = read_byte(data, offset);
let flags = range::InternalFlags::from_bits(flag_byte)
.expect("range flags must be encoded validly");
if flags.contains(range::InternalFlags::EMPTY) {
assert!(
flags == range::InternalFlags::EMPTY,
"empty ranges contain only RANGE_EMPTY flag"
);
return Datum::Range(Range { inner: None });
}
let lower_bound = if flags.contains(range::InternalFlags::LB_INFINITE) {
None
} else {
Some(DatumNested::extract(data, offset))
};
let lower = RangeBound {
inclusive: flags.contains(range::InternalFlags::LB_INCLUSIVE),
bound: lower_bound,
};
let upper_bound = if flags.contains(range::InternalFlags::UB_INFINITE) {
None
} else {