Skip to main content

artmap/versioned/
entry.rs

1// Copyright (c) 2026 SurrealDB Ltd
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! # Versioned entry handles (ยง11.6)
16
17#![deny(unsafe_op_in_unsafe_fn, clippy::undocumented_unsafe_blocks)]
18
19use std::ops::Deref;
20use std::ptr::NonNull;
21
22use crate::guard::GuardHandle;
23use crate::versioned::node::{VersionNode, VersionedLeaf};
24use crate::versioned::tree::{find_le, VersionedTree};
25
26/// A snapshot of one version of one key of a
27/// [`VersionedArtMap`](crate::VersionedArtMap).
28///
29/// The handle captures a single version node when it is created, so
30/// [`value`](Self::value) and [`version`](Self::version) always belong
31/// together, whatever writers do meanwhile. Fresh reads are explicit:
32/// [`latest`](Self::latest) and [`get_version_le`](Self::get_version_le) walk
33/// the current chain.
34///
35/// Bounded by the map borrow and an epoch guard; neither `Send` nor `Sync`.
36pub struct VersionedEntryRef<'a, K, V> {
37    pub(crate) leaf: NonNull<VersionedLeaf<K, V>>,
38    /// Never a tombstone.
39    pub(crate) node: NonNull<VersionNode<V>>,
40    pub(crate) tree: &'a VersionedTree<K, V>,
41    pub(crate) guard: GuardHandle<'a>,
42}
43
44impl<'a, K, V> VersionedEntryRef<'a, K, V> {
45    /// A handle on `node`, or `None` if it is a tombstone.
46    #[inline]
47    pub(crate) fn new(
48        leaf: NonNull<VersionedLeaf<K, V>>,
49        node: &VersionNode<V>,
50        tree: &'a VersionedTree<K, V>,
51        guard: GuardHandle<'a>,
52    ) -> Option<Self> {
53        if node.is_tombstone() {
54            return None;
55        }
56        Some(Self {
57            leaf,
58            node: NonNull::from(node),
59            tree,
60            guard,
61        })
62    }
63
64    #[inline]
65    fn leaf(&self) -> &VersionedLeaf<K, V> {
66        // SAFETY: Inv 2: the guard and the map borrow keep the leaf alive.
67        unsafe { self.leaf.as_ref() }
68    }
69
70    #[inline]
71    fn node(&self) -> &VersionNode<V> {
72        // SAFETY: Inv 1 and 2: the captured node is immutable and protected by
73        // the guard (heap nodes) or by the leaf (inline slots).
74        unsafe { self.node.as_ref() }
75    }
76
77    /// The entry's key.
78    #[inline]
79    pub fn key(&self) -> &K {
80        &self.leaf().key
81    }
82
83    /// The captured version's value.
84    #[inline]
85    pub fn value(&self) -> &V {
86        self.node()
87            .value()
88            .expect("a VersionedEntryRef never captures a tombstone")
89    }
90
91    /// The captured version.
92    #[inline]
93    pub fn version(&self) -> u64 {
94        self.node().version
95    }
96
97    /// `true` if the captured version was deleted when captured. Always
98    /// `false`: handles never capture tombstones.
99    #[inline]
100    pub fn is_removed(&self) -> bool {
101        false
102    }
103
104    /// `true` once the captured version has been unlinked: a same-version
105    /// insert replaced it, `remove` or `remove_version` removed it, a prune
106    /// unlinked it, or its whole key was removed, pruned or cleared.
107    #[inline]
108    pub fn is_superseded(&self) -> bool {
109        self.node().is_superseded() || self.leaf().chain_latch.is_dead()
110    }
111
112    /// A fresh read of the key's newest live version, sharing this handle's
113    /// protection (no new pin).
114    pub fn latest(&self) -> Option<VersionedEntryRef<'_, K, V>> {
115        let head = self.leaf().head();
116        VersionedEntryRef::new(self.leaf, head, self.tree, self.borrowed())
117    }
118
119    /// A fresh walk of the key's chain for the newest version `<= max_version`.
120    pub fn get_version_le(&self, max_version: u64) -> Option<(u64, &V)> {
121        let n = find_le(self.leaf().head(), max_version)?;
122        n.value().map(|v| (n.version, v))
123    }
124
125    #[inline]
126    fn borrowed(&self) -> GuardHandle<'_> {
127        GuardHandle::Borrowed(self.guard.guard())
128    }
129}
130
131impl<K, V> Clone for VersionedEntryRef<'_, K, V> {
132    /// Shares the protection (see [`EntryRef::clone`](crate::EntryRef)).
133    fn clone(&self) -> Self {
134        Self {
135            leaf: self.leaf,
136            node: self.node,
137            tree: self.tree,
138            guard: self.guard.duplicate(),
139        }
140    }
141}
142
143impl<K, V> Deref for VersionedEntryRef<'_, K, V> {
144    type Target = V;
145
146    #[inline]
147    fn deref(&self) -> &V {
148        self.value()
149    }
150}
151
152impl<K: std::fmt::Debug, V: std::fmt::Debug> std::fmt::Debug for VersionedEntryRef<'_, K, V> {
153    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
154        f.debug_struct("VersionedEntryRef")
155            .field("key", self.key())
156            .field("version", &self.version())
157            .field("value", self.value())
158            .finish()
159    }
160}
161
162impl<K: PartialEq, V: PartialEq> PartialEq for VersionedEntryRef<'_, K, V> {
163    fn eq(&self, other: &Self) -> bool {
164        self.key() == other.key()
165            && self.version() == other.version()
166            && self.value() == other.value()
167    }
168}