dag/namedag/
mem_namedag.rs

1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
8use std::sync::atomic;
9use std::sync::atomic::AtomicU64;
10
11use super::AbstractNameDag;
12use super::NameDagBuilder;
13use crate::iddag::IdDag;
14use crate::iddagstore::InProcessStore;
15use crate::idmap::MemIdMap;
16use crate::ops::IntVersion;
17use crate::ops::Open;
18use crate::ops::Persist;
19use crate::Result;
20
21/// In-memory version of [`NameDag`].
22///
23/// Does not support loading from or saving to the filesystem.
24/// The graph has to be built from scratch by `add_heads`.
25pub type MemNameDag =
26    AbstractNameDag<IdDag<InProcessStore>, MemIdMap, MemNameDagPath, MemNameDagState>;
27
28/// Address to open in-memory Dag.
29#[derive(Debug, Clone)]
30pub struct MemNameDagPath;
31
32#[derive(Debug, Clone)]
33pub struct MemNameDagState {
34    version: (u64, u64),
35}
36
37impl Default for MemNameDagState {
38    fn default() -> Self {
39        Self {
40            version: (rand::random(), 0),
41        }
42    }
43}
44
45impl Open for MemNameDagPath {
46    type OpenTarget = MemNameDag;
47
48    fn open(&self) -> Result<Self::OpenTarget> {
49        let dag = IdDag::new_in_process();
50        let map = MemIdMap::new();
51        let id = format!("mem:{}", next_id());
52        let state = MemNameDagState::default();
53        let result = NameDagBuilder::new_with_idmap_dag(map, dag)
54            .with_path(self.clone())
55            .with_id(id)
56            .with_state(state)
57            .build()?;
58        Ok(result)
59    }
60}
61
62impl MemNameDag {
63    pub fn new() -> Self {
64        MemNameDagPath.open().unwrap()
65    }
66}
67
68impl Persist for MemNameDagState {
69    type Lock = ();
70
71    fn lock(&mut self) -> Result<Self::Lock> {
72        Ok(())
73    }
74
75    fn reload(&mut self, _lock: &Self::Lock) -> Result<()> {
76        Ok(())
77    }
78
79    fn persist(&mut self, _lock: &Self::Lock) -> Result<()> {
80        self.version.1 += 1;
81        Ok(())
82    }
83}
84
85impl IntVersion for MemNameDagState {
86    fn int_version(&self) -> (u64, u64) {
87        self.version
88    }
89}
90
91fn next_id() -> u64 {
92    static ID: AtomicU64 = AtomicU64::new(0);
93    ID.fetch_add(1, atomic::Ordering::AcqRel)
94}