-
Notifications
You must be signed in to change notification settings - Fork 61
/
table.rs
1775 lines (1572 loc) · 47.2 KB
/
table.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 2021-2022 Parity Technologies (UK) Ltd.
// This file is dual-licensed as Apache-2.0 or MIT.
// On disk data layout for value tables.
// All numerical values are little endian.
//
// Entry 0 (metadata)
// [LAST_REMOVED: 8][FILLED: 8]
// LAST_REMOVED - 64-bit index of removed entries linked list head
// FILLED - highest index filled with live data
//
// Complete entry:
// [SIZE: 2][REFS: 4][KEY: 26][VALUE]
// SIZE: 15-bit value size. Sizes up to 0x7ffc are allowed.
// This includes size of REFS and KEY.
// The highest bit is reserved to indicate if compression is applied.
// REF: 32-bit reference counter (optional).
// KEY: lower 26 bytes of the key (optional for btree nodes).
// VALUE: payload bytes.
//
// Partial entry (first part):
// [MULTIHEAD: 2][NEXT: 8][REFS: 4][KEY: 26][VALUE]
// MULTIHEAD - Split entry head marker. 0xfffd.
// NEXT - 64-bit index of the entry that holds the next part.
// take all available space in this entry.
// REF: 32-bit reference counter (optional).
// KEY: lower 26 bytes of the key (optional for btree nodes).
// VALUE: The rest of the entry is filled with payload bytes.
//
// Partial entry (continuation):
// [MULTIPART: 2][NEXT: 8][VALUE]
// MULTIPART - Split entry marker. 0xfffe.
// NEXT - 64-bit index of the entry that holds the next part.
// VALUE: The rest of the entry is filled with payload bytes.
//
// Partial entry (last part):
// [SIZE: 2][VALUE: SIZE]
// SIZE: 15-bit size of the remaining payload.
// The highest bit is reserved to indicate if compression is applied.
// VALUE: SIZE payload bytes.
//
// Deleted entry
// [TOMBSTONE: 2][NEXT: 8]
// TOMBSTONE - Deleted entry marker. 0xffff
// NEXT - 64-bit index of the next deleted entry.
use crate::{
column::ColId,
display::hex,
error::Result,
log::{LogOverlays, LogQuery, LogReader, LogWriter},
options::ColumnOptions as Options,
parking_lot::RwLock,
table::key::{TableKey, TableKeyQuery, PARTIAL_SIZE},
};
use std::{
convert::TryInto,
mem::MaybeUninit,
sync::{
atomic::{AtomicBool, AtomicU64, Ordering},
Arc,
},
};
pub const SIZE_TIERS: usize = 1usize << SIZE_TIERS_BITS;
pub const SIZE_TIERS_BITS: u8 = 8;
pub const COMPRESSED_MASK: u16 = 0x80_00;
pub const MAX_ENTRY_SIZE: usize = 0x7ff8; // Actual max size in V4 was 0x7dfe
pub const MIN_ENTRY_SIZE: usize = 32;
const REFS_SIZE: usize = 4;
const SIZE_SIZE: usize = 2;
const INDEX_SIZE: usize = 8;
const MAX_ENTRY_BUF_SIZE: usize = 0x8000;
const TOMBSTONE: &[u8] = &[0xff, 0xff];
const MULTIPART_V4: &[u8] = &[0xff, 0xfe];
const MULTIHEAD_V4: &[u8] = &[0xff, 0xfd];
const MULTIPART: &[u8] = &[0xfe, 0xff];
const MULTIHEAD: &[u8] = &[0xfd, 0xff];
const MULTIHEAD_COMPRESSED: &[u8] = &[0xfd, 0x7f];
// When a rc reach locked ref, it is locked in db.
const LOCKED_REF: u32 = u32::MAX;
const MULTIPART_ENTRY_SIZE: u16 = 4096;
pub type Value = Vec<u8>;
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub struct TableId(u16);
impl TableId {
pub fn new(col: ColId, size_tier: u8) -> TableId {
TableId(((col as u16) << 8) | size_tier as u16)
}
pub fn from_u16(id: u16) -> TableId {
TableId(id)
}
pub fn col(&self) -> ColId {
(self.0 >> 8) as ColId
}
pub fn size_tier(&self) -> u8 {
(self.0 & 0xff) as u8
}
pub fn file_name(&self) -> String {
format!("table_{:02}_{}", self.col(), hex(&[self.size_tier()]))
}
pub fn is_file_name(col: ColId, name: &str) -> bool {
name.starts_with(&format!("table_{col:02}_"))
}
pub fn as_u16(&self) -> u16 {
self.0
}
pub fn log_index(&self) -> usize {
self.col() as usize * SIZE_TIERS + self.size_tier() as usize
}
pub const fn max_log_tables(num_columns: usize) -> usize {
SIZE_TIERS * num_columns
}
pub fn from_log_index(i: usize) -> Self {
let col = i / SIZE_TIERS;
let tier = i % SIZE_TIERS;
Self::new(col as ColId, tier as u8)
}
}
impl std::fmt::Display for TableId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "t{:02}-{:02}", self.col(), hex(&[self.size_tier()]))
}
}
#[derive(Debug)]
struct FreeEntries {
stack: Vec<u64>,
}
#[derive(Debug)]
pub struct ValueTable {
pub id: TableId,
pub entry_size: u16,
file: crate::file::TableFile,
filled: AtomicU64, // Number of entries from the POV of the log overlay.
written: AtomicU64, // Actual number of entries on disk.
last_removed: AtomicU64,
dirty_header: AtomicBool,
needs_free_entries: bool,
free_entries: Option<RwLock<FreeEntries>>,
multipart: bool,
ref_counted: bool,
db_version: u32,
}
#[derive(Default, Clone, Copy)]
struct Header([u8; 16]);
impl Header {
fn last_removed(&self) -> u64 {
u64::from_le_bytes(self.0[0..INDEX_SIZE].try_into().unwrap())
}
fn set_last_removed(&mut self, last_removed: u64) {
self.0[0..INDEX_SIZE].copy_from_slice(&last_removed.to_le_bytes());
}
fn filled(&self) -> u64 {
u64::from_le_bytes(self.0[INDEX_SIZE..INDEX_SIZE * 2].try_into().unwrap())
}
fn set_filled(&mut self, filled: u64) {
self.0[INDEX_SIZE..INDEX_SIZE * 2].copy_from_slice(&filled.to_le_bytes());
}
}
pub struct Entry<B: AsRef<[u8]>>(usize, B);
#[cfg(feature = "loom")]
pub type FullEntry = Entry<Vec<u8>>;
#[cfg(not(feature = "loom"))]
pub type FullEntry = Entry<[u8; MAX_ENTRY_BUF_SIZE]>;
pub type EntryRef<'a> = Entry<&'a [u8]>;
type PartialEntry = Entry<[u8; 10]>;
type PartialKeyEntry = Entry<[u8; 40]>; // 2 + 4 + 26 + 8
impl<const C: usize> Entry<[u8; C]> {
#[inline(always)]
#[allow(clippy::uninit_assumed_init)]
pub fn new_uninit() -> Self {
Entry(0, unsafe { MaybeUninit::uninit().assume_init() })
}
}
#[cfg(feature = "loom")]
impl Entry<Vec<u8>> {
pub fn new_uninit_full_entry() -> Self {
Entry(0, vec![0; MAX_ENTRY_BUF_SIZE])
}
}
#[cfg(not(feature = "loom"))]
impl Entry<[u8; MAX_ENTRY_BUF_SIZE]> {
pub fn new_uninit_full_entry() -> Self {
Self::new_uninit()
}
}
impl<B: AsRef<[u8]>> Entry<B> {
#[inline(always)]
pub fn check_remaining_len(
&self,
len: usize,
error: impl Fn() -> crate::error::Error,
) -> Result<()> {
if self.0 + len > self.1.as_ref().len() {
return Err(error())
}
Ok(())
}
#[inline(always)]
pub fn new(data: B) -> Self {
Entry(0, data)
}
pub fn set_offset(&mut self, offset: usize) {
self.0 = offset;
}
pub fn offset(&self) -> usize {
self.0
}
pub fn read_slice(&mut self, size: usize) -> &[u8] {
let start = self.0;
self.0 += size;
&self.1.as_ref()[start..self.0]
}
fn is_tombstone(&self) -> bool {
&self.1.as_ref()[0..SIZE_SIZE] == TOMBSTONE
}
fn is_multipart(&self) -> bool {
&self.1.as_ref()[0..SIZE_SIZE] == MULTIPART
}
fn is_multipart_v4(&self) -> bool {
&self.1.as_ref()[0..SIZE_SIZE] == MULTIPART_V4
}
fn is_multihead_compressed(&self) -> bool {
&self.1.as_ref()[0..SIZE_SIZE] == MULTIHEAD_COMPRESSED
}
fn is_multihead(&self) -> bool {
self.is_multihead_compressed() || &self.1.as_ref()[0..SIZE_SIZE] == MULTIHEAD
}
fn is_multihead_v4(&self) -> bool {
&self.1.as_ref()[0..SIZE_SIZE] == MULTIHEAD_V4
}
fn is_multi(&self, db_version: u32) -> bool {
self.is_multipart() ||
self.is_multihead() ||
(db_version <= 4 && (self.is_multipart_v4() || self.is_multihead_v4()))
}
fn read_size(&mut self) -> (u16, bool) {
let size = u16::from_le_bytes(self.read_slice(SIZE_SIZE).try_into().unwrap());
let compressed = (size & COMPRESSED_MASK) > 0;
(size & !COMPRESSED_MASK, compressed)
}
fn skip_size(&mut self) {
self.0 += SIZE_SIZE;
}
pub fn read_u64(&mut self) -> u64 {
u64::from_le_bytes(self.read_slice(8).try_into().unwrap())
}
fn read_next(&mut self) -> u64 {
self.read_u64()
}
pub fn skip_u64(&mut self) {
self.0 += 8;
}
pub fn skip_next(&mut self) {
self.skip_u64()
}
pub fn read_u32(&mut self) -> u32 {
u32::from_le_bytes(self.read_slice(REFS_SIZE).try_into().unwrap())
}
fn read_rc(&mut self) -> u32 {
self.read_u32()
}
fn read_partial(&mut self) -> &[u8] {
self.read_slice(PARTIAL_SIZE)
}
fn remaining_to(&self, end: usize) -> &[u8] {
&self.1.as_ref()[self.0..end]
}
}
impl<B: AsRef<[u8]> + AsMut<[u8]>> Entry<B> {
pub fn write_slice(&mut self, buf: &[u8]) {
let start = self.0;
self.0 += buf.len();
self.1.as_mut()[start..self.0].copy_from_slice(buf);
}
fn write_tombstone(&mut self) {
self.write_slice(TOMBSTONE);
}
fn write_multipart(&mut self) {
self.write_slice(MULTIPART);
}
fn write_multihead(&mut self) {
self.write_slice(MULTIHEAD);
}
fn write_multihead_compressed(&mut self) {
self.write_slice(MULTIHEAD_COMPRESSED);
}
fn write_size(&mut self, mut size: u16, compressed: bool) {
if compressed {
size |= COMPRESSED_MASK;
}
self.write_slice(&size.to_le_bytes());
}
pub fn write_u64(&mut self, next_index: u64) {
self.write_slice(&next_index.to_le_bytes());
}
fn write_next(&mut self, next_index: u64) {
self.write_u64(next_index)
}
pub fn write_u32(&mut self, next_index: u32) {
self.write_slice(&next_index.to_le_bytes());
}
fn write_rc(&mut self, rc: u32) {
self.write_slice(&rc.to_le_bytes());
}
pub fn inner_mut(&mut self) -> &mut B {
&mut self.1
}
}
impl<B: AsRef<[u8]> + AsMut<[u8]>> AsMut<[u8]> for Entry<B> {
fn as_mut(&mut self) -> &mut [u8] {
self.1.as_mut()
}
}
impl<B: AsRef<[u8]>> AsRef<[u8]> for Entry<B> {
fn as_ref(&self) -> &[u8] {
self.1.as_ref()
}
}
impl<B: AsRef<[u8]> + AsMut<[u8]>> std::ops::Index<std::ops::Range<usize>> for Entry<B> {
type Output = [u8];
fn index(&self, index: std::ops::Range<usize>) -> &[u8] {
&self.1.as_ref()[index]
}
}
impl<B: AsRef<[u8]> + AsMut<[u8]>> std::ops::IndexMut<std::ops::Range<usize>> for Entry<B> {
fn index_mut(&mut self, index: std::ops::Range<usize>) -> &mut [u8] {
&mut self.1.as_mut()[index]
}
}
enum LockedSlice<O: std::ops::Deref<Target = [u8]>, F: std::ops::Deref<Target = [u8]>> {
FromOverlay(O),
FromFile(F),
}
impl<O: std::ops::Deref<Target = [u8]>, F: std::ops::Deref<Target = [u8]>> LockedSlice<O, F> {
fn as_slice(&self) -> &[u8] {
match self {
LockedSlice::FromOverlay(slice) => &*slice,
LockedSlice::FromFile(slice) => &*slice,
}
}
}
impl ValueTable {
pub fn open(
path: Arc<std::path::PathBuf>,
id: TableId,
entry_size: Option<u16>,
options: &Options,
db_version: u32,
) -> Result<ValueTable> {
let (multipart, entry_size) = match entry_size {
Some(s) => (false, s),
None => (true, MULTIPART_ENTRY_SIZE),
};
assert!(entry_size >= MIN_ENTRY_SIZE as u16);
assert!(entry_size <= MAX_ENTRY_SIZE as u16);
let mut filepath: std::path::PathBuf = std::path::PathBuf::clone(&*path);
filepath.push(id.file_name());
let file = crate::file::TableFile::open(filepath, entry_size, id)?;
let mut filled = 1;
let mut last_removed = 0;
if file.map.read().is_some() {
let mut header = Header::default();
file.read_at(&mut header.0, 0)?;
last_removed = header.last_removed();
filled = header.filled();
if filled == 0 {
filled = 1;
}
if last_removed >= filled {
return Err(crate::error::Error::Corruption(format!(
"Bad removed ref {} out of {}",
last_removed, filled
)))
}
log::debug!(target: "parity-db", "Opened value table {} with {} entries, entry_size={}, removed={}", id, filled, entry_size, last_removed);
}
Ok(ValueTable {
id,
entry_size,
file,
filled: AtomicU64::new(filled),
written: AtomicU64::new(filled),
last_removed: AtomicU64::new(last_removed),
dirty_header: AtomicBool::new(false),
needs_free_entries: options.multitree,
free_entries: None,
multipart,
ref_counted: options.ref_counted,
db_version,
})
}
pub fn init_table_data(&mut self) -> Result<()> {
let free_entries = if self.needs_free_entries {
let mut stack: Vec<u64> = Default::default();
let filled = self.filled.load(Ordering::Relaxed);
let last_removed = self.last_removed.load(Ordering::Relaxed);
let mut next = last_removed;
while next != 0 {
if next >= filled {
return Err(crate::error::Error::Corruption(format!(
"Bad removed ref {} out of {}",
next, filled
)))
}
stack.insert(0, next);
let mut buf = PartialEntry::new_uninit();
self.file.read_at(buf.as_mut(), next * self.entry_size as u64)?;
buf.skip_size();
next = buf.read_next();
}
Some(RwLock::new(FreeEntries { stack }))
} else {
None
};
self.free_entries = free_entries;
Ok(())
}
pub fn value_size(&self, key: &TableKey) -> Option<u16> {
let base = self.entry_size - SIZE_SIZE as u16 - self.ref_size() as u16;
let k_encoded = key.encoded_size() as u16;
if base < k_encoded {
None
} else {
Some(base - k_encoded)
}
}
// Return ref counter, partial key and if the value is compressed.
#[inline(always)]
fn for_parts(
&self,
key: &mut TableKeyQuery,
mut index: u64,
log: &impl LogQuery,
mut f: impl FnMut(&[u8]) -> bool,
) -> Result<(u32, bool)> {
let mut part = 0;
let mut compressed = false;
let mut rc = 1;
let entry_size = self.entry_size as usize;
loop {
let vbuf = log.value_ref(self.id, index);
let buf: LockedSlice<_, _> = if let Some(buf) = vbuf.as_deref() {
log::trace!(
target: "parity-db",
"{}: Found in overlay {}",
self.id,
index,
);
LockedSlice::FromOverlay(buf)
} else {
log::trace!(
target: "parity-db",
"{}: Query slot {}",
self.id,
index,
);
let vbuf = self.file.slice_at(index * self.entry_size as u64, entry_size);
LockedSlice::FromFile(vbuf)
};
let mut buf = EntryRef::new(buf.as_slice());
if buf.is_tombstone() {
return Ok((0, false))
}
if self.multipart && part == 0 && !buf.is_multihead() {
// This may only happen during value iteration.
return Ok((0, false))
}
let (entry_end, next) = if self.multipart && buf.is_multi(self.db_version) {
if part == 0 && self.db_version > 6 && buf.is_multihead_compressed() {
compressed = true;
}
buf.skip_size();
let next = buf.read_next();
(entry_size, next)
} else {
let (size, read_compressed) = buf.read_size();
if part == 0 || self.db_version <= 6 {
compressed = read_compressed;
}
(buf.offset() + size as usize, 0)
};
if part == 0 {
if self.ref_counted {
rc = buf.read_rc();
}
match key {
TableKeyQuery::Fetch(Some(to_fetch)) => {
**to_fetch = TableKey::fetch_partial(&mut buf)?;
},
TableKeyQuery::Fetch(None) => (),
TableKeyQuery::Check(k) => {
let to_fetch = k.fetch(&mut buf)?;
if !k.compare(&to_fetch) {
log::debug!(
target: "parity-db",
"{}: Key mismatch at {}. Expected {}, got {:?}, size = {}",
self.id,
index,
k,
to_fetch.as_ref().map(hex),
self.entry_size,
);
return Ok((0, false))
}
},
}
}
if buf.offset() > entry_end {
return Err(crate::error::Error::Corruption(format!(
"Unexpected entry size. Expected at least {} bytes",
buf.offset() - 2
)))
}
if !f(buf.remaining_to(entry_end)) {
break
};
if next == 0 {
break
}
part += 1;
index = next;
}
Ok((rc, compressed))
}
pub fn get(
&self,
key: &TableKey,
index: u64,
log: &impl LogQuery,
) -> Result<Option<(Value, bool)>> {
if let Some((value, compressed, _)) =
self.query(&mut TableKeyQuery::Check(key), index, log)?
{
Ok(Some((value, compressed)))
} else {
Ok(None)
}
}
pub fn dump_entry(&self, index: u64) -> Result<Vec<u8>> {
let entry_size = self.entry_size as usize;
let mut buf = FullEntry::new_uninit_full_entry();
self.file.read_at(&mut buf[0..entry_size], index * self.entry_size as u64)?;
Ok(buf[0..entry_size].to_vec())
}
pub fn query(
&self,
key: &mut TableKeyQuery,
index: u64,
log: &impl LogQuery,
) -> Result<Option<(Value, bool, u32)>> {
let mut result = Vec::new();
let (rc, compressed) = self.for_parts(key, index, log, |buf| {
result.extend_from_slice(buf);
true
})?;
if rc > 0 {
return Ok(Some((result, compressed, rc)))
}
Ok(None)
}
#[allow(clippy::type_complexity)]
pub fn get_with_meta(
&self,
index: u64,
log: &impl LogQuery,
) -> Result<Option<(Value, u32, [u8; PARTIAL_SIZE], bool)>> {
let mut query_key = Default::default();
if let Some((value, compressed, rc)) =
self.query(&mut TableKeyQuery::Fetch(Some(&mut query_key)), index, log)?
{
return Ok(Some((value, rc, query_key, compressed)))
}
Ok(None)
}
pub fn size(
&self,
key: &TableKey,
index: u64,
log: &impl LogQuery,
) -> Result<Option<(u32, bool)>> {
let mut result = 0;
let (rc, compressed) =
self.for_parts(&mut TableKeyQuery::Check(key), index, log, |buf| {
result += buf.len() as u32;
true
})?;
if rc > 0 {
return Ok(Some((result, compressed)))
}
Ok(None)
}
pub fn has_key_at(&self, index: u64, key: &TableKey, log: &LogWriter) -> Result<bool> {
match key {
TableKey::Partial(k) => Ok(match self.partial_key_at(index, log)? {
Some(existing_key) => &existing_key[..] == key::partial_key(k),
None => false,
}),
TableKey::NoHash => Ok(!self.is_tombstone(index, log)?),
}
}
pub fn partial_key_at(
&self,
index: u64,
log: &impl LogQuery,
) -> Result<Option<[u8; PARTIAL_SIZE]>> {
let mut query_key = Default::default();
let (rc, _compressed) =
self.for_parts(&mut TableKeyQuery::Fetch(Some(&mut query_key)), index, log, |_buf| {
false
})?;
Ok(if rc == 0 { None } else { Some(query_key) })
}
pub fn is_tombstone(&self, index: u64, log: &impl LogQuery) -> Result<bool> {
let mut buf = PartialKeyEntry::new_uninit();
let buf = if log.value(self.id, index, buf.as_mut()) {
&mut buf
} else {
self.file.read_at(buf.as_mut(), index * self.entry_size as u64)?;
&mut buf
};
Ok(buf.is_tombstone())
}
pub fn read_next_free(&self, index: u64, log: &LogWriter) -> Result<u64> {
let mut buf = PartialEntry::new_uninit();
let filled = self.filled.load(Ordering::Relaxed);
if !log.value(self.id, index, buf.as_mut()) {
self.file.read_at(buf.as_mut(), index * self.entry_size as u64)?;
}
buf.skip_size();
let next = buf.read_next();
if next >= filled {
return Err(crate::error::Error::Corruption(format!(
"Bad removed ref {} out of {}",
next, filled
)))
}
Ok(next)
}
pub fn read_next_part(&self, index: u64, log: &LogWriter) -> Result<Option<u64>> {
let mut buf = PartialEntry::new_uninit();
if !log.value(self.id, index, buf.as_mut()) {
self.file.read_at(buf.as_mut(), index * self.entry_size as u64)?;
}
if self.multipart && buf.is_multi(self.db_version) {
buf.skip_size();
let next = buf.read_next();
return Ok(Some(next))
}
Ok(None)
}
pub fn next_free(&self, log: &mut LogWriter) -> Result<u64> {
let free_entries_guard = if let Some(free_entries) = &self.free_entries {
Some(free_entries.write())
} else {
None
};
let filled = self.filled.load(Ordering::Relaxed);
let last_removed = self.last_removed.load(Ordering::Relaxed);
let index = if last_removed != 0 {
let next_removed = self.read_next_free(last_removed, log)?;
log::trace!(
target: "parity-db",
"{}: Inserting into removed slot {}",
self.id,
last_removed,
);
self.last_removed.store(next_removed, Ordering::Relaxed);
if let Some(mut free_entries) = free_entries_guard {
let last = free_entries.stack.pop().unwrap();
debug_assert_eq!(last, last_removed);
}
last_removed
} else {
log::trace!(
target: "parity-db",
"{}: Inserting into new slot {}",
self.id,
filled,
);
self.filled.store(filled + 1, Ordering::Relaxed);
filled
};
self.dirty_header.store(true, Ordering::Relaxed);
Ok(index)
}
pub fn claim_entries(&self, num: usize) -> Result<Vec<u64>> {
match &self.free_entries {
Some(free_entries) => {
let mut free_entries = free_entries.write();
let mut entries: Vec<u64> = Default::default();
for _i in 0..num {
let filled = self.filled.load(Ordering::Relaxed);
let last_removed = self.last_removed.load(Ordering::Relaxed);
let index = if last_removed != 0 {
let last = free_entries.stack.pop().unwrap();
debug_assert_eq!(last, last_removed);
let next_removed = *free_entries.stack.last().unwrap_or(&0u64);
self.last_removed.store(next_removed, Ordering::Relaxed);
last_removed
} else {
self.filled.store(filled + 1, Ordering::Relaxed);
filled
};
entries.push(index);
}
self.dirty_header.store(true, Ordering::Relaxed);
Ok(entries)
},
None =>
return Err(crate::error::Error::InvalidConfiguration(format!(
"claim_entries called without free_entries"
))),
}
}
fn overwrite_chain(
&self,
key: &TableKey,
value: &[u8],
log: &mut LogWriter,
at: Option<u64>,
claimed: bool,
compressed: bool,
) -> Result<u64> {
let mut remainder = value.len() + self.ref_size() + key.encoded_size();
let mut offset = 0;
let mut start = 0;
assert!(self.multipart || value.len() <= self.value_size(key).unwrap() as usize);
let (mut index, mut follow) = match at {
Some(index) => (index, !claimed),
None => (self.next_free(log)?, false),
};
loop {
let mut next_index = 0;
if follow {
// check existing link
match self.read_next_part(index, log)? {
Some(next) => {
next_index = next;
},
None => {
follow = false;
},
}
}
log::trace!(
target: "parity-db",
"{}: Writing slot {}: {}",
self.id,
index,
key,
);
let mut buf = FullEntry::new_uninit_full_entry();
let free_space = self.entry_size as usize - SIZE_SIZE;
let value_len = if remainder > free_space {
if !follow {
next_index = self.next_free(log)?
}
if start == 0 {
if compressed {
buf.write_multihead_compressed();
} else {
buf.write_multihead();
}
} else {
buf.write_multipart();
}
buf.write_next(next_index);
free_space - INDEX_SIZE
} else {
buf.write_size(remainder as u16, compressed);
remainder
};
let init_offset = buf.offset();
if offset == 0 {
if self.ref_counted {
// First reference.
buf.write_rc(1u32);
}
key.write(&mut buf);
}
let written = buf.offset() - init_offset;
buf.write_slice(&value[offset..offset + value_len - written]);
offset += value_len - written;
log.insert_value(self.id, index, buf[0..buf.offset()].to_vec());
remainder -= value_len;
if start == 0 {
start = index;
}
index = next_index;
if remainder == 0 {
if index != 0 {
// End of new entry. Clear the remaining tail and exit
self.clear_chain(index, log)?;
}
break
}
}
Ok(start)
}
fn clear_chain(&self, mut index: u64, log: &mut LogWriter) -> Result<()> {
loop {
match self.read_next_part(index, log)? {
Some(next) => {
self.clear_slot(index, log)?;
index = next;
},
None => {
self.clear_slot(index, log)?;
return Ok(())
},
}
}
}
fn clear_slot(&self, index: u64, log: &mut LogWriter) -> Result<()> {
let free_entries_guard = if let Some(free_entries) = &self.free_entries {
Some(free_entries.write())
} else {
None
};
let last_removed = self.last_removed.load(Ordering::Relaxed);
log::trace!(
target: "parity-db",
"{}: Freeing slot {}",
self.id,
index,
);
let mut buf = PartialEntry::new_uninit();
buf.write_tombstone();
buf.write_next(last_removed);
log.insert_value(self.id, index, buf[0..buf.offset()].to_vec());
self.last_removed.store(index, Ordering::Relaxed);
self.dirty_header.store(true, Ordering::Relaxed);
if let Some(mut free_entries) = free_entries_guard {
free_entries.stack.push(index);
}
Ok(())
}
pub fn write_insert_plan(
&self,
key: &TableKey,
value: &[u8],
log: &mut LogWriter,
compressed: bool,
) -> Result<u64> {
self.overwrite_chain(key, value, log, None, false, compressed)
}
pub fn write_replace_plan(
&self,
index: u64,
key: &TableKey,
value: &[u8],
log: &mut LogWriter,
compressed: bool,
) -> Result<()> {
self.overwrite_chain(key, value, log, Some(index), false, compressed)?;
Ok(())
}
pub fn write_claimed_plan(
&self,
index: u64,
key: &TableKey,
value: &[u8],
log: &mut LogWriter,
compressed: bool,
) -> Result<()> {
self.overwrite_chain(key, value, log, Some(index), true, compressed)?;
Ok(())
}
pub fn write_remove_plan(&self, index: u64, log: &mut LogWriter) -> Result<()> {
if self.multipart {
self.clear_chain(index, log)?;
} else {
self.clear_slot(index, log)?;
}
Ok(())
}
pub fn write_inc_ref(&self, index: u64, log: &mut LogWriter) -> Result<()> {
self.change_ref(index, 1, log)?;
Ok(())
}
pub fn write_dec_ref(&self, index: u64, log: &mut LogWriter) -> Result<bool> {
if self.change_ref(index, -1, log)? {
return Ok(true)
}
self.write_remove_plan(index, log)?;
Ok(false)