Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 33 additions & 49 deletions src/cursor/btree.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
use std::{collections::VecDeque, mem::replace, ops::Bound, sync::Arc};

use crate::{
cache::WritableSlot, disk::Pointer, table::TableHandle, wal::TxId, Error, Result,
cache::WritableSlot, disk::Pointer, table::TableHandle, utils::InlineVec, wal::TxId,
Error, Result,
};

use crossbeam::epoch::{pin, Guard};

use super::{
BTreeNode, BTreeNodeView, CreatablePolicy, DataChunk, DataEntry, InternalNode, Key,
KeyRef, LeafNode, NodeFindResult, ReadonlyPolicy, RecordData, TreeHeader,
VersionRecord, WritablePolicy, CHUNK_SIZE, HEADER_POINTER, LARGE_VALUE,
BTreeNode, BTreeNodeView, CreatablePolicy, DataChunk, DataChunkView, DataEntry,
DataEntryView, InternalNode, Key, KeyRef, LeafNode, NodeFindResult, ReadonlyPolicy,
RecordData, RecordDataView, TreeHeader, VersionRecord, WritablePolicy, CHUNK_SIZE,
HEADER_POINTER, LARGE_VALUE,
};

pub struct BTreeIndex<Policy>(Policy);
Expand Down Expand Up @@ -56,11 +58,8 @@ impl<Policy: ReadonlyPolicy> BTreeIndex<Policy> {
let mut data = Vec::new();

for &ptr in pointers {
let chunk: DataChunk = policy
.fetch_slot(ptr, table)?
.for_read()
.as_ref()
.deserialize()?;
let slot = policy.fetch_slot(ptr, table)?.for_read();
let chunk = slot.as_ref().view::<DataChunkView>()?;
data.extend_from_slice(chunk.get_data());
}

Expand All @@ -80,22 +79,17 @@ impl<Policy: ReadonlyPolicy> BTreeIndex<Policy> {
let mut next = Some(ptr);
while let Some(ptr) = next.take() {
let new_guard = pin();
let entry: DataEntry = self
.0
.fetch_slot(ptr, table)?
.for_read()
.as_ref()
.deserialize()?;

let slot = self.0.fetch_slot(ptr, table)?.for_read();
let entry: DataEntryView = slot.as_ref().view()?;
if let Some(record) =
entry.find(|&record| self.0.is_visible(record.owner, record.version))
entry.find(|&owner, &version| self.0.is_visible(owner, version))
{
return Ok(Some(match &record.data {
RecordData::Data(data) => Some(data.to_vec()),
RecordData::Chunked(pointers) => {
RecordDataView::Data(data) => Some(data.to_vec()),
RecordDataView::Chunked(pointers) => {
Some(Self::read_chunk(&self.0, pointers, table)?)
}
RecordData::Tombstone => None,
RecordDataView::Tombstone => None,
}));
}

Expand All @@ -115,19 +109,14 @@ impl<Policy: ReadonlyPolicy> BTreeIndex<Policy> {
let mut next = Some(ptr);
while let Some(ptr) = next.take() {
let new_guard = pin();
let entry: DataEntry = self
.0
.fetch_slot(ptr, table)?
.for_read()
.as_ref()
.deserialize()?;

let slot = self.0.fetch_slot(ptr, table)?.for_read();
let entry: DataEntryView = slot.as_ref().view()?;
if let Some(record) =
entry.find(|&record| self.0.is_visible(record.owner, record.version))
entry.find(|&owner, &version| self.0.is_visible(owner, version))
{
return Ok(match &record.data {
RecordData::Chunked(_) | RecordData::Data(_) => true,
RecordData::Tombstone => false,
RecordDataView::Chunked(_) | RecordDataView::Data(_) => true,
RecordDataView::Tombstone => false,
});
};

Expand All @@ -142,7 +131,7 @@ impl<Policy: ReadonlyPolicy> BTreeIndex<Policy> {
&self,
key: KeyRef,
table: &Arc<TableHandle>,
) -> Result<(Pointer, Vec<Pointer>)> {
) -> Result<(Pointer, InlineVec<Pointer, 3>)> {
let (mut ptr, height) = {
let header = self
.0
Expand All @@ -152,7 +141,7 @@ impl<Policy: ReadonlyPolicy> BTreeIndex<Policy> {
.deserialize::<TreeHeader>()?;
(header.get_root(), header.get_height())
};
let mut stack = vec![];
let mut stack = InlineVec::with_capacity(height as usize);

while let BTreeNodeView::Internal(node) = self
.0
Expand Down Expand Up @@ -248,7 +237,7 @@ impl<Policy: WritablePolicy> BTreeIndex<Policy> {
let entry = DataEntry::init(create_record());
let entry_ptr = self.0.alloc_and_log(&entry, table)?;

let split = match node.insert_and_split(pos, key.to_vec(), entry_ptr) {
let split = match node.insert_and_split(pos, key.into(), entry_ptr) {
Some(split) => split,
None => {
return self
Expand All @@ -271,7 +260,7 @@ impl<Policy: WritablePolicy> BTreeIndex<Policy> {
&self,
mut split_key: Key,
mut split_pointer: Pointer,
mut stack: Vec<Pointer>,
mut stack: InlineVec<Pointer, 3>,
table: &Arc<TableHandle>,
) -> Result {
// CAS loop: multiple concurrent splits may race to update the root.
Expand Down Expand Up @@ -323,12 +312,11 @@ impl<Policy: WritablePolicy> BTreeIndex<Policy> {
return Ok(RecordData::Data(data));
}

let mut pointers = Vec::with_capacity(data.len().div_ceil(CHUNK_SIZE));
let mut pointers = InlineVec::with_capacity(data.len().div_ceil(CHUNK_SIZE));
while data.len() > CHUNK_SIZE {
let remain = data.split_off(CHUNK_SIZE);
let chunk = DataChunk::new(data);
let chunk = DataChunk::new(replace(&mut data, remain));
pointers.push(self.0.alloc_and_log(&chunk, table)?);
data = remain;
}
pointers.push(self.0.alloc_and_log(&DataChunk::new(data), table)?);

Expand Down Expand Up @@ -599,7 +587,7 @@ where
count += 1;

if let Some(found) = Self::__find(policy, p, table)? {
buffered.push_back((k.to_vec(), found));
buffered.push_back((k.into(), found));
}
}

Expand Down Expand Up @@ -629,25 +617,21 @@ where
let mut next = Some(ptr);

while let Some(ptr) = next.take() {
let entry: DataEntry = policy
.fetch_slot(ptr, table)?
.for_read()
.as_ref()
.deserialize()?;

let slot = policy.fetch_slot(ptr, table)?.for_read();
let entry: DataEntryView = slot.as_ref().view()?;
if let Some(record) =
entry.find(|record| policy.is_visible(record.owner, record.version))
entry.find(|&owner, &version| policy.is_visible(owner, version))
{
return Ok(Some(match &record.data {
RecordData::Data(data) => {
RecordDataView::Data(data) => {
Some((Buffered::Data(data.to_vec()), record.owner, record.version))
}
RecordData::Chunked(pointers) => Some((
RecordDataView::Chunked(pointers) => Some((
Buffered::Chunked(pointers.to_vec()),
record.owner,
record.version,
)),
RecordData::Tombstone => None,
RecordDataView::Tombstone => None,
}));
}

Expand Down Expand Up @@ -680,7 +664,7 @@ where
for (k, p) in node.get_entries_while(&self.end) {
count += 1;
if let Some(found) = self.find_value(p)? {
self.buffered.push_back((k.to_vec(), found))
self.buffered.push_back((k.into(), found))
}
}

Expand Down
25 changes: 15 additions & 10 deletions src/cursor/cursor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ impl<'a> Cursor<'a> {
self
.metrics
.operation_insert
.measure(|| self.index.insert(key, value, table))
.measure(|| self.index.insert(key.into(), value, table))
.map(|_| ())
}

Expand All @@ -100,7 +100,7 @@ impl<'a> Cursor<'a> {
.measure(|| {
self
.index
.insert_record(key.as_ref().to_vec(), RecordData::Tombstone, table)
.insert_record(key.as_ref().into(), RecordData::Tombstone, table)
})
.map(|_| ());
}
Expand Down Expand Up @@ -129,8 +129,8 @@ impl<'a> Cursor<'a> {
&self.table,
self.compaction.as_ref(),
&self.index,
range.start_bound().map(|k| k.as_ref().to_vec()),
range.end_bound().map(|k| k.as_ref().to_vec()),
range.start_bound().map(|k| k.as_ref().into()),
range.end_bound().map(|k| k.as_ref().into()),
)
}
}
Expand All @@ -140,9 +140,9 @@ pub struct CursorIterator<'a> {
table: BTreeIterator<'a, &'a TxContext<'a>>,
compaction: Option<(
BTreeIterator<'a, &'a TxContext<'a>>,
Option<(Vec<u8>, Option<Vec<u8>>)>,
Option<(Key, Option<Vec<u8>>)>,
)>,
buffered: Option<(Vec<u8>, Option<Vec<u8>>)>,
buffered: Option<(Key, Option<Vec<u8>>)>,
}
impl<'a> CursorIterator<'a> {
pub fn new(
Expand All @@ -165,14 +165,19 @@ impl<'a> CursorIterator<'a> {
buffered: None,
})
}
pub fn try_next(&mut self) -> Result<Option<(Key, Vec<u8>)>> {
pub fn try_next(&mut self) -> Result<Option<(Vec<u8>, Vec<u8>)>> {
if !self.context.is_available() {
return Err(Error::TransactionClosed);
}

let (compaction, c_buffered) = match self.compaction.as_mut() {
Some(v) => v,
None => return self.table.next_kv_skip_tombstone(),
None => {
return self
.table
.next_kv_skip_tombstone()
.map(|r| r.map(|(k, v)| (k.into(), v)));
}
};

loop {
Expand All @@ -188,7 +193,7 @@ impl<'a> CursorIterator<'a> {
let (k_old, v_old, k_new, v_new) = match (kv_old, kv_new) {
(None, None) => return Ok(None),
(None, Some((k, Some(v)))) | (Some((k, Some(v))), None) => {
return Ok(Some((k, v)))
return Ok(Some((k.into(), v)))
}
(None, Some((_, None))) | (Some((_, None)), None) => continue,
(Some((k1, v1)), Some((k2, v2))) => (k1, v1, k2, v2),
Expand All @@ -206,7 +211,7 @@ impl<'a> CursorIterator<'a> {
Ordering::Equal => (k_new, v_new),
};
if let Some(v) = v {
return Ok(Some((k, v)));
return Ok(Some((k.into(), v)));
}
}
}
Expand Down
39 changes: 6 additions & 33 deletions src/cursor/entry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use crate::{
serialize::{
Deserializable, Serializable, SerializeType, TypedObject, SERIALIZABLE_BYTES,
},
utils::InlineVec,
wal::{TxId, TX_ID_BYTES},
Error,
};
Expand All @@ -27,7 +28,7 @@ pub const CHUNK_SIZE: usize = SERIALIZABLE_BYTES - 2;
#[derive(Debug)]
pub enum RecordData {
Data(Vec<u8>),
Chunked(Vec<Pointer>),
Chunked(InlineVec<Pointer, 3>),
Tombstone,
}
impl RecordData {
Expand Down Expand Up @@ -106,13 +107,6 @@ impl DataEntry {
self.versions.iter()
}

pub fn find<P>(&self, predicate: P) -> Option<&VersionRecord>
where
P: FnMut(&&VersionRecord) -> bool,
{
self.versions.iter().find(predicate)
}

pub fn get_last_owner(&self) -> Option<TxId> {
self.versions.front().map(|v| v.owner)
}
Expand All @@ -133,24 +127,9 @@ impl DataEntry {
POINTER_BYTES + 2 + self.versions.iter().map(|v| v.byte_len()).sum::<usize>();
record.byte_len() + byte_len <= SERIALIZABLE_BYTES
}

pub fn is_empty(&self) -> bool {
if self.versions.is_empty() {
return true;
}
if self.versions.len() > 1 {
return false;
}
if let RecordData::Tombstone = self.versions[0].data {
return true;
}
false
}
}
impl TypedObject for DataEntry {
fn get_type() -> SerializeType {
SerializeType::DataEntry
}
const TYPE: SerializeType = SerializeType::DataEntry;
}
impl Serializable for DataEntry {
fn write_at(&self, writer: &mut crate::disk::PageWriter) -> crate::Result {
Expand Down Expand Up @@ -183,7 +162,7 @@ impl Deserializable for DataEntry {
fn read_from(reader: &mut crate::disk::PageScanner) -> crate::Result<Self> {
let next = reader.read_u64()?;
let len = reader.read_u16()? as usize;
let mut versions = VecDeque::with_capacity(len);
let mut versions = VecDeque::with_capacity(len + 1);
for _ in 0..len {
let version = reader.read_u64()?;
let owner = reader.read_u64()?;
Expand All @@ -195,7 +174,7 @@ impl Deserializable for DataEntry {
1 => RecordData::Tombstone,
2 => {
let l = reader.read()? as usize;
let mut pointers = Vec::with_capacity(l);
let mut pointers = InlineVec::with_capacity(l);
for _ in 0..l {
pointers.push(reader.read_u64()?);
}
Expand All @@ -219,15 +198,9 @@ impl DataChunk {
pub const fn new(chunk: Vec<u8>) -> Self {
Self { chunk }
}

pub fn get_data(&self) -> &[u8] {
&self.chunk
}
}
impl TypedObject for DataChunk {
fn get_type() -> SerializeType {
SerializeType::DataChunk
}
const TYPE: SerializeType = SerializeType::DataChunk;
}
impl Serializable for DataChunk {
fn write_at(&self, writer: &mut crate::disk::PageWriter) -> crate::Result {
Expand Down
Loading
Loading