graph-api-lib 0.2.1

Core library for the graph-api ecosystem - a flexible, type-safe API for working with in-memory graphs in Rust
Documentation
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
use crate::ElementId;
use crate::graph::Graph;
use crate::walker::builder::{EdgeWalkerBuilder, StartWalkerBuilder, VertexWalkerBuilder};
use crate::walker::steps::Empty;
use crate::walker::{EdgeWalker, VertexWalker, Walker};
use include_doc::function_body;
use std::marker::PhantomData;
use std::ops::{Deref, DerefMut};
// ================ CONTEXT IMPLEMENTATION ================

#[derive(Clone, Debug)]
pub struct ContextRef<Current, Parent> {
    inner: Inner<Current, Parent>,
}

#[derive(Debug, Clone)]
struct Inner<Current, Parent> {
    parent: Parent,
    delegate: Current,
}

impl<Current, Parent> Deref for ContextRef<Current, Parent> {
    type Target = Current;

    fn deref(&self) -> &Self::Target {
        &self.inner.delegate
    }
}

impl<Current, Parent> DerefMut for ContextRef<Current, Parent> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.inner.delegate
    }
}

impl<Current, Parent> ContextRef<Current, Parent> {
    pub(crate) fn new(delegate: Current, parent: Parent) -> ContextRef<Current, Parent> {
        Self {
            inner: Inner { parent, delegate },
        }
    }
    pub fn parent(&self) -> &Parent {
        &self.inner.parent
    }
}

#[derive(Clone, Debug)]
pub struct DefaultVertexContext<VertexId, Vertex> {
    pub(crate) vertex_id: VertexId,
    pub(crate) vertex: Vertex,
}

impl<VertexId, Vertex> DefaultVertexContext<VertexId, Vertex> {
    pub fn vertex(&self) -> &Vertex {
        &self.vertex
    }

    pub fn vertex_id(&self) -> &VertexId {
        &self.vertex_id
    }
}

#[derive(Clone, Debug)]
pub struct DefaultEdgeContext<EdgeId, Edge> {
    pub(crate) edge_id: EdgeId,
    pub(crate) edge: Edge,
}

impl<EdgeId, Edge> DefaultEdgeContext<EdgeId, Edge> {
    pub fn edge(&self) -> &Edge {
        &self.edge
    }

    pub fn edge_id(&self) -> &EdgeId {
        &self.edge_id
    }
}

pub struct VertexContext<'graph, Parent, Callback, Context>
where
    Parent: VertexWalker<'graph>,
    Callback: Fn(&<Parent::Graph as Graph>::VertexReference<'_>, &Parent::Context) -> Context,
{
    _phantom_data: PhantomData<&'graph ()>,
    parent: Parent,
    callback: Callback,
    context: Option<Context>,
}

impl<'graph, Parent, Callback, Context> VertexContext<'graph, Parent, Callback, Context>
where
    Parent: VertexWalker<'graph>,
    Callback: Fn(&<Parent::Graph as Graph>::VertexReference<'_>, &Parent::Context) -> Context,
{
    pub fn new(parent: Parent, callback: Callback) -> Self {
        VertexContext {
            _phantom_data: Default::default(),
            parent,
            callback,
            context: None,
        }
    }
}

impl<'graph, Parent, Predicate, Context> Walker<'graph>
    for VertexContext<'graph, Parent, Predicate, Context>
where
    Parent: VertexWalker<'graph>,
    Predicate: Fn(&<Parent::Graph as Graph>::VertexReference<'_>, &Parent::Context) -> Context,
    Context: Clone + 'static,
{
    type Graph = Parent::Graph;
    type Context = Context;

    fn next_element(&mut self, graph: &'graph Self::Graph) -> Option<ElementId<Self::Graph>> {
        self.next(graph).map(ElementId::Vertex)
    }

    fn ctx(&self) -> &Self::Context {
        self.context
            .as_ref()
            .expect("context cannot be retrieved before call to next")
    }

    fn ctx_mut(&mut self) -> &mut Self::Context {
        self.context
            .as_mut()
            .expect("context cannot be retrieved before call to next")
    }
}

impl<'graph, Parent, Predicate, Context> VertexWalker<'graph>
    for VertexContext<'graph, Parent, Predicate, Context>
where
    Parent: VertexWalker<'graph>,
    Predicate: Fn(&<Parent::Graph as Graph>::VertexReference<'_>, &Parent::Context) -> Context,
    Context: Clone + 'static,
{
    fn next(&mut self, graph: &'graph Self::Graph) -> Option<<Self::Graph as Graph>::VertexId> {
        while let Some(next) = self.parent.next(graph) {
            if let Some(vertex) = graph.vertex(next) {
                self.context = Some((self.callback)(&vertex, self.parent.ctx()));
                return Some(next);
            }
        }
        None
    }
}

pub struct EdgeContext<'graph, Parent, Callback, Context>
where
    Parent: EdgeWalker<'graph>,
    Callback: Fn(&<Parent::Graph as Graph>::EdgeReference<'_>, &Parent::Context) -> Context,
{
    _phantom_data: PhantomData<&'graph ()>,
    parent: Parent,
    callback: Callback,
    context: Option<Context>,
}

impl<'graph, Parent, Callback, Context> EdgeContext<'graph, Parent, Callback, Context>
where
    Parent: EdgeWalker<'graph>,
    Callback: Fn(&<Parent::Graph as Graph>::EdgeReference<'_>, &Parent::Context) -> Context,
{
    pub fn new(parent: Parent, callback: Callback) -> Self {
        EdgeContext {
            _phantom_data: Default::default(),
            parent,
            callback,
            context: None,
        }
    }
}

impl<'graph, Parent, Predicate, Context> Walker<'graph>
    for EdgeContext<'graph, Parent, Predicate, Context>
where
    Parent: EdgeWalker<'graph>,
    Predicate: Fn(&<Parent::Graph as Graph>::EdgeReference<'_>, &Parent::Context) -> Context,
    Context: Clone + 'static,
{
    type Graph = Parent::Graph;

    type Context = Context;

    fn next_element(&mut self, graph: &'graph Self::Graph) -> Option<ElementId<Self::Graph>> {
        self.next(graph).map(ElementId::Edge)
    }
    fn ctx(&self) -> &Self::Context {
        self.context
            .as_ref()
            .expect("context cannot be retrieved before call to next")
    }

    fn ctx_mut(&mut self) -> &mut Self::Context {
        self.context
            .as_mut()
            .expect("context cannot be retrieved before call to next")
    }
}

impl<'graph, Parent, Predicate, Context> EdgeWalker<'graph>
    for EdgeContext<'graph, Parent, Predicate, Context>
where
    Parent: EdgeWalker<'graph>,
    Predicate: Fn(&<Parent::Graph as Graph>::EdgeReference<'_>, &Parent::Context) -> Context,
    Context: Clone + 'static,
{
    fn next(&mut self, graph: &'graph Self::Graph) -> Option<<Self::Graph as Graph>::EdgeId> {
        if let Some(next) = self.parent.next(graph) {
            if let Some(edge) = graph.edge(next) {
                self.context = Some((self.callback)(&edge, self.parent.ctx()));
                return Some(next);
            }
        }
        None
    }
}

impl<'graph, Mutability, Graph, Walker> VertexWalkerBuilder<'graph, Mutability, Graph, Walker>
where
    Graph: crate::graph::Graph,
    Walker: VertexWalker<'graph, Graph = Graph>,
{
    /// # Context Step
    ///
    /// The `push_context` step allows you to associate additional data with each element in the traversal.
    /// This is useful for carrying information along as you traverse, preserving state between traversal steps,
    /// or accumulating results.
    ///
    /// ## Visual Diagram
    ///
    /// Before push_context step (traversal with regular elements):
    /// ```text
    ///   [Person A]* --- created ---> [Project X]*  
    ///    |
    ///   knows
    ///    |
    ///   [Person B]*
    /// ```
    ///
    /// After push_context step (elements now have associated context data):
    /// ```text
    ///   [Person A]* + {age: 30} --- created ---> [Project X]* + {name: "Graph API"}
    ///    |
    ///   knows
    ///    |
    ///   [Person B]* + {age: 25}
    /// ```
    ///
    /// ## Parameters
    ///
    /// - `callback`: A function that takes the current element and its existing context,
    ///   and returns a new context value to associate with that element
    ///
    /// ## Return Value
    ///
    /// Returns a traversal with the same elements, but with additional context information
    /// attached to each element.
    ///
    /// ## Example
    ///
    /// ```rust
    #[doc = function_body!("examples/context.rs", vertex_context_example, [])]
    /// ```
    ///
    /// ## Notes
    ///
    /// - Context is carried through the entire traversal, even across different graph elements
    /// - Each push_context call creates a new context layer, with the previous context available as `ctx.parent()`
    /// - For complex traversals, you can build a nested context structure
    /// - The context is cloned for each element, so keep context objects relatively small for performance
    /// - Use `push_default_context()` for common patterns like storing the element's ID and data
    /// - Context persists even when traversing to different elements (e.g., from vertex to connected edge)
    /// - When retrieving results, both the element and its context are returned in a tuple
    pub fn push_context<Callback, Context>(
        self,
        callback: Callback,
    ) -> VertexWalkerBuilder<
        'graph,
        Mutability,
        Graph,
        VertexContext<
            'graph,
            Walker,
            impl Fn(
                &Graph::VertexReference<'_>,
                &Walker::Context,
            ) -> ContextRef<Context, Walker::Context>,
            ContextRef<Context, Walker::Context>,
        >,
    >
    where
        Callback: Fn(&Graph::VertexReference<'_>, &Walker::Context) -> Context + 'graph,
        Context: Clone + 'static,
    {
        self.with_vertex_walker(move |walker| {
            walker.context(move |vertex, context| {
                ContextRef::new(callback(vertex, context), context.clone())
            })
        })
    }
}

impl<'graph, Mutability, Graph, Walker> EdgeWalkerBuilder<'graph, Mutability, Graph, Walker>
where
    Graph: crate::graph::Graph,
    Walker: EdgeWalker<'graph, Graph = Graph>,
    <Walker as crate::walker::Walker<'graph>>::Context: Clone + 'static,
{
    /// # Context Step
    ///
    /// The `push_context` step allows you to associate additional data with each edge in the traversal.
    /// This is useful for carrying information along as you traverse, preserving state between traversal steps,
    /// or accumulating results.
    ///
    /// ## Visual Diagram
    ///
    /// Before push_context step (traversal with regular edges):
    /// ```text
    ///   [Person A] --- created* ---> [Project X]  
    ///    |
    ///   knows*
    ///    |
    ///    v
    ///   [Person B]
    /// ```
    ///
    /// After push_context step (edges now have associated context data):
    /// ```text
    ///   [Person A] --- created* + {type: "maintainer"} ---> [Project X]  
    ///    |
    ///   knows* + {since: "2020"}
    ///    |
    ///    v
    ///   [Person B]
    /// ```
    ///
    /// ## Parameters
    ///
    /// - `callback`: A function that takes the current edge and its existing context,
    ///   and returns a new context value to associate with that edge
    ///
    /// ## Return Value
    ///
    /// Returns a traversal with the same elements, but with additional context information
    /// attached to each edge.
    ///
    /// ## Example
    ///
    /// ```rust
    #[doc = function_body!("examples/context.rs", edge_context_example, [])]
    /// ```
    ///
    /// ## Notes
    ///
    /// - Context is carried through the entire traversal, even across different graph elements
    /// - Each push_context call creates a new context layer, with the previous context available as `ctx.parent()`
    /// - For complex traversals, you can build a nested context structure
    /// - The context is cloned for each element, so keep context objects relatively small for performance
    /// - Use `push_default_context()` for common patterns like storing the edge's ID and data
    /// - When retrieving results, both the element and its context are returned in a tuple
    pub fn push_context<Callback, Context>(
        self,
        callback: Callback,
    ) -> EdgeWalkerBuilder<
        'graph,
        Mutability,
        Graph,
        EdgeContext<
            'graph,
            Walker,
            impl Fn(&Graph::EdgeReference<'_>, &Walker::Context) -> ContextRef<Context, Walker::Context>,
            ContextRef<Context, Walker::Context>,
        >,
    >
    where
        Callback: Fn(&Graph::EdgeReference<'_>, &Walker::Context) -> Context,
        Context: Clone + 'static,
    {
        self.with_edge_walker(move |walker| {
            walker.context(move |edge, context| {
                ContextRef::new(callback(edge, context), context.clone())
            })
        })
    }
}

impl<'graph, Graph, Mutability> StartWalkerBuilder<'graph, Mutability, Graph, ()>
where
    Graph: crate::graph::Graph,
{
    pub fn push_context<Context>(
        self,
        context: Context,
    ) -> StartWalkerBuilder<'graph, Mutability, Graph, Context>
    where
        Context: Clone + 'static,
    {
        StartWalkerBuilder {
            _phantom: Default::default(),
            graph: self.graph,
            empty: Empty::with_context(context),
        }
    }
}