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
use crate::error::{TraverserError, TraverserResult};
use crate::graph::GraphStorage;
use crate::traversal::TraverserContext;
use crate::traversal::optimizer::path_analysis::PathMode;
use crate::value::{PathArena, PathRef, SackRef, TraverserValue};
/// One item flowing through a traversal: its current value and a handle to its path.
///
/// The path lives in the path arena of the execution, so cloning a traverser copies the value
/// handle and four bytes.
pub(crate) struct Traverser<S: GraphStorage> {
/// The current object.
pub value: TraverserValue<S>,
pub(crate) path: PathRef,
/// Multiplicity of this traverser: it stands for `bulk` identical traversers (TinkerPop
/// `Traverser.bulk()`). Always at least 1. Values above 1 exist only after a merge point
/// (see `traversal/bulk.rs`).
pub(crate) bulk: u64,
/// Handle of this traverser's sack in the execution's sack arena; `SackRef::NONE` (reads as
/// `null`) when the query uses no `withSack`. Four bytes that fit the padding after `path`.
pub(crate) sack: SackRef,
}
impl<S: GraphStorage> std::fmt::Debug for Traverser<S> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Traverser")
.field("value", &self.value)
.field("path", &self.path)
.field("bulk", &self.bulk)
.field("sack", &self.sack)
.finish()
}
}
impl<S: GraphStorage> Clone for Traverser<S> {
fn clone(&self) -> Self {
Self {
value: self.value.clone(),
path: self.path,
bulk: self.bulk,
sack: self.sack,
}
}
}
impl<S: GraphStorage> Traverser<S> {
/// Creates a traverser with an empty path, a bulk of 1 and no sack (it reads as `null`).
///
/// Use a traversal source's `with_sack` for streams that carry a sack.
#[cfg(test)]
pub(crate) fn from_value(value: TraverserValue<S>) -> Self {
Self {
value,
path: PathRef::NONE,
bulk: 1,
sack: SackRef::NONE,
}
}
/// How many identical traversers this one stands for (TinkerPop `Traverser.bulk()`).
///
/// Always at least 1; it is greater than 1 only for a traverser that merged equal
/// traversers at a merge point.
pub fn bulk(&self) -> u64 {
self.bulk
}
/// A traverser *generated* by a start step or a reducing barrier (TinkerPop
/// `TraverserGenerator.generate`): bulk 1, an empty path and the *initial* sack of the
/// execution.
#[inline]
pub(crate) fn start(context: &TraverserContext<'_, S>, value: TraverserValue<S>) -> Self {
Self {
value,
path: PathRef::NONE,
bulk: 1,
sack: context.initial_sack,
}
}
/// A traverser derived from `self` (TinkerPop `split`): the new value with the same path,
/// bulk and sack.
#[inline]
pub(crate) fn split(&self, value: TraverserValue<S>) -> Self {
Self {
value,
path: self.path,
bulk: self.bulk,
sack: self.sack,
}
}
/// A traverser with an explicit path, bulk and sack.
#[inline]
pub(crate) fn with_parts(
value: TraverserValue<S>,
path: PathRef,
bulk: u64,
sack: SackRef,
) -> Self {
Self {
value,
path,
bulk,
sack,
}
}
/// Returns the schema carried by this traverser, if its value is one.
#[cfg(test)]
pub(crate) fn as_schema(&self) -> Option<&crate::graph::schema::GraphSchema> {
self.value.as_schema()
}
/// Records the current value as a new position of the path when `mode` is `Full`, and drops
/// the path when nothing downstream reads it. In `Labels` mode the path is left untouched:
/// only `as()` records positions there.
#[inline(always)]
pub(crate) fn extend_path(
&mut self,
paths: &mut PathArena<S>,
mode: &PathMode,
) -> TraverserResult<()> {
match mode {
PathMode::Full => {
self.path = paths.push(self.path, self.value.clone(), None)?;
}
PathMode::Labels(_) => {}
PathMode::None => self.path = PathRef::NONE,
}
Ok(())
}
/// Keeps the path of a traverser that passes through a step unchanged, or drops it when
/// nothing downstream reads it.
#[inline(always)]
pub(crate) fn keep_path(&mut self, mode: &PathMode) {
if mode.is_none() {
self.path = PathRef::NONE;
}
}
/// Starts a new path at the current value, for steps that create traversers (start steps,
/// barriers): the first position in `Full` mode, an empty path otherwise.
#[inline(always)]
pub(crate) fn start_path(
mut self,
paths: &mut PathArena<S>,
mode: &PathMode,
) -> TraverserResult<Self> {
self.path = PathRef::NONE;
if matches!(mode, PathMode::Full) {
self.path = paths.push(PathRef::NONE, self.value.clone(), None)?;
}
Ok(self)
}
/// The type name a string step reports when [`as_string`](Self::as_string) found no string.
///
/// Reads the stored value's type in place, without materializing it: a property that is
/// absent is `null`, a stored value reports its [`ValueType`](crate::graph::ValueType) name
/// (`uuid`, `int64`, ...), and a non-property stream value reports its stream kind.
pub(crate) fn observed_type_name(
context: &TraverserContext<'_, S>,
traverser_value: &TraverserValue<S>,
) -> String {
let stored = match traverser_value {
TraverserValue::Computed(value, _) => Some(value),
TraverserValue::VertexProperty(prop, vertex_index, _) => {
if prop.eq("id") || prop.eq("label") {
return "string".to_string();
}
match context
.storage
.vertex_properties(*vertex_index)
.and_then(|p| p.get(prop.as_str()))
{
Some(value) => Some(value),
None => return "null".to_string(),
}
}
TraverserValue::EdgeProperty(prop, edge_index, _) => {
if prop.eq("id") || prop.eq("label") {
return "string".to_string();
}
match context
.storage
.edge_properties(*edge_index)
.and_then(|p| p.get(prop.as_str()))
{
Some(value) => Some(value),
None => return "null".to_string(),
}
}
_ => None,
};
match stored {
Some(value) => crate::graph::schema::value_type_name(value),
None => traverser_value.type_name().to_string(),
}
}
pub(crate) fn as_string(
context: &TraverserContext<'_, S>,
traverser_value: &TraverserValue<S>,
) -> TraverserResult<Option<String>> {
match traverser_value {
TraverserValue::Computed(value, _) => Ok(value.text().map(|s| s.into_owned())),
TraverserValue::VertexProperty(prop, vertex_index, _) => {
if prop.eq("label") {
Ok(context
.storage
.vertex_label(*vertex_index)
.map(|s| s.to_string()))
} else if prop.eq("id") {
let id =
crate::graph::storage::stored_vertex_id(&*context.storage, *vertex_index)?
.to_string();
Ok(Some(id))
} else {
let value = context
.storage
.vertex_properties(*vertex_index)
.and_then(|p| p.get(prop.as_str()))
.and_then(|p| p.text())
.map(|s| s.into_owned());
Ok(value)
}
}
TraverserValue::EdgeProperty(prop, edge_index, _) => {
if prop.eq("label") {
Ok(context
.storage
.edge_label(*edge_index)
.map(|s| s.to_string()))
} else if prop.eq("id") {
let id = crate::graph::storage::stored_edge_id(&*context.storage, *edge_index)?
.to_string();
Ok(Some(id))
} else {
let value = context
.storage
.edge_properties(*edge_index)
.and_then(|p| p.get(prop.as_str()))
.and_then(|p| p.text())
.map(|s| s.into_owned());
Ok(value)
}
}
t => Err(Box::new(TraverserError::cast_exception(
&["computed", "vertexProperty", "edgeProperty"],
t,
))),
}
}
/// Borrowing sibling of [`Traverser::as_string`], for callers that only need the string for
/// an immediate comparison (e.g. `P::test()`'s `Eq`/`Neq` arms) and would otherwise discard
/// the owned `String` right after it. Every value stored in the graph is already backed by a
/// `&str` reachable from `context`, so every case borrows at zero cost; a vertex/edge without
/// a stored id is an `InvalidElementState` error, never a made-up id. The [`std::borrow::Cow`]
/// return type leaves room for a future case that has to allocate.
///
/// `as_string()` itself keeps its own `Option<String>` contract: every one of its other call
/// sites (`cast()`, and the `StartingWith`/`EndingWith`/`Containing`/`WithIn` predicate
/// arms; the string steps now borrow through this function) either mutates the string
/// or needs to own it past the point where `context`'s borrow ends, so changing its contract
/// would just move the allocation to those call sites instead of removing it.
pub(crate) fn as_string_ref<'ctx>(
context: &'ctx TraverserContext<'_, S>,
traverser_value: &'ctx TraverserValue<S>,
) -> TraverserResult<Option<std::borrow::Cow<'ctx, str>>> {
use std::borrow::Cow;
match traverser_value {
TraverserValue::Computed(value, _) => Ok(value.text()),
TraverserValue::VertexProperty(prop, vertex_index, _) => {
if prop.eq("label") {
Ok(context
.storage
.vertex_label(*vertex_index)
.map(Cow::Borrowed))
} else if prop.eq("id") {
let id = Cow::Borrowed(crate::graph::storage::stored_vertex_id(
&*context.storage,
*vertex_index,
)?);
Ok(Some(id))
} else {
let value = context
.storage
.vertex_properties(*vertex_index)
.and_then(|p| p.get(prop.as_str()))
.and_then(|p| p.text());
Ok(value)
}
}
TraverserValue::EdgeProperty(prop, edge_index, _) => {
if prop.eq("label") {
Ok(context.storage.edge_label(*edge_index).map(Cow::Borrowed))
} else if prop.eq("id") {
let id = Cow::Borrowed(crate::graph::storage::stored_edge_id(
&*context.storage,
*edge_index,
)?);
Ok(Some(id))
} else {
let value = context
.storage
.edge_properties(*edge_index)
.and_then(|p| p.get(prop.as_str()))
.and_then(|p| p.text());
Ok(value)
}
}
t => Err(Box::new(TraverserError::cast_exception(
&["computed", "vertexProperty", "edgeProperty"],
t,
))),
}
}
}
#[cfg(test)]
mod tests {
use super::Traverser;
use crate::graph::TraversalGraph;
use crate::value::TraverserValue;
use std::mem::size_of;
/// Rule 20: the value (64 bytes), a 4-byte path handle, a 4-byte sack handle in the former
/// padding and an 8-byte bulk; traversers stay cheap to clone and to buffer.
#[test]
fn traverser_stays_80_bytes() {
type G = TraversalGraph;
assert_eq!(size_of::<Traverser<G>>(), 80);
assert!(size_of::<Traverser<G>>() <= size_of::<TraverserValue<G>>() + 16);
}
}