oxirs-core 0.2.4

Core RDF and SPARQL functionality for OxiRS - native Rust implementation with zero dependencies
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
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
//! Arena-based memory management for efficient RDF data allocation
//!
//! This module provides arena allocators that allocate RDF terms and triples
//! in contiguous memory blocks, reducing memory fragmentation and improving
//! cache locality.

use crate::model::{Term, Triple};
use bumpalo::Bump;
use parking_lot::Mutex;
use std::cell::RefCell;
use std::collections::HashMap;
use std::marker::PhantomData;
use std::sync::Arc;

thread_local! {
    static THREAD_ARENA: RefCell<Option<Bump>> = const { RefCell::new(None) };
}

/// Arena-allocated string slice with lifetime tied to the arena
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ArenaStr<'arena> {
    value: &'arena str,
}

impl<'arena> ArenaStr<'arena> {
    pub fn as_str(&self) -> &'arena str {
        self.value
    }
}

/// Arena-allocated term reference
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ArenaTerm<'arena> {
    NamedNode(ArenaStr<'arena>),
    BlankNode(ArenaStr<'arena>),
    Literal {
        value: ArenaStr<'arena>,
        language: Option<ArenaStr<'arena>>,
        datatype: Option<ArenaStr<'arena>>,
    },
    Variable(ArenaStr<'arena>),
}

/// Arena-allocated triple reference
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ArenaTriple<'arena> {
    pub subject: ArenaTerm<'arena>,
    pub predicate: ArenaStr<'arena>,
    pub object: ArenaTerm<'arena>,
}

/// Single-threaded arena for allocating RDF data
pub struct LocalArena {
    bump: RefCell<Bump>,
    allocated_bytes: RefCell<usize>,
}

impl Default for LocalArena {
    fn default() -> Self {
        Self::new()
    }
}

impl LocalArena {
    /// Create a new local arena
    pub fn new() -> Self {
        Self {
            bump: RefCell::new(Bump::new()),
            allocated_bytes: RefCell::new(0),
        }
    }

    /// Create a new arena with a specific capacity
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            bump: RefCell::new(Bump::with_capacity(capacity)),
            allocated_bytes: RefCell::new(0),
        }
    }

    /// Allocate a string in the arena
    pub fn alloc_str(&self, s: &str) -> ArenaStr<'_> {
        let value = unsafe {
            // We use unsafe here because we know the arena will outlive the returned reference
            let bump = &*self.bump.as_ptr();
            bump.alloc_str(s)
        };
        *self.allocated_bytes.borrow_mut() += s.len();
        ArenaStr { value }
    }

    /// Allocate a term in the arena
    pub fn alloc_term<'a>(&'a self, term: &Term) -> ArenaTerm<'a> {
        match term {
            Term::NamedNode(n) => ArenaTerm::NamedNode(self.alloc_str(n.as_str())),
            Term::BlankNode(b) => ArenaTerm::BlankNode(self.alloc_str(b.as_str())),
            Term::Literal(l) => ArenaTerm::Literal {
                value: self.alloc_str(l.value()),
                language: l.language().map(|lang| self.alloc_str(lang)),
                datatype: if l.datatype().as_str() != "http://www.w3.org/2001/XMLSchema#string" {
                    Some(self.alloc_str(l.datatype().as_str()))
                } else {
                    None
                },
            },
            Term::Variable(v) => ArenaTerm::Variable(self.alloc_str(v.as_str())),
            Term::QuotedTriple(_) => panic!("QuotedTriple not supported in arena"),
        }
    }

    /// Allocate a triple in the arena
    pub fn alloc_triple<'a>(&'a self, triple: &Triple) -> ArenaTriple<'a> {
        // Convert subject to term
        let subject_term = match triple.subject() {
            crate::model::Subject::NamedNode(n) => Term::NamedNode(n.clone()),
            crate::model::Subject::BlankNode(b) => Term::BlankNode(b.clone()),
            crate::model::Subject::Variable(v) => Term::Variable(v.clone()),
            crate::model::Subject::QuotedTriple(_) => panic!("QuotedTriple not supported"),
        };

        // Convert object to term
        let object_term = match triple.object() {
            crate::model::Object::NamedNode(n) => Term::NamedNode(n.clone()),
            crate::model::Object::BlankNode(b) => Term::BlankNode(b.clone()),
            crate::model::Object::Literal(l) => Term::Literal(l.clone()),
            crate::model::Object::Variable(v) => Term::Variable(v.clone()),
            crate::model::Object::QuotedTriple(_) => panic!("QuotedTriple not supported"),
        };

        // Get predicate string
        let predicate_str = match triple.predicate() {
            crate::model::Predicate::NamedNode(n) => n.as_str(),
            crate::model::Predicate::Variable(v) => v.as_str(),
        };

        ArenaTriple {
            subject: self.alloc_term(&subject_term),
            predicate: self.alloc_str(predicate_str),
            object: self.alloc_term(&object_term),
        }
    }

    /// Get the total allocated bytes
    pub fn allocated_bytes(&self) -> usize {
        *self.allocated_bytes.borrow()
    }

    /// Reset the arena, freeing all allocations
    pub fn reset(&self) {
        self.bump.borrow_mut().reset();
        *self.allocated_bytes.borrow_mut() = 0;
    }
}

/// Thread-safe arena for concurrent allocation
/// Uses thread-local storage to avoid cross-thread sharing of non-Send types
pub struct ConcurrentArena {
    arena_size: usize,
    total_allocated: Arc<Mutex<usize>>,
}

impl ConcurrentArena {
    /// Create a new concurrent arena with the specified arena size
    pub fn new(arena_size: usize) -> Self {
        Self {
            arena_size,
            total_allocated: Arc::new(Mutex::new(0)),
        }
    }

    /// Allocate a string in the arena using thread-local storage
    pub fn alloc_str(&self, s: &str) -> &'static str {
        let len = s.len();

        THREAD_ARENA.with(|arena_cell| {
            let mut arena_opt = arena_cell.borrow_mut();
            if arena_opt.is_none() {
                *arena_opt = Some(Bump::with_capacity(self.arena_size.max(len * 2)));
            }

            let arena = arena_opt
                .as_ref()
                .expect("arena was just initialized above");
            let allocated = arena.alloc_str(s);
            *self.total_allocated.lock() += len;

            // Unsafe: We're extending the lifetime to 'static
            // This is safe as long as the arena lives as long as the references
            unsafe { std::mem::transmute(allocated) }
        })
    }

    /// Get total allocated bytes across all thread-local arenas
    pub fn total_allocated(&self) -> usize {
        *self.total_allocated.lock()
    }

    /// Get the number of thread-local arenas (simplified to 1 for thread-local impl)
    pub fn arena_count(&self) -> usize {
        THREAD_ARENA.with(
            |arena_cell| {
                if arena_cell.borrow().is_some() {
                    1
                } else {
                    0
                }
            },
        )
    }
}

/// Graph arena that manages memory for an entire RDF graph
pub struct GraphArena<'arena> {
    local_arena: LocalArena,
    term_cache: RefCell<HashMap<Term, ArenaTerm<'arena>>>,
    _phantom: PhantomData<&'arena ()>,
}

impl<'arena> Default for GraphArena<'arena> {
    fn default() -> Self {
        Self::new()
    }
}

impl<'arena> GraphArena<'arena> {
    /// Create a new graph arena
    pub fn new() -> Self {
        Self {
            local_arena: LocalArena::new(),
            term_cache: RefCell::new(HashMap::new()),
            _phantom: PhantomData,
        }
    }

    /// Create a new graph arena with capacity
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            local_arena: LocalArena::with_capacity(capacity),
            term_cache: RefCell::new(HashMap::new()),
            _phantom: PhantomData,
        }
    }

    /// Allocate a term, using cache for deduplication
    pub fn alloc_term(&'arena self, term: &Term) -> ArenaTerm<'arena> {
        let mut cache = self.term_cache.borrow_mut();
        if let Some(&cached) = cache.get(term) {
            return cached;
        }

        let allocated = self.local_arena.alloc_term(term);
        cache.insert(term.clone(), allocated);
        allocated
    }

    /// Allocate a triple
    pub fn alloc_triple(&'arena self, triple: &Triple) -> ArenaTriple<'arena> {
        self.local_arena.alloc_triple(triple)
    }

    /// Get allocated bytes
    pub fn allocated_bytes(&self) -> usize {
        self.local_arena.allocated_bytes()
    }

    /// Get the number of cached terms
    pub fn cached_terms(&self) -> usize {
        self.term_cache.borrow().len()
    }

    /// Clear the arena and cache
    pub fn clear(&self) {
        self.local_arena.reset();
        self.term_cache.borrow_mut().clear();
    }
}

/// Scoped arena for temporary allocations
pub struct ScopedArena<'parent> {
    parent: &'parent LocalArena,
    checkpoint: usize,
}

impl<'parent> ScopedArena<'parent> {
    /// Create a new scoped arena
    pub fn new(parent: &'parent LocalArena) -> Self {
        let checkpoint = parent.allocated_bytes();
        Self { parent, checkpoint }
    }

    /// Allocate a string in the scoped arena
    pub fn alloc_str<'a>(&'a self, s: &str) -> ArenaStr<'a>
    where
        'parent: 'a,
    {
        self.parent.alloc_str(s)
    }

    /// Allocate a term in the scoped arena
    pub fn alloc_term<'a>(&'a self, term: &Term) -> ArenaTerm<'a>
    where
        'parent: 'a,
    {
        self.parent.alloc_term(term)
    }

    /// Get bytes allocated in this scope
    pub fn scope_allocated(&self) -> usize {
        self.parent.allocated_bytes() - self.checkpoint
    }
}

impl<'parent> Drop for ScopedArena<'parent> {
    fn drop(&mut self) {
        // In a real implementation, we could reset to checkpoint
        // For now, we just track the allocation
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Literal, NamedNode};
    use std::thread;

    #[test]
    fn test_local_arena() {
        let arena = LocalArena::new();

        // Test string allocation
        let s1 = arena.alloc_str("hello");
        let s2 = arena.alloc_str("world");
        assert_eq!(s1.as_str(), "hello");
        assert_eq!(s2.as_str(), "world");

        // Test term allocation
        let term = Term::NamedNode(NamedNode::new("http://example.org/test").expect("valid IRI"));
        let arena_term = arena.alloc_term(&term);
        match arena_term {
            ArenaTerm::NamedNode(s) => assert_eq!(s.as_str(), "http://example.org/test"),
            _ => panic!("Wrong term type"),
        }

        assert!(arena.allocated_bytes() > 0);
    }

    #[test]
    fn test_triple_allocation() {
        let arena = LocalArena::new();

        let triple = Triple::new(
            NamedNode::new("http://s").expect("valid IRI"),
            NamedNode::new("http://p").expect("valid IRI"),
            Literal::new("object"),
        );

        let arena_triple = arena.alloc_triple(&triple);
        match arena_triple.subject {
            ArenaTerm::NamedNode(s) => assert_eq!(s.as_str(), "http://s"),
            _ => panic!("Wrong subject type"),
        }
        assert_eq!(arena_triple.predicate.as_str(), "http://p");
        match arena_triple.object {
            ArenaTerm::Literal { value, .. } => assert_eq!(value.as_str(), "object"),
            _ => panic!("Wrong object type"),
        }
    }

    #[test]
    fn test_concurrent_arena() {
        let arena = Arc::new(ConcurrentArena::new(1024));

        // Test concurrent allocation
        thread::scope(|s| {
            let handles: Vec<_> = (0..4)
                .map(|i| {
                    let arena_clone = Arc::clone(&arena);
                    s.spawn(move || {
                        for j in 0..100 {
                            let string = format!("thread_{i}_item_{j}");
                            let allocated = arena_clone.alloc_str(&string);
                            assert_eq!(allocated, string);
                        }
                    })
                })
                .collect();

            for handle in handles {
                handle.join().expect("thread should not panic");
            }
        });

        // Ensure the main thread also initializes its thread-local arena
        let _main_alloc = arena.alloc_str("main_thread_test");

        assert!(arena.total_allocated() > 0);
        assert!(arena.arena_count() >= 1);
    }

    #[test]
    fn test_graph_arena() {
        let arena = GraphArena::new();

        // Test term caching
        let term1 = Term::NamedNode(NamedNode::new("http://example.org/same").expect("valid IRI"));
        let term2 = term1.clone();

        let allocated1 = arena.alloc_term(&term1);
        let allocated2 = arena.alloc_term(&term2);

        // Should be the same due to caching
        assert_eq!(allocated1, allocated2);
        assert_eq!(arena.cached_terms(), 1);
    }

    #[test]
    fn test_scoped_arena() {
        let parent = LocalArena::new();
        let initial = parent.allocated_bytes();

        {
            let scoped = ScopedArena::new(&parent);
            scoped.alloc_str("temporary");
            assert!(scoped.scope_allocated() > 0);
        }

        // Allocation persists after scope ends (simplified implementation)
        assert!(parent.allocated_bytes() > initial);
    }

    #[test]
    fn test_arena_reset() {
        let arena = LocalArena::new();

        arena.alloc_str("test1");
        arena.alloc_str("test2");
        let allocated = arena.allocated_bytes();
        assert!(allocated > 0);

        arena.reset();
        assert_eq!(arena.allocated_bytes(), 0);
    }
}