From ccdf22ec6a0ae4175b4c35107135bea9866c3aae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fabrice=20Desr=C3=A9?= Date: Thu, 2 Nov 2023 11:08:51 -0700 Subject: [PATCH] [refactor] Switch from Rc to Arc --- wnfs-bench/hamt.rs | 12 +-- wnfs-common/src/async_serialize.rs | 4 +- wnfs-common/src/link.rs | 4 +- wnfs-common/src/pathnodes.rs | 6 +- wnfs-hamt/src/diff.rs | 74 +++++++++--------- wnfs-hamt/src/hamt.rs | 30 ++++---- wnfs-hamt/src/merge.rs | 28 +++---- wnfs-hamt/src/node.rs | 102 ++++++++++++------------- wnfs-hamt/src/pointer.rs | 4 +- wnfs-hamt/src/strategies/changes.rs | 6 +- wnfs-hamt/src/strategies/kv.rs | 6 +- wnfs-hamt/src/strategies/operations.rs | 8 +- wnfs/examples/mnemonic_based.rs | 8 +- wnfs/src/private/directory.rs | 90 +++++++++++----------- wnfs/src/private/file.rs | 32 ++++---- wnfs/src/private/forest/hamt.rs | 50 ++++++------ wnfs/src/private/link.rs | 6 +- wnfs/src/private/node/node.rs | 52 ++++++------- wnfs/src/private/previous.rs | 48 ++++++------ wnfs/src/private/share.rs | 10 +-- wnfs/src/public/directory.rs | 46 +++++------ wnfs/src/public/file.rs | 20 ++--- wnfs/src/public/link.rs | 8 +- wnfs/src/public/node/node.rs | 48 ++++++------ wnfs/src/root_tree.rs | 26 +++---- wnfs/src/utils/test.rs | 6 +- 26 files changed, 367 insertions(+), 367 deletions(-) diff --git a/wnfs-bench/hamt.rs b/wnfs-bench/hamt.rs index d13b9449..71453075 100644 --- a/wnfs-bench/hamt.rs +++ b/wnfs-bench/hamt.rs @@ -4,7 +4,7 @@ use criterion::{ Criterion, Throughput, }; use proptest::{arbitrary::any, collection::vec, test_runner::TestRunner}; -use std::{cmp, rc::Rc, sync::Arc}; +use std::{cmp, sync::Arc}; use wnfs_common::{ async_encode, decode, libipld::cbor::DagCborCodec, utils::Sampleable, BlockStore, Link, MemoryBlockStore, @@ -33,7 +33,7 @@ fn node_set(c: &mut Criterion) { (store, kv) }, |(store, (key, value))| async move { - Rc::clone(node) + Arc::clone(node) .set(key, value, store.as_ref()) .await .unwrap(); @@ -75,7 +75,7 @@ fn node_set_consecutive(c: &mut Criterion) { fn node_load_get(c: &mut Criterion) { let store = MemoryBlockStore::default(); let cid = async_std::task::block_on(async { - let mut node = Rc::new(>::default()); + let mut node = Arc::new(>::default()); for i in 0..50 { node.set(i.to_string(), i, &store).await.unwrap(); } @@ -107,7 +107,7 @@ fn node_load_get(c: &mut Criterion) { fn node_load_remove(c: &mut Criterion) { let store = MemoryBlockStore::default(); let cid = async_std::task::block_on(async { - let mut node = Rc::new(>::default()); + let mut node = Arc::new(>::default()); for i in 0..50 { node.set(i.to_string(), i, &store).await.unwrap(); } @@ -136,7 +136,7 @@ fn node_load_remove(c: &mut Criterion) { fn hamt_load_decode(c: &mut Criterion) { let store = MemoryBlockStore::default(); let (cid, bytes) = async_std::task::block_on(async { - let mut node = Rc::new(>::default()); + let mut node = Arc::new(>::default()); for i in 0..50 { node.set(i.to_string(), i, &store).await.unwrap(); } @@ -168,7 +168,7 @@ fn hamt_set_encode(c: &mut Criterion) { || { ( MemoryBlockStore::default(), - Rc::new(>::default()), + Arc::new(>::default()), ) }, |(store, mut node)| async move { diff --git a/wnfs-common/src/async_serialize.rs b/wnfs-common/src/async_serialize.rs index 655712e4..75c95197 100644 --- a/wnfs-common/src/async_serialize.rs +++ b/wnfs-common/src/async_serialize.rs @@ -2,7 +2,7 @@ use crate::BlockStore; use async_trait::async_trait; use libipld::{error::SerdeError, serde as ipld_serde, Ipld}; use serde::{Serialize, Serializer}; -use std::rc::Rc; +use std::sync::Arc; //-------------------------------------------------------------------------------------------------- // Macros @@ -60,7 +60,7 @@ pub trait AsyncSerialize { //-------------------------------------------------------------------------------------------------- #[async_trait(?Send)] -impl AsyncSerialize for Rc { +impl AsyncSerialize for Arc { async fn async_serialize(&self, serializer: S, store: &B) -> Result where S: Serializer, diff --git a/wnfs-common/src/link.rs b/wnfs-common/src/link.rs index e5347444..cc994b25 100644 --- a/wnfs-common/src/link.rs +++ b/wnfs-common/src/link.rs @@ -6,7 +6,7 @@ use libipld::Cid; use serde::de::DeserializeOwned; use std::{ fmt::{self, Debug, Formatter}, - rc::Rc, + sync::Arc, }; //-------------------------------------------------------------------------------------------------- @@ -256,7 +256,7 @@ pub trait RemembersCid { fn persisted_as(&self) -> &OnceCell; } -impl RemembersCid for Rc { +impl RemembersCid for Arc { fn persisted_as(&self) -> &OnceCell { self.as_ref().persisted_as() } diff --git a/wnfs-common/src/pathnodes.rs b/wnfs-common/src/pathnodes.rs index 6699daaf..f5175010 100644 --- a/wnfs-common/src/pathnodes.rs +++ b/wnfs-common/src/pathnodes.rs @@ -1,4 +1,4 @@ -use std::rc::Rc; +use std::sync::Arc; //-------------------------------------------------------------------------------------------------- // Type Definitions @@ -7,8 +7,8 @@ use std::rc::Rc; /// Represents the directory nodes along a path. #[derive(Debug, Clone, PartialEq, Eq)] pub struct PathNodes { - pub path: Vec<(Rc, String)>, - pub tail: Rc, + pub path: Vec<(Arc, String)>, + pub tail: Arc, } /// The kinds of outcome from getting a `PathNodes`. diff --git a/wnfs-hamt/src/diff.rs b/wnfs-hamt/src/diff.rs index 51971bfe..8b6a4a82 100644 --- a/wnfs-hamt/src/diff.rs +++ b/wnfs-hamt/src/diff.rs @@ -3,7 +3,7 @@ use crate::{Hasher, Node, Pair, Pointer, HAMT_BITMASK_BIT_SIZE}; use anyhow::{Ok, Result}; use async_recursion::async_recursion; use serde::de::DeserializeOwned; -use std::{collections::HashMap, hash::Hash, mem, rc::Rc}; +use std::{collections::HashMap, hash::Hash, mem, sync::Arc}; use wnfs_common::{BlockStore, Link}; //-------------------------------------------------------------------------------------------------- @@ -41,14 +41,14 @@ pub struct KeyValueChange { /// # Examples /// /// ``` -/// use std::rc::Rc; +/// use std::sync::Arc; /// use wnfs_hamt::{Node, Pair, diff}; /// use wnfs_common::{Link, MemoryBlockStore}; /// /// #[async_std::main] /// async fn main() { /// let store = &MemoryBlockStore::new(); -/// let main_node = &mut Rc::new(Node::<[u8; 4], String>::default()); +/// let main_node = &mut Arc::new(Node::<[u8; 4], String>::default()); /// for i in 0u32..3 { /// main_node /// .set(i.to_le_bytes(), i.to_string(), store) @@ -56,15 +56,15 @@ pub struct KeyValueChange { /// .unwrap(); /// } /// -/// let other_node = &mut Rc::new(Node::<[u8; 4], String>::default()); +/// let other_node = &mut Arc::new(Node::<[u8; 4], String>::default()); /// other_node /// .set(0_u32.to_le_bytes(), 0_u32.to_string(), store) /// .await /// .unwrap(); /// /// let changes = diff( -/// Link::from(Rc::clone(main_node)), -/// Link::from(Rc::clone(other_node)), +/// Link::from(Arc::clone(main_node)), +/// Link::from(Arc::clone(other_node)), /// store, /// ) /// .await @@ -75,8 +75,8 @@ pub struct KeyValueChange { /// } /// ``` pub async fn diff( - main_link: Link>>, - other_link: Link>>, + main_link: Link>>, + other_link: Link>>, store: &impl BlockStore, ) -> Result>> where @@ -89,8 +89,8 @@ where #[async_recursion(?Send)] pub async fn diff_helper( - main_link: Link>>, - other_link: Link>>, + main_link: Link>>, + other_link: Link>>, depth: usize, store: &impl BlockStore, ) -> Result>> @@ -140,7 +140,7 @@ where // Main and other have a value. They may be the same or different so we check. let main_index = main_node.get_value_index(index); let main_pointer = mem::take( - Rc::make_mut(&mut main_node) + Arc::make_mut(&mut main_node) .pointers .get_mut(main_index) .unwrap(), @@ -148,7 +148,7 @@ where let other_index = other_node.get_value_index(index); let other_pointer = mem::take( - Rc::make_mut(&mut other_node) + Arc::make_mut(&mut other_node) .pointers .get_mut(other_index) .unwrap(), @@ -277,13 +277,13 @@ async fn create_node_from_pairs( values: Vec>, depth: usize, store: &impl BlockStore, -) -> Result>> +) -> Result>> where K: DeserializeOwned + Clone + AsRef<[u8]>, V: DeserializeOwned + Clone, H: Hasher + Clone + 'static, { - let mut node = Rc::new(Node::<_, _, H>::default()); + let mut node = Arc::new(Node::<_, _, H>::default()); for Pair { key, value } in values { let digest = &H::hash(&key); let hashnibbles = &mut HashNibbles::with_cursor(digest, depth); @@ -300,7 +300,7 @@ where mod tests { use super::{ChangeType::*, *}; use helper::*; - use std::{collections::BTreeSet, rc::Rc}; + use std::collections::BTreeSet; use wnfs_common::MemoryBlockStore; mod helper { @@ -335,7 +335,7 @@ mod tests { async fn can_diff_main_node_with_added_removed_pairs() { let store = &MemoryBlockStore::default(); - let main_node = &mut Rc::new(Node::<[u8; 4], String>::default()); + let main_node = &mut Arc::new(Node::<[u8; 4], String>::default()); for i in 0u32..3 { main_node .set(i.to_le_bytes(), i.to_string(), store) @@ -343,15 +343,15 @@ mod tests { .unwrap(); } - let other_node = &mut Rc::new(Node::<[u8; 4], String>::default()); + let other_node = &mut Arc::new(Node::<[u8; 4], String>::default()); other_node .set(0_u32.to_le_bytes(), 0_u32.to_string(), store) .await .unwrap(); let changes = diff( - Link::from(Rc::clone(main_node)), - Link::from(Rc::clone(other_node)), + Link::from(Arc::clone(main_node)), + Link::from(Arc::clone(other_node)), store, ) .await @@ -376,8 +376,8 @@ mod tests { ); let changes = diff( - Link::from(Rc::clone(other_node)), - Link::from(Rc::clone(main_node)), + Link::from(Arc::clone(other_node)), + Link::from(Arc::clone(main_node)), store, ) .await @@ -406,7 +406,7 @@ mod tests { async fn can_diff_main_node_with_no_changes() { let store = &MemoryBlockStore::default(); - let main_node = &mut Rc::new(Node::<_, _>::default()); + let main_node = &mut Arc::new(Node::<_, _>::default()); for i in 0_u32..3 { main_node .set(i.to_le_bytes(), i.to_string(), store) @@ -414,7 +414,7 @@ mod tests { .unwrap(); } - let other_node = &mut Rc::new(Node::<_, _>::default()); + let other_node = &mut Arc::new(Node::<_, _>::default()); for i in 0_u32..3 { other_node .set(i.to_le_bytes(), i.to_string(), store) @@ -423,8 +423,8 @@ mod tests { } let changes = diff( - Link::from(Rc::clone(main_node)), - Link::from(Rc::clone(other_node)), + Link::from(Arc::clone(main_node)), + Link::from(Arc::clone(other_node)), store, ) .await @@ -438,7 +438,7 @@ mod tests { let store = &MemoryBlockStore::default(); // A node that adds the first 3 pairs of HASH_KV_PAIRS. - let other_node = &mut Rc::new(Node::<_, _, MockHasher>::default()); + let other_node = &mut Arc::new(Node::<_, _, MockHasher>::default()); for (digest, kv) in HASH_KV_PAIRS.iter().take(3) { other_node .set_value( @@ -452,7 +452,7 @@ mod tests { } // Another node that keeps the first pair, modify the second pair, removes the third pair, and adds the fourth and fifth pair. - let main_node = &mut Rc::new(Node::<_, _, MockHasher>::default()); + let main_node = &mut Arc::new(Node::<_, _, MockHasher>::default()); main_node .set_value( &mut HashNibbles::new(&HASH_KV_PAIRS[0].0), @@ -486,8 +486,8 @@ mod tests { } let changes = diff( - Link::from(Rc::clone(main_node)), - Link::from(Rc::clone(other_node)), + Link::from(Arc::clone(main_node)), + Link::from(Arc::clone(other_node)), store, ) .await @@ -524,8 +524,8 @@ mod tests { ); let changes = diff( - Link::from(Rc::clone(other_node)), - Link::from(Rc::clone(main_node)), + Link::from(Arc::clone(other_node)), + Link::from(Arc::clone(main_node)), store, ) .await @@ -570,7 +570,7 @@ mod proptests { ChangeType, }; use async_std::task; - use std::{collections::HashSet, rc::Rc}; + use std::{collections::HashSet, sync::Arc}; use test_strategy::proptest; use wnfs_common::{Link, MemoryBlockStore}; @@ -590,14 +590,14 @@ mod proptests { .await .unwrap(); - let main_node = &mut Rc::clone(other_node); + let main_node = &mut Arc::clone(other_node); strategies::apply_changes(main_node, &strategy_changes, store) .await .unwrap(); let changes = super::diff( - Link::from(Rc::clone(main_node)), - Link::from(Rc::clone(other_node)), + Link::from(Arc::clone(main_node)), + Link::from(Arc::clone(other_node)), store, ) .await @@ -654,8 +654,8 @@ mod proptests { let node2 = strategies::node_from_kvs(kvs2, store).await.unwrap(); let changes = super::diff( - Link::from(Rc::clone(&node1)), - Link::from(Rc::clone(&node2)), + Link::from(Arc::clone(&node1)), + Link::from(Arc::clone(&node2)), store, ) .await diff --git a/wnfs-hamt/src/hamt.rs b/wnfs-hamt/src/hamt.rs index 63fe92ab..db838af2 100644 --- a/wnfs-hamt/src/hamt.rs +++ b/wnfs-hamt/src/hamt.rs @@ -9,7 +9,7 @@ use serde::{ ser::Error as SerError, Deserialize, Deserializer, Serialize, Serializer, }; -use std::{collections::BTreeMap, hash::Hash, rc::Rc, str::FromStr}; +use std::{collections::BTreeMap, hash::Hash, str::FromStr, sync::Arc}; use wnfs_common::{AsyncSerialize, BlockStore, Link}; //-------------------------------------------------------------------------------------------------- @@ -34,7 +34,7 @@ pub struct Hamt where H: Hasher, { - pub root: Rc>, + pub root: Arc>, pub version: Version, } @@ -55,7 +55,7 @@ impl Hamt { /// ``` pub fn new() -> Self { Self { - root: Rc::new(Node::default()), + root: Arc::new(Node::default()), version: HAMT_VERSION, } } @@ -65,14 +65,14 @@ impl Hamt { /// # Examples /// /// ``` - /// use std::rc::Rc; + /// use std::sync::Arc; /// use wnfs_hamt::{Hamt, Node}; /// - /// let hamt = Hamt::::with_root(Rc::new(Node::default())); + /// let hamt = Hamt::::with_root(Arc::new(Node::default())); /// /// println!("HAMT: {:?}", hamt); /// ``` - pub fn with_root(root: Rc>) -> Self { + pub fn with_root(root: Arc>) -> Self { Self { root, version: HAMT_VERSION, @@ -84,7 +84,7 @@ impl Hamt { /// # Examples /// /// ``` - /// use std::rc::Rc; + /// use std::sync::Arc; /// use wnfs_hamt::{Hamt, Node}; /// use wnfs_common::MemoryBlockStore; /// @@ -93,14 +93,14 @@ impl Hamt { /// let store = &MemoryBlockStore::default(); /// /// let main_hamt = Hamt::::with_root({ - /// let mut node = Rc::new(Node::default()); + /// let mut node = Arc::new(Node::default()); /// node.set("foo".into(), 400, store).await.unwrap(); /// node.set("bar".into(), 500, store).await.unwrap(); /// node /// }); /// /// let other_hamt = Hamt::::with_root({ - /// let mut node = Rc::new(Node::default()); + /// let mut node = Arc::new(Node::default()); /// node.set("foo".into(), 200, store).await.unwrap(); /// node.set("qux".into(), 600, store).await.unwrap(); /// node @@ -121,8 +121,8 @@ impl Hamt { H: Clone + 'static, { super::diff( - Link::from(Rc::clone(&self.root)), - Link::from(Rc::clone(&other.root)), + Link::from(Arc::clone(&self.root)), + Link::from(Arc::clone(&other.root)), store, ) .await @@ -182,7 +182,7 @@ where fn try_from(ipld: Ipld) -> Result { match ipld { Ipld::Map(mut map) => { - let root = Rc::new( + let root = Arc::new( Node::::deserialize(map.remove("root").ok_or("Missing root")?) .map_err(|e| e.to_string())?, ); @@ -229,7 +229,7 @@ mod tests { #[async_std::test] async fn hamt_can_encode_decode_as_cbor() { let store = &MemoryBlockStore::default(); - let root = Rc::new(Node::default()); + let root = Arc::new(Node::default()); let hamt: Hamt = Hamt::with_root(root); let encoded_hamt = async_encode(&hamt, store, DagCborCodec).await.unwrap(); @@ -247,14 +247,14 @@ mod snapshot_tests { #[async_std::test] async fn test_hamt() { let store = &SnapshotBlockStore::default(); - let node = &mut Rc::new(Node::<[u8; 4], String>::default()); + let node = &mut Arc::new(Node::<[u8; 4], String>::default()); for i in 0..99_u32 { node.set(i.to_le_bytes(), i.to_string(), store) .await .unwrap(); } - let hamt = Hamt::with_root(Rc::clone(node)); + let hamt = Hamt::with_root(Arc::clone(node)); let cid = store.put_async_serializable(&hamt).await.unwrap(); let hamt = store.get_block_snapshot(&cid).await.unwrap(); diff --git a/wnfs-hamt/src/merge.rs b/wnfs-hamt/src/merge.rs index 7b72f7be..3e2d5fcc 100644 --- a/wnfs-hamt/src/merge.rs +++ b/wnfs-hamt/src/merge.rs @@ -2,7 +2,7 @@ use super::{ChangeType, Node}; use crate::{error::HamtError, Hasher}; use anyhow::Result; use serde::de::DeserializeOwned; -use std::{hash::Hash, rc::Rc}; +use std::{hash::Hash, sync::Arc}; use wnfs_common::{BlockStore, Link}; //-------------------------------------------------------------------------------------------------- @@ -11,11 +11,11 @@ use wnfs_common::{BlockStore, Link}; /// Merges a node with another with the help of a resolver function. pub async fn merge( - main_link: Link>>, - other_link: Link>>, + main_link: Link>>, + other_link: Link>>, f: F, store: &B, -) -> Result>> +) -> Result>> where F: Fn(&V, &V) -> Result, K: DeserializeOwned + Eq + Clone + Hash + AsRef<[u8]>, @@ -27,7 +27,7 @@ where let main_node = main_link.resolve_owned_value(store).await?; let other_node = other_link.resolve_owned_value(store).await?; - let mut merge_node = Rc::clone(&main_node); + let mut merge_node = Arc::clone(&main_node); for change in kv_changes { match change.r#type { ChangeType::Remove => { @@ -65,7 +65,7 @@ where mod proptests { use crate::strategies::{self, generate_kvs}; use async_std::task; - use std::{cmp, rc::Rc}; + use std::{cmp, sync::Arc}; use test_strategy::proptest; use wnfs_common::{Link, MemoryBlockStore}; @@ -84,8 +84,8 @@ mod proptests { let merge_node_left_assoc = { let tmp = super::merge( - Link::from(Rc::clone(&node1)), - Link::from(Rc::clone(&node2)), + Link::from(Arc::clone(&node1)), + Link::from(Arc::clone(&node2)), |a, b| Ok(cmp::min(*a, *b)), store, ) @@ -94,7 +94,7 @@ mod proptests { super::merge( Link::from(tmp), - Link::from(Rc::clone(&node3)), + Link::from(Arc::clone(&node3)), |a, b| Ok(cmp::min(*a, *b)), store, ) @@ -138,8 +138,8 @@ mod proptests { let node2 = strategies::node_from_kvs(kvs2, store).await.unwrap(); let merge_node_1 = super::merge( - Link::from(Rc::clone(&node1)), - Link::from(Rc::clone(&node2)), + Link::from(Arc::clone(&node1)), + Link::from(Arc::clone(&node2)), |a, b| Ok(cmp::min(*a, *b)), store, ) @@ -171,8 +171,8 @@ mod proptests { let node2 = strategies::node_from_kvs(kvs2, store).await.unwrap(); let merge_node_1 = super::merge( - Link::from(Rc::clone(&node1)), - Link::from(Rc::clone(&node2)), + Link::from(Arc::clone(&node1)), + Link::from(Arc::clone(&node2)), |a, b| Ok(cmp::min(*a, *b)), store, ) @@ -180,7 +180,7 @@ mod proptests { .unwrap(); let merge_node_2 = super::merge( - Link::from(Rc::clone(&merge_node_1)), + Link::from(Arc::clone(&merge_node_1)), Link::from(node2), |a, b| Ok(cmp::min(*a, *b)), store, diff --git a/wnfs-hamt/src/node.rs b/wnfs-hamt/src/node.rs index 1e5d3ac7..34cb1b0f 100644 --- a/wnfs-hamt/src/node.rs +++ b/wnfs-hamt/src/node.rs @@ -25,7 +25,7 @@ use std::{ fmt::{self, Debug, Formatter}, hash::Hash, marker::PhantomData, - rc::Rc, + sync::Arc, }; use wnfs_common::{AsyncSerialize, BlockStore, HashOutput, Link, RemembersCid}; @@ -41,12 +41,12 @@ pub type BitMaskType = [u8; HAMT_BITMASK_BYTE_SIZE]; /// # Examples /// /// ``` -/// use std::rc::Rc; +/// use std::sync::Arc; /// use wnfs_hamt::Node; /// use wnfs_common::MemoryBlockStore; /// /// let store = &MemoryBlockStore::new(); -/// let node = Rc::new(Node::::default()); +/// let node = Arc::new(Node::::default()); /// /// assert!(node.is_empty()); /// ``` @@ -73,20 +73,20 @@ where /// # Examples /// /// ``` - /// use std::rc::Rc; + /// use std::sync::Arc; /// use wnfs_hamt::Node; /// use wnfs_common::MemoryBlockStore; /// /// #[async_std::main] /// async fn main() { /// let store = &MemoryBlockStore::new(); - /// let mut node = Rc::new(Node::::default()); + /// let mut node = Arc::new(Node::::default()); /// /// node.set("key".into(), 42, store).await.unwrap(); /// assert_eq!(node.get(&String::from("key"), store).await.unwrap(), Some(&42)); /// } /// ``` - pub async fn set(self: &mut Rc, key: K, value: V, store: &impl BlockStore) -> Result<()> + pub async fn set(self: &mut Arc, key: K, value: V, store: &impl BlockStore) -> Result<()> where K: DeserializeOwned + Clone + AsRef<[u8]>, V: DeserializeOwned + Clone, @@ -105,14 +105,14 @@ where /// # Examples /// /// ``` - /// use std::rc::Rc; + /// use std::sync::Arc; /// use wnfs_hamt::Node; /// use wnfs_common::MemoryBlockStore; /// /// #[async_std::main] /// async fn main() { /// let store = &MemoryBlockStore::new(); - /// let mut node = Rc::new(Node::::default()); + /// let mut node = Arc::new(Node::::default()); /// /// node.set("key".into(), 42, store).await.unwrap(); /// assert_eq!(node.get(&String::from("key"), store).await.unwrap(), Some(&42)); @@ -141,14 +141,14 @@ where /// # Examples /// /// ``` - /// use std::rc::Rc; + /// use std::sync::Arc; /// use wnfs_hamt::Node; /// use wnfs_common::MemoryBlockStore; /// /// #[async_std::main] /// async fn main() { /// let store = &mut MemoryBlockStore::new(); - /// let mut node = Rc::new(Node::::default()); + /// let mut node = Arc::new(Node::::default()); /// node.set("key".into(), 40, store).await.unwrap(); /// /// let value = node.get_mut(&String::from("key"), store).await.unwrap().unwrap(); @@ -159,7 +159,7 @@ where /// ``` // TODO(matheus23): Eventually provide a HashMap::Entry-similar API pub async fn get_mut<'a>( - self: &'a mut Rc, + self: &'a mut Arc, key: &K, store: &'a impl BlockStore, ) -> Result> @@ -183,14 +183,14 @@ where /// # Examples /// /// ``` - /// use std::rc::Rc; + /// use std::sync::Arc; /// use wnfs_hamt::{Node, Pair}; /// use wnfs_common::MemoryBlockStore; /// /// #[async_std::main] /// async fn main() { /// let store = &MemoryBlockStore::new(); - /// let mut node = Rc::new(Node::::default()); + /// let mut node = Arc::new(Node::::default()); /// /// node.set("key".into(), 42, store).await.unwrap(); /// assert_eq!(node.get(&String::from("key"), store).await.unwrap(), Some(&42)); @@ -201,7 +201,7 @@ where /// } /// ``` pub async fn remove( - self: &mut Rc, + self: &mut Arc, key: &K, store: &impl BlockStore, ) -> Result>> @@ -222,14 +222,14 @@ where /// # Examples /// /// ``` - /// use std::rc::Rc; + /// use std::sync::Arc; /// use wnfs_hamt::{Node, Hasher}; /// use wnfs_common::MemoryBlockStore; /// /// #[async_std::main] /// async fn main() { /// let store = &MemoryBlockStore::new(); - /// let mut node = Rc::new(Node::::default()); + /// let mut node = Arc::new(Node::::default()); /// /// node.set("key".into(), 42, store).await.unwrap(); /// @@ -260,14 +260,14 @@ where /// # Examples /// /// ``` - /// use std::rc::Rc; + /// use std::sync::Arc; /// use wnfs_hamt::{Node, Hasher, Pair}; /// use wnfs_common::MemoryBlockStore; /// /// #[async_std::main] /// async fn main() { /// let store = &MemoryBlockStore::new(); - /// let mut node = Rc::new(Node::::default()); + /// let mut node = Arc::new(Node::::default()); /// /// node.set("key".into(), 42, store).await.unwrap(); /// assert_eq!(node.get(&String::from("key"), store).await.unwrap(), Some(&42)); @@ -280,7 +280,7 @@ where /// } /// ``` pub async fn remove_by_hash( - self: &mut Rc, + self: &mut Arc, hash: &HashOutput, store: &impl BlockStore, ) -> Result>> @@ -296,7 +296,7 @@ where /// # Examples /// /// ``` - /// use std::rc::Rc; + /// use std::sync::Arc; /// use wnfs_hamt::Node; /// use wnfs_common::MemoryBlockStore; /// @@ -304,7 +304,7 @@ where /// async fn main() { /// let store = &MemoryBlockStore::new(); /// - /// let mut node = Rc::new(Node::::default()); + /// let mut node = Arc::new(Node::::default()); /// assert!(node.is_empty()); /// /// node.set("key".into(), 42, store).await.unwrap(); @@ -330,7 +330,7 @@ where } pub fn set_value<'a>( - self: &'a mut Rc, + self: &'a mut Arc, hashnibbles: &'a mut HashNibbles, key: K, value: V, @@ -351,7 +351,7 @@ where bit_index, value_index ); - let node = Rc::make_mut(self); + let node = Arc::make_mut(self); node.persisted_as = OnceCell::new(); // If the bit is not set yet, insert a new pointer. @@ -383,7 +383,7 @@ where values.insert(index, Pair::new(key, value)); } else { // If values has reached threshold, we need to create a node link that splits it. - let mut sub_node = Rc::new(Node::::default()); + let mut sub_node = Arc::new(Node::::default()); let cursor = hashnibbles.get_cursor(); // We can take because // Pointer::Values() gets replaced with Pointer::Link at the end @@ -400,7 +400,7 @@ where } } Pointer::Link(link) => { - let mut child = Rc::clone(link.resolve_value(store).await?); + let mut child = Arc::clone(link.resolve_value(store).await?); child.set_value(hashnibbles, key, value, store).await?; node.pointers[value_index] = Pointer::Link(Link::from(child)); } @@ -443,7 +443,7 @@ where #[async_recursion(?Send)] pub async fn get_value_mut<'a>( - self: &'a mut Rc, + self: &'a mut Arc, hashnibbles: &mut HashNibbles, store: &'a impl BlockStore, ) -> Result>> @@ -459,7 +459,7 @@ where } let value_index = self.get_value_index(bit_index); - let node = Rc::make_mut(self); + let node = Arc::make_mut(self); node.persisted_as = OnceCell::new(); match &mut node.pointers[value_index] { @@ -478,7 +478,7 @@ where // It's internal and is only more complex because async_recursion doesn't work here #[allow(clippy::type_complexity)] pub fn remove_value<'k, 'v, 'a>( - self: &'a mut Rc, + self: &'a mut Arc, hashnibbles: &'a mut HashNibbles, store: &'a impl BlockStore, ) -> LocalBoxFuture<'a, Result>>> @@ -498,7 +498,7 @@ where let value_index = self.get_value_index(bit_index); - let node = Rc::make_mut(self); + let node = Arc::make_mut(self); node.persisted_as = OnceCell::new(); Ok(match &mut node.pointers[value_index] { @@ -532,7 +532,7 @@ where } } Pointer::Link(link) => { - let mut child = Rc::clone(link.resolve_value(store).await?); + let mut child = Arc::clone(link.resolve_value(store).await?); let removed = child.remove_value(hashnibbles, store).await?; if removed.is_some() { // If something has been deleted, we attempt to canonicalize the pointer. @@ -560,14 +560,14 @@ where /// # Examples /// /// ``` - /// use std::rc::Rc; + /// use std::sync::Arc; /// use wnfs_hamt::{Node, Pair, Hasher}; /// use wnfs_common::{utils, MemoryBlockStore}; /// /// #[async_std::main] /// async fn main() { /// let store = &MemoryBlockStore::new(); - /// let mut node = Rc::new(Node::<[u8; 4], String>::default()); + /// let mut node = Arc::new(Node::<[u8; 4], String>::default()); /// for i in 0..99_u32 { /// node /// .set(i.to_le_bytes(), i.to_string(), store) @@ -615,7 +615,7 @@ where /// # Examples /// /// ``` - /// use std::rc::Rc; + /// use std::sync::Arc; /// use wnfs_hamt::{Node, HashPrefix, Hasher}; /// use wnfs_common::{MemoryBlockStore, utils}; /// @@ -623,7 +623,7 @@ where /// async fn main() { /// let store = &MemoryBlockStore::new(); /// - /// let mut node = Rc::new(Node::<[u8; 4], String>::default()); + /// let mut node = Arc::new(Node::<[u8; 4], String>::default()); /// for i in 0..100_u32 { /// node /// .set(i.to_le_bytes(), i.to_string(), store) @@ -642,7 +642,7 @@ where &'a self, hashprefix: &HashPrefix, store: &B, - ) -> Result, &'a Rc>>> + ) -> Result, &'a Arc>>> where K: DeserializeOwned + AsRef<[u8]>, V: DeserializeOwned, @@ -657,7 +657,7 @@ where hashprefix: &HashPrefix, index: u8, store: &B, - ) -> Result, &'a Rc>>> + ) -> Result, &'a Arc>>> where K: DeserializeOwned + AsRef<[u8]>, V: DeserializeOwned, @@ -695,7 +695,7 @@ where /// # Examples /// /// ``` - /// use std::rc::Rc; + /// use std::sync::Arc; /// use wnfs_hamt::{Node, Hasher}; /// use wnfs_common::MemoryBlockStore; /// @@ -703,7 +703,7 @@ where /// async fn main() { /// let store = &MemoryBlockStore::new(); /// - /// let mut node = Rc::new(Node::<[u8; 4], String>::default()); + /// let mut node = Arc::new(Node::<[u8; 4], String>::default()); /// for i in 0..100_u32 { /// node /// .set(i.to_le_bytes(), i.to_string(), store) @@ -739,7 +739,7 @@ where impl Node { /// Returns the count of the values in all the values pointer of a node. - pub fn count_values(self: &Rc) -> Result { + pub fn count_values(self: &Arc) -> Result { let mut len = 0; for i in self.pointers.iter() { if let Pointer::Values(values) = i { @@ -933,7 +933,7 @@ mod tests { let store = &MemoryBlockStore::default(); // Insert 4 values to trigger the creation of a linked node. - let working_node = &mut Rc::new(Node::::default()); + let working_node = &mut Arc::new(Node::::default()); for (digest, kv) in HASH_KV_PAIRS.iter().take(4) { let hashnibbles = &mut HashNibbles::new(digest); working_node @@ -956,7 +956,7 @@ mod tests { let store = &MemoryBlockStore::default(); // Insert 4 values to trigger the creation of a linked node. - let working_node = &mut Rc::new(Node::::default()); + let working_node = &mut Arc::new(Node::::default()); for (digest, kv) in HASH_KV_PAIRS.iter().take(4) { let hashnibbles = &mut HashNibbles::new(digest); working_node @@ -995,7 +995,7 @@ mod tests { let store = &MemoryBlockStore::default(); // Insert 3 values into the HAMT. - let working_node = &mut Rc::new(Node::::default()); + let working_node = &mut Arc::new(Node::::default()); for (idx, (digest, kv)) in HASH_KV_PAIRS.iter().take(3).enumerate() { let kv = kv.to_string(); let hashnibbles = &mut HashNibbles::new(digest); @@ -1057,7 +1057,7 @@ mod tests { (&[0xF0], 15), ]; - let working_node = &mut Rc::new(Node::::default()); + let working_node = &mut Arc::new(Node::::default()); for (hash, expected_idx) in hash_expected_idx_samples.into_iter() { let bytes = utils::to_hash_output(&hash[..]); let hashnibbles = &mut HashNibbles::new(&bytes); @@ -1085,7 +1085,7 @@ mod tests { #[async_std::test] async fn node_can_insert_pair_and_retrieve() { let store = MemoryBlockStore::default(); - let node = &mut Rc::new(Node::::default()); + let node = &mut Arc::new(Node::::default()); node.set("pill".into(), (10, 0.315), &store).await.unwrap(); @@ -1101,7 +1101,7 @@ mod tests { let remove_key: String = "hK i3b4V4152EPOdA".into(); let store = &MemoryBlockStore::default(); - let node0: &mut Rc> = &mut Rc::new(Node::default()); + let node0: &mut Arc> = &mut Arc::new(Node::default()); node0.set(insert_key.clone(), 0, store).await.unwrap(); node0.remove(&remove_key, store).await.unwrap(); @@ -1113,8 +1113,8 @@ mod tests { async fn node_history_independence_regression() { let store = &MemoryBlockStore::default(); - let node1: &mut Rc> = &mut Rc::new(Node::default()); - let node2: &mut Rc> = &mut Rc::new(Node::default()); + let node1: &mut Arc> = &mut Arc::new(Node::default()); + let node2: &mut Arc> = &mut Arc::new(Node::default()); node1.set("key 17".into(), 508, store).await.unwrap(); node1.set("key 81".into(), 971, store).await.unwrap(); @@ -1140,7 +1140,7 @@ mod tests { async fn can_map_over_leaf_nodes() { let store = &MemoryBlockStore::default(); - let node = &mut Rc::new(Node::<[u8; 4], String>::default()); + let node = &mut Arc::new(Node::<[u8; 4], String>::default()); for i in 0..99_u32 { node.set(i.to_le_bytes(), i.to_string(), store) .await @@ -1159,7 +1159,7 @@ mod tests { async fn can_fetch_node_at_hashprefix() { let store = &MemoryBlockStore::default(); - let node = &mut Rc::new(Node::::default()); + let node = &mut Arc::new(Node::::default()); for (digest, kv) in HASH_KV_PAIRS.iter() { let hashnibbles = &mut HashNibbles::new(digest); node.set_value(hashnibbles, kv.to_string(), kv.to_string(), store) @@ -1184,7 +1184,7 @@ mod tests { async fn can_generate_hashmap_from_node() { let store = &MemoryBlockStore::default(); - let node = &mut Rc::new(Node::<[u8; 4], String>::default()); + let node = &mut Arc::new(Node::<[u8; 4], String>::default()); const NUM_VALUES: u32 = 1000; for i in (u32::MAX - NUM_VALUES..u32::MAX).rev() { node.set(i.to_le_bytes(), i.to_string(), store) @@ -1344,7 +1344,7 @@ mod snapshot_tests { #[async_std::test] async fn test_node() { let store = &SnapshotBlockStore::default(); - let node = &mut Rc::new(Node::<[u8; 4], String>::default()); + let node = &mut Arc::new(Node::<[u8; 4], String>::default()); for i in 0..99_u32 { node.set(i.to_le_bytes(), i.to_string(), store) .await diff --git a/wnfs-hamt/src/pointer.rs b/wnfs-hamt/src/pointer.rs index f7f74ae5..e547b2e4 100644 --- a/wnfs-hamt/src/pointer.rs +++ b/wnfs-hamt/src/pointer.rs @@ -7,7 +7,7 @@ use serde::{ ser::Error as SerError, Deserialize, Deserializer, Serialize, Serializer, }; -use std::{fmt::Debug, rc::Rc}; +use std::{fmt::Debug, sync::Arc}; use wnfs_common::{utils::error, AsyncSerialize, BlockStore, Link}; //-------------------------------------------------------------------------------------------------- @@ -36,7 +36,7 @@ pub struct Pair { /// A `Pointer` can be either a link to a child node or a collection of key-value pairs. pub(crate) enum Pointer { Values(Vec>), - Link(Link>>), + Link(Link>>), } //-------------------------------------------------------------------------------------------------- diff --git a/wnfs-hamt/src/strategies/changes.rs b/wnfs-hamt/src/strategies/changes.rs index ea4a3eea..3fb0eb94 100644 --- a/wnfs-hamt/src/strategies/changes.rs +++ b/wnfs-hamt/src/strategies/changes.rs @@ -4,7 +4,7 @@ use crate::Node; use anyhow::Result; use proptest::{collection::vec, strategy::Strategy}; use serde::de::DeserializeOwned; -use std::{collections::HashMap, fmt::Debug, rc::Rc}; +use std::{collections::HashMap, fmt::Debug, sync::Arc}; use wnfs_common::BlockStore; //-------------------------------------------------------------------------------------------------- @@ -53,7 +53,7 @@ pub(crate) fn generate_ops_and_changes( } pub(crate) async fn apply_changes( - node: &mut Rc>, + node: &mut Arc>, changes: &Vec>, store: &impl BlockStore, ) -> Result<()> @@ -79,7 +79,7 @@ where } pub(crate) async fn prepare_node( - node: &mut Rc>, + node: &mut Arc>, changes: &Vec>, store: &B, ) -> Result<()> diff --git a/wnfs-hamt/src/strategies/kv.rs b/wnfs-hamt/src/strategies/kv.rs index 78a56f2a..cb8cc077 100644 --- a/wnfs-hamt/src/strategies/kv.rs +++ b/wnfs-hamt/src/strategies/kv.rs @@ -2,7 +2,7 @@ use crate::Node; use anyhow::Result; use proptest::{collection::vec, sample::SizeRange, strategy::Strategy}; use serde::{de::DeserializeOwned, Serialize}; -use std::{collections::HashMap, fmt::Debug, hash::Hash, rc::Rc}; +use std::{collections::HashMap, fmt::Debug, hash::Hash, sync::Arc}; use wnfs_common::BlockStore; //-------------------------------------------------------------------------------------------------- @@ -28,12 +28,12 @@ where pub async fn node_from_kvs( pairs: Vec<(K, V)>, store: &impl BlockStore, -) -> Result>> +) -> Result>> where K: DeserializeOwned + Serialize + Clone + Debug + AsRef<[u8]>, V: DeserializeOwned + Serialize + Clone + Debug, { - let mut node: Rc> = Rc::new(Node::default()); + let mut node: Arc> = Arc::new(Node::default()); for (k, v) in pairs { node.set(k, v, store).await?; } diff --git a/wnfs-hamt/src/strategies/operations.rs b/wnfs-hamt/src/strategies/operations.rs index e4aeafd5..6046b386 100644 --- a/wnfs-hamt/src/strategies/operations.rs +++ b/wnfs-hamt/src/strategies/operations.rs @@ -2,7 +2,7 @@ use crate::Node; use anyhow::Result; use proptest::{collection::*, prelude::*, strategy::Shuffleable}; use serde::{de::DeserializeOwned, Serialize}; -use std::{collections::HashMap, fmt::Debug, hash::Hash, rc::Rc}; +use std::{collections::HashMap, fmt::Debug, hash::Hash, sync::Arc}; use wnfs_common::BlockStore; //-------------------------------------------------------------------------------------------------- @@ -183,12 +183,12 @@ where pub async fn node_from_operations( operations: &Operations, store: &impl BlockStore, -) -> Result>> +) -> Result>> where K: DeserializeOwned + Serialize + Clone + Debug + AsRef<[u8]>, V: DeserializeOwned + Serialize + Clone + Debug, { - let mut node: Rc> = Rc::new(Node::default()); + let mut node: Arc> = Arc::new(Node::default()); for op in &operations.0 { match op { Operation::Insert(key, value) => { @@ -199,7 +199,7 @@ where } Operation::Reserialize => { let cid = store.put_async_serializable(node.as_ref()).await?; - node = Rc::new(store.get_deserializable(&cid).await?); + node = Arc::new(store.get_deserializable(&cid).await?); } }; } diff --git a/wnfs/examples/mnemonic_based.rs b/wnfs/examples/mnemonic_based.rs index 66b7af08..3d05c8ef 100644 --- a/wnfs/examples/mnemonic_based.rs +++ b/wnfs/examples/mnemonic_based.rs @@ -7,7 +7,7 @@ use rand_chacha::ChaCha12Rng; use rand_core::SeedableRng; use rsa::{traits::PublicKeyParts, BigUint, Oaep, RsaPrivateKey, RsaPublicKey}; use sha2::Sha256; -use std::rc::Rc; +use std::sync::Arc; use wnfs::{ common::{BlockStore, MemoryBlockStore, CODEC_RAW}, private::{ @@ -54,7 +54,7 @@ async fn main() -> Result<()> { Ok(()) } -async fn root_dir_setup(store: &impl BlockStore) -> Result<(Rc, AccessKey)> { +async fn root_dir_setup(store: &impl BlockStore) -> Result<(Arc, AccessKey)> { // We generate a new simple example file system: let rng = &mut rand::thread_rng(); let forest = &mut HamtForest::new_trusted_rc(rng); @@ -77,11 +77,11 @@ async fn root_dir_setup(store: &impl BlockStore) -> Result<(Rc, Acce // And finally we return the forest and the root directory's access key let access_key = root_dir.as_node().store(forest, store, rng).await?; - Ok((Rc::clone(forest), access_key)) + Ok((Arc::clone(forest), access_key)) } async fn setup_seeded_keypair_access( - forest: &mut Rc, + forest: &mut Arc, access_key: AccessKey, store: &impl BlockStore, ) -> Result { diff --git a/wnfs/src/private/directory.rs b/wnfs/src/private/directory.rs index 2e7d663c..a0f7ab73 100644 --- a/wnfs/src/private/directory.rs +++ b/wnfs/src/private/directory.rs @@ -12,7 +12,7 @@ use rand_core::CryptoRngCore; use std::{ collections::{BTreeMap, BTreeSet}, fmt::Debug, - rc::Rc, + sync::Arc, }; use wnfs_common::{utils::error, BlockStore, Metadata, PathNodes, PathNodesResult, CODEC_RAW}; use wnfs_nameaccumulator::{Name, NameSegment}; @@ -89,7 +89,7 @@ impl PrivateDirectory { } } - /// Creates a `PrivateDirectory` with provided details and wraps it in an `Rc`. + /// Creates a `PrivateDirectory` with provided details and wraps it in an `Arc`. /// /// # Examples /// @@ -112,8 +112,8 @@ impl PrivateDirectory { parent_name: &Name, time: DateTime, rng: &mut impl CryptoRngCore, - ) -> Rc { - Rc::new(Self::new(parent_name, time, rng)) + ) -> Arc { + Arc::new(Self::new(parent_name, time, rng)) } /// This contstructor creates a new private directory and stores it in a provided `PrivateForest`. @@ -123,8 +123,8 @@ impl PrivateDirectory { forest: &mut impl PrivateForest, store: &impl BlockStore, rng: &mut impl CryptoRngCore, - ) -> Result> { - let dir = Rc::new(Self::new(parent_name, time, rng)); + ) -> Result> { + let dir = Arc::new(Self::new(parent_name, time, rng)); dir.store(forest, store, rng).await?; Ok(dir) } @@ -133,7 +133,7 @@ impl PrivateDirectory { /// /// Supports cases where the entire path does not exist. pub(crate) async fn get_path_nodes( - self: Rc, + self: Arc, path_segments: &[String], search_latest: bool, forest: &impl PrivateForest, @@ -149,13 +149,13 @@ impl PrivateDirectory { .await? { Some(PrivateNode::Dir(ref directory)) => { - path_nodes.push((Rc::clone(&working_node), path_segment.clone())); - working_node = Rc::clone(directory); + path_nodes.push((Arc::clone(&working_node), path_segment.clone())); + working_node = Arc::clone(directory); } Some(_) => { let path_nodes = PrivatePathNodes { path: path_nodes, - tail: Rc::clone(&working_node), + tail: Arc::clone(&working_node), }; return Ok(NotADirectory(path_nodes, path_segment.clone())); @@ -163,7 +163,7 @@ impl PrivateDirectory { None => { let path_nodes = PrivatePathNodes { path: path_nodes, - tail: Rc::clone(&working_node), + tail: Arc::clone(&working_node), }; return Ok(MissingLink(path_nodes, path_segment.clone())); @@ -173,7 +173,7 @@ impl PrivateDirectory { Ok(Complete(PrivatePathNodes { path: path_nodes, - tail: Rc::clone(&working_node), + tail: Arc::clone(&working_node), })) } @@ -201,7 +201,7 @@ impl PrivateDirectory { /// assert_eq!(dir.get_metadata(), &Metadata::new(time)); /// ``` #[inline] - pub fn get_metadata<'a>(self: &'a Rc) -> &'a Metadata { + pub fn get_metadata<'a>(self: &'a Arc) -> &'a Metadata { &self.content.metadata } @@ -282,13 +282,13 @@ impl PrivateDirectory { } pub(crate) async fn get_leaf_dir( - self: &Rc, + self: &Arc, path_segments: &[String], search_latest: bool, forest: &impl PrivateForest, store: &impl BlockStore, - ) -> Result>> { - let mut working_dir = Rc::clone(self); + ) -> Result>> { + let mut working_dir = Arc::clone(self); if search_latest { working_dir = working_dir.search_latest(forest, store).await?; @@ -300,7 +300,7 @@ impl PrivateDirectory { .await? { Some(PrivateNode::Dir(directory)) => { - working_dir = Rc::clone(&directory); + working_dir = Arc::clone(&directory); } Some(_) => return Ok(SearchResult::NotADir(working_dir, depth)), None => return Ok(SearchResult::Missing(working_dir, depth)), @@ -311,7 +311,7 @@ impl PrivateDirectory { } pub(crate) async fn get_leaf_dir_mut<'a>( - self: &'a mut Rc, + self: &'a mut Arc, path_segments: &[String], search_latest: bool, forest: &impl PrivateForest, @@ -350,7 +350,7 @@ impl PrivateDirectory { #[allow(clippy::suspicious)] pub(crate) async fn get_or_create_leaf_dir_mut<'a>( - self: &'a mut Rc, + self: &'a mut Arc, path_segments: &[String], time: DateTime, search_latest: bool, @@ -365,7 +365,7 @@ impl PrivateDirectory { SearchResult::Found(dir) => Ok(dir), SearchResult::Missing(mut dir, depth) => { for segment in &path_segments[depth..] { - dir = Rc::make_mut( + dir = Arc::make_mut( dir.content .entries .entry(segment.to_string()) @@ -392,16 +392,16 @@ impl PrivateDirectory { /// This doesn't have any effect if the current state hasn't been `.store()`ed yet. /// Otherwise, it clones itself, stores its current CID in the previous links and /// advances its ratchet. - pub(crate) fn prepare_next_revision<'a>(self: &'a mut Rc) -> Result<&'a mut Self> { + pub(crate) fn prepare_next_revision<'a>(self: &'a mut Arc) -> Result<&'a mut Self> { let Some(previous_cid) = self.content.persisted_as.get().cloned() else { // The current revision wasn't written yet. // There's no point in advancing the revision even further. - return Ok(Rc::make_mut(self)); + return Ok(Arc::make_mut(self)); }; let temporal_key = self.header.derive_temporal_key(); let previous_link = (1, Encrypted::from_value(previous_cid, &temporal_key)?); - let cloned = Rc::make_mut(self); + let cloned = Arc::make_mut(self); // We make sure to clear any cached states. cloned.content.persisted_as = OnceCell::new(); @@ -468,7 +468,7 @@ impl PrivateDirectory { /// } /// ``` pub async fn get_node( - self: &Rc, + self: &Arc, path_segments: &[String], search_latest: bool, forest: &impl PrivateForest, @@ -532,7 +532,7 @@ impl PrivateDirectory { /// } /// ``` pub async fn read( - self: &Rc, + self: &Arc, path_segments: &[String], search_latest: bool, forest: &impl PrivateForest, @@ -614,7 +614,7 @@ impl PrivateDirectory { /// ``` #[allow(clippy::suspicious)] pub async fn open_file_mut<'a>( - self: &'a mut Rc, + self: &'a mut Arc, path_segments: &[String], search_latest: bool, time: DateTime, @@ -688,7 +688,7 @@ impl PrivateDirectory { /// ``` #[allow(clippy::too_many_arguments)] pub async fn write( - self: &mut Rc, + self: &mut Arc, path_segments: &[String], search_latest: bool, time: DateTime, @@ -732,7 +732,7 @@ impl PrivateDirectory { /// # Examples /// /// ``` - /// use std::rc::Rc; + /// use std::sync::Arc; /// use anyhow::Result; /// use chrono::Utc; /// use rand::thread_rng; @@ -757,7 +757,7 @@ impl PrivateDirectory { /// rng /// ).await?; /// - /// let dir_clone = &mut Rc::clone(&init_dir); + /// let dir_clone = &mut Arc::clone(&init_dir); /// /// dir_clone /// .mkdir(&["pictures".into(), "cats".into()], true, Utc::now(), forest, store, rng) @@ -776,10 +776,10 @@ impl PrivateDirectory { /// ``` #[inline] pub async fn search_latest( - self: Rc, + self: Arc, forest: &impl PrivateForest, store: &impl BlockStore, - ) -> Result> { + ) -> Result> { PrivateNode::Dir(self) .search_latest(forest, store) .await? @@ -823,7 +823,7 @@ impl PrivateDirectory { /// } /// ``` pub async fn mkdir( - self: &mut Rc, + self: &mut Arc, path_segments: &[String], search_latest: bool, time: DateTime, @@ -886,7 +886,7 @@ impl PrivateDirectory { /// } /// ``` pub async fn ls( - self: &Rc, + self: &Arc, path_segments: &[String], search_latest: bool, forest: &impl PrivateForest, @@ -922,7 +922,7 @@ impl PrivateDirectory { /// /// Other than [PrivateDirectory::ls] this returns only the names, without loading the /// metadata for each node from the store. - pub fn get_entries<'a>(self: &'a Rc) -> impl Iterator { + pub fn get_entries<'a>(self: &'a Arc) -> impl Iterator { self.content.entries.iter().map(|x| x.0) } @@ -982,7 +982,7 @@ impl PrivateDirectory { /// } /// ``` pub async fn rm( - self: &mut Rc, + self: &mut Arc, path_segments: &[String], search_latest: bool, forest: &impl PrivateForest, @@ -1012,7 +1012,7 @@ impl PrivateDirectory { /// Fixes up the subtree bare names to refer to the new parent. #[allow(clippy::too_many_arguments)] async fn attach( - self: &mut Rc, + self: &mut Arc, mut node: PrivateNode, path_segments: &[String], search_latest: bool, @@ -1104,7 +1104,7 @@ impl PrivateDirectory { /// ``` #[allow(clippy::too_many_arguments)] pub async fn basic_mv( - self: &mut Rc, + self: &mut Arc, path_segments_from: &[String], path_segments_to: &[String], search_latest: bool, @@ -1189,7 +1189,7 @@ impl PrivateDirectory { /// ``` #[allow(clippy::too_many_arguments)] pub async fn cp( - self: &mut Rc, + self: &mut Arc, path_segments_from: &[String], path_segments_to: &[String], search_latest: bool, @@ -1279,8 +1279,8 @@ impl PrivateDirectory { } /// Wraps the directory in a [`PrivateNode`]. - pub fn as_node(self: &Rc) -> PrivateNode { - PrivateNode::Dir(Rc::clone(self)) + pub fn as_node(self: &Arc) -> PrivateNode { + PrivateNode::Dir(Arc::clone(self)) } } @@ -1710,7 +1710,7 @@ mod tests { root_dir.store(forest, store, rng).await.unwrap(); - let old_root = &Rc::clone(root_dir); + let old_root = &Arc::clone(root_dir); root_dir .write(&path, true, Utc::now(), b"Two".to_vec(), forest, store, rng) @@ -1721,7 +1721,7 @@ mod tests { let new_read = root_dir.read(&path, false, forest, store).await.unwrap(); - let old_read = Rc::clone(old_root) + let old_read = Arc::clone(old_root) .read(&path, false, forest, store) .await .unwrap(); @@ -2068,7 +2068,7 @@ mod tests { let forest = &mut HamtForest::new_rsa_2048_rc(rng); let old_dir = &mut PrivateDirectory::new_rc(&forest.empty_name(), Utc::now(), rng); - let new_dir = &mut Rc::clone(old_dir); + let new_dir = &mut Arc::clone(old_dir); new_dir .write( &["file.txt".into()], @@ -2094,7 +2094,7 @@ mod tests { let old_dir = &mut PrivateDirectory::new_rc(&forest.empty_name(), Utc::now(), rng); old_dir.store(forest, store, rng).await.unwrap(); - let new_dir = &mut Rc::clone(old_dir); + let new_dir = &mut Arc::clone(old_dir); new_dir .write( &["file.txt".into()], @@ -2124,7 +2124,7 @@ mod tests { let path = &["some".into(), "test.txt".into()]; let content = b"Hello"; - let dir = &mut Rc::clone(&old_dir); + let dir = &mut Arc::clone(&old_dir); dir.write(path, true, Utc::now(), content.to_vec(), forest, store, rng) .await?; dir.as_node().store(forest, store, rng).await?; diff --git a/wnfs/src/private/file.rs b/wnfs/src/private/file.rs index 606bc5f1..fa5a46d8 100644 --- a/wnfs/src/private/file.rs +++ b/wnfs/src/private/file.rs @@ -16,7 +16,7 @@ use libipld_core::{ }; use rand_core::CryptoRngCore; use serde::{Deserialize, Serialize}; -use std::{collections::BTreeSet, iter, rc::Rc}; +use std::{collections::BTreeSet, iter, sync::Arc}; use wnfs_common::{utils, BlockStore, Metadata, CODEC_RAW, MAX_BLOCK_SIZE}; use wnfs_nameaccumulator::{Name, NameAccumulator, NameSegment}; @@ -144,7 +144,7 @@ impl PrivateFile { } } - /// Creates an empty file wrapped in an `Rc`. + /// Creates an empty file wrapped in an `Arc`. /// /// # Examples /// @@ -165,8 +165,8 @@ impl PrivateFile { parent_name: &Name, time: DateTime, rng: &mut impl CryptoRngCore, - ) -> Rc { - Rc::new(Self::new(parent_name, time, rng)) + ) -> Arc { + Arc::new(Self::new(parent_name, time, rng)) } /// Creates a file with provided content. @@ -223,7 +223,7 @@ impl PrivateFile { }) } - /// Creates a file with provided content wrapped in an `Rc`. + /// Creates a file with provided content wrapped in an `Arc`. /// /// # Examples /// @@ -262,8 +262,8 @@ impl PrivateFile { forest: &mut impl PrivateForest, store: &impl BlockStore, rng: &mut impl CryptoRngCore, - ) -> Result> { - Ok(Rc::new( + ) -> Result> { + Ok(Arc::new( Self::with_content(parent_name, time, content, forest, store, rng).await?, )) } @@ -331,7 +331,7 @@ impl PrivateFile { }) } - /// Creates a file with provided content as a stream wrapped in an `Rc`. + /// Creates a file with provided content as a stream wrapped in an `Arc`. /// /// # Examples /// @@ -375,8 +375,8 @@ impl PrivateFile { forest: &mut impl PrivateForest, store: &impl BlockStore, rng: &mut impl CryptoRngCore, - ) -> Result> { - Ok(Rc::new( + ) -> Result> { + Ok(Arc::new( Self::with_content_streaming(parent_name, time, content, forest, store, rng).await?, )) } @@ -517,7 +517,7 @@ impl PrivateFile { } /// Returns a mutable reference to this file's metadata and ratchets forward its revision, if necessary. - pub fn get_metadata_mut_rc<'a>(self: &'a mut Rc) -> Result<&'a mut Metadata> { + pub fn get_metadata_mut_rc<'a>(self: &'a mut Arc) -> Result<&'a mut Metadata> { Ok(self.prepare_next_revision()?.get_metadata_mut()) } @@ -622,19 +622,19 @@ impl PrivateFile { /// This doesn't have any effect if the current state hasn't been `.store()`ed yet. /// Otherwise, it clones itself, stores its current CID in the previous links and /// advances its ratchet. - pub(crate) fn prepare_next_revision<'a>(self: &'a mut Rc) -> Result<&'a mut Self> { + pub(crate) fn prepare_next_revision<'a>(self: &'a mut Arc) -> Result<&'a mut Self> { let previous_cid = match self.content.persisted_as.get() { Some(cid) => *cid, None => { // The current revision wasn't written yet. // There's no point in advancing the revision even further. - return Ok(Rc::make_mut(self)); + return Ok(Arc::make_mut(self)); } }; let temporal_key = self.header.derive_temporal_key(); let previous_link = (1, Encrypted::from_value(previous_cid, &temporal_key)?); - let cloned = Rc::make_mut(self); + let cloned = Arc::make_mut(self); // We make sure to clear any cached states. cloned.content.persisted_as = OnceCell::new(); @@ -724,8 +724,8 @@ impl PrivateFile { } /// Wraps the file in a [`PrivateNode`]. - pub fn as_node(self: &Rc) -> PrivateNode { - PrivateNode::File(Rc::clone(self)) + pub fn as_node(self: &Arc) -> PrivateNode { + PrivateNode::File(Arc::clone(self)) } } diff --git a/wnfs/src/private/forest/hamt.rs b/wnfs/src/private/forest/hamt.rs index df80b09f..8598555a 100644 --- a/wnfs/src/private/forest/hamt.rs +++ b/wnfs/src/private/forest/hamt.rs @@ -8,7 +8,7 @@ use rand_core::CryptoRngCore; use serde::{ de::Error as DeError, ser::Error as SerError, Deserialize, Deserializer, Serialize, Serializer, }; -use std::{collections::BTreeSet, rc::Rc}; +use std::{collections::BTreeSet, sync::Arc}; use wnfs_common::{AsyncSerialize, BlockStore, HashOutput, Link}; use wnfs_hamt::{merge, Hamt, Hasher, KeyValueChange, Pair}; use wnfs_nameaccumulator::{AccumulatorSetup, ElementsProof, Name, NameAccumulator}; @@ -43,7 +43,7 @@ const NAME_CACHE_CAPACITY: usize = 2_000_000 / APPROX_CACHE_ENTRY_SIZE; pub struct HamtForest { hamt: Hamt, blake3::Hasher>, accumulator: AccumulatorSetup, - name_cache: Rc>, + name_cache: Arc>, } //-------------------------------------------------------------------------------------------------- @@ -56,13 +56,13 @@ impl HamtForest { Self { hamt: Hamt::new(), accumulator: setup, - name_cache: Rc::new(Cache::new(NAME_CACHE_CAPACITY)), + name_cache: Arc::new(Cache::new(NAME_CACHE_CAPACITY)), } } - /// Create a new, empty hamt forest with given pre-run accumulator setup wrapped in an `Rc`. - pub fn new_rc(setup: AccumulatorSetup) -> Rc { - Rc::new(Self::new(setup)) + /// Create a new, empty hamt forest with given pre-run accumulator setup wrapped in an `Arc`. + pub fn new_rc(setup: AccumulatorSetup) -> Arc { + Arc::new(Self::new(setup)) } /// Create a new, empty hamt forest with an accumulator setup with its @@ -75,10 +75,10 @@ impl HamtForest { Self::new(AccumulatorSetup::from_rsa_2048(rng)) } - /// Creates an `Rc` of a new, empty hamt forest with an accumulator setup + /// Creates an `Arc` of a new, empty hamt forest with an accumulator setup /// based on the factors of the RSA-2048 factoring challenge modulus. - pub fn new_rsa_2048_rc(rng: &mut impl CryptoRngCore) -> Rc { - Rc::new(Self::new_rsa_2048(rng)) + pub fn new_rsa_2048_rc(rng: &mut impl CryptoRngCore) -> Arc { + Arc::new(Self::new_rsa_2048(rng)) } /// Create a new, empty hamt forest with and run a trusted accumulator @@ -98,10 +98,10 @@ impl HamtForest { Self::new(AccumulatorSetup::trusted(rng)) } - /// Creates an `Rc` of a new, empty hamt forest with a trusted accumulator + /// Creates an `Arc` of a new, empty hamt forest with a trusted accumulator /// setup. - pub fn new_trusted_rc(rng: &mut impl CryptoRngCore) -> Rc { - Rc::new(Self::new_trusted(rng)) + pub fn new_trusted_rc(rng: &mut impl CryptoRngCore) -> Arc { + Arc::new(Self::new_trusted(rng)) } /// Gets the difference in changes between two forests. @@ -217,7 +217,7 @@ impl PrivateForest for HamtForest { } #[async_trait(?Send)] -impl PrivateForest for Rc { +impl PrivateForest for Arc { fn empty_name(&self) -> Name { (**self).empty_name() } @@ -244,7 +244,7 @@ impl PrivateForest for Rc { values: impl IntoIterator, store: &impl BlockStore, ) -> Result { - Rc::make_mut(self).put_encrypted(name, values, store).await + Arc::make_mut(self).put_encrypted(name, values, store).await } async fn get_encrypted_by_hash<'b>( @@ -268,7 +268,7 @@ impl PrivateForest for Rc { name: &Name, store: &impl BlockStore, ) -> Result>>> { - Rc::make_mut(self).remove_encrypted(name, store).await + Arc::make_mut(self).remove_encrypted(name, store).await } } @@ -279,7 +279,7 @@ impl HamtForest { /// # Examples /// /// ``` - /// use std::rc::Rc; + /// use std::sync::Arc; /// use anyhow::Result; /// use chrono::Utc; /// use rand::thread_rng; @@ -308,13 +308,13 @@ impl HamtForest { /// root_dir.as_node().store(forest, store, rng).await?; /// /// // Make two conflicting writes - /// let forest_one = &mut Rc::clone(forest); - /// let dir_one = &mut Rc::clone(root_dir); + /// let forest_one = &mut Arc::clone(forest); + /// let dir_one = &mut Arc::clone(root_dir); /// dir_one.mkdir(&["DirOne".into()], true, Utc::now(), forest_one, store, rng).await?; /// dir_one.as_node().store(forest_one, store, rng).await?; /// - /// let forest_two = &mut Rc::clone(forest); - /// let dir_two = &mut Rc::clone(root_dir); + /// let forest_two = &mut Arc::clone(forest); + /// let dir_two = &mut Arc::clone(root_dir); /// dir_two.mkdir(&["DirTwo".into()], true, Utc::now(), forest_two, store, rng).await?; /// let access_key = dir_two.as_node().store(forest_two, store, rng).await?; /// let label = access_key.get_label(); @@ -343,8 +343,8 @@ impl HamtForest { } let merged_root = merge( - Link::from(Rc::clone(&self.hamt.root)), - Link::from(Rc::clone(&other.hamt.root)), + Link::from(Arc::clone(&self.hamt.root)), + Link::from(Arc::clone(&other.hamt.root)), |a, b| Ok(a.union(b).cloned().collect()), store, ) @@ -415,7 +415,7 @@ impl<'de> Deserialize<'de> for HamtForest { Ok(Self { hamt, accumulator, - name_cache: Rc::new(Cache::new(NAME_CACHE_CAPACITY)), + name_cache: Arc::new(Cache::new(NAME_CACHE_CAPACITY)), }) } } @@ -431,7 +431,7 @@ mod tests { use chrono::Utc; use rand_chacha::ChaCha12Rng; use rand_core::SeedableRng; - use std::rc::Rc; + use std::sync::Arc; use wnfs_common::MemoryBlockStore; use wnfs_nameaccumulator::NameSegment; @@ -479,7 +479,7 @@ mod tests { let dir_conflict = { let mut dir = (*dir).clone(); dir.content.metadata.upsert_mtime(Utc::now()); - Rc::new(dir) + Arc::new(dir) }; let private_node = PrivateNode::Dir(dir.clone()); diff --git a/wnfs/src/private/link.rs b/wnfs/src/private/link.rs index 538c08a7..1160f8aa 100644 --- a/wnfs/src/private/link.rs +++ b/wnfs/src/private/link.rs @@ -5,7 +5,7 @@ use anyhow::Result; use async_once_cell::OnceCell; use async_recursion::async_recursion; use rand_core::CryptoRngCore; -use std::rc::Rc; +use std::sync::Arc; use wnfs_common::BlockStore; use wnfs_nameaccumulator::Name; @@ -126,13 +126,13 @@ impl PrivateLink { /// Creates a link to a directory node. #[inline] pub(crate) fn with_dir(dir: PrivateDirectory) -> Self { - Self::from(PrivateNode::Dir(Rc::new(dir))) + Self::from(PrivateNode::Dir(Arc::new(dir))) } /// Creates a link to a file node. #[inline] pub(crate) fn with_file(file: PrivateFile) -> Self { - Self::from(PrivateNode::File(Rc::new(file))) + Self::from(PrivateNode::File(Arc::new(file))) } } diff --git a/wnfs/src/private/node/node.rs b/wnfs/src/private/node/node.rs index 5a1d9fa2..ed32909f 100644 --- a/wnfs/src/private/node/node.rs +++ b/wnfs/src/private/node/node.rs @@ -15,7 +15,7 @@ use futures::StreamExt; use libipld_core::cid::Cid; use rand_core::CryptoRngCore; use skip_ratchet::{JumpSize, RatchetSeeker}; -use std::{cmp::Ordering, collections::BTreeSet, fmt::Debug, rc::Rc}; +use std::{cmp::Ordering, collections::BTreeSet, fmt::Debug, sync::Arc}; use wnfs_common::BlockStore; use wnfs_hamt::Hasher; use wnfs_nameaccumulator::Name; @@ -45,8 +45,8 @@ use wnfs_nameaccumulator::Name; /// ``` #[derive(Debug, Clone, PartialEq)] pub enum PrivateNode { - File(Rc), - Dir(Rc), + File(Arc), + Dir(Arc), } //-------------------------------------------------------------------------------------------------- @@ -90,12 +90,12 @@ impl PrivateNode { Self::File(file) => { let mut file = (**file).clone(); file.content.metadata.upsert_mtime(time); - Self::File(Rc::new(file)) + Self::File(Arc::new(file)) } Self::Dir(dir) => { let mut dir = (**dir).clone(); dir.content.metadata.upsert_mtime(time); - Self::Dir(Rc::new(dir)) + Self::Dir(Arc::new(dir)) } } } @@ -111,11 +111,11 @@ impl PrivateNode { ) -> Result<()> { match self { Self::File(file_rc) => { - let file = Rc::make_mut(file_rc); + let file = Arc::make_mut(file_rc); file.prepare_key_rotation(parent_name, rng).await?; } Self::Dir(dir_rc) => { - let dir = Rc::make_mut(dir_rc); + let dir = Arc::make_mut(dir_rc); for private_link in &mut dir.content.entries.values_mut() { let mut node = private_link @@ -138,7 +138,7 @@ impl PrivateNode { /// # Examples /// /// ``` - /// use std::rc::Rc; + /// use std::sync::Arc; /// use wnfs::{ /// private::{ /// PrivateDirectory, PrivateNode, @@ -151,7 +151,7 @@ impl PrivateNode { /// let rng = &mut thread_rng(); /// let forest = &mut HamtForest::new_rsa_2048_rc(rng); /// let dir = PrivateDirectory::new_rc(&forest.empty_name(), Utc::now(), rng); - /// let node = PrivateNode::Dir(Rc::clone(&dir)); + /// let node = PrivateNode::Dir(Arc::clone(&dir)); /// /// assert_eq!(&dir.header, node.get_header()); /// ``` @@ -193,7 +193,7 @@ impl PrivateNode { /// # Examples /// /// ``` - /// use std::rc::Rc; + /// use std::sync::Arc; /// use wnfs::{ /// private::{ /// PrivateDirectory, PrivateNode, @@ -206,19 +206,19 @@ impl PrivateNode { /// let rng = &mut thread_rng(); /// let forest = &mut HamtForest::new_rsa_2048_rc(rng); /// let dir = PrivateDirectory::new_rc(&forest.empty_name(), Utc::now(), rng); - /// let node = PrivateNode::Dir(Rc::clone(&dir)); + /// let node = PrivateNode::Dir(Arc::clone(&dir)); /// /// assert_eq!(node.as_dir().unwrap(), dir); /// ``` - pub fn as_dir(&self) -> Result> { + pub fn as_dir(&self) -> Result> { Ok(match self { - Self::Dir(dir) => Rc::clone(dir), + Self::Dir(dir) => Arc::clone(dir), _ => bail!(FsError::NotADirectory), }) } /// Casts a node to a mutable directory. - pub fn as_dir_mut(&mut self) -> Result<&mut Rc> { + pub fn as_dir_mut(&mut self) -> Result<&mut Arc> { Ok(match self { Self::Dir(dir) => dir, _ => bail!(FsError::NotADirectory), @@ -230,7 +230,7 @@ impl PrivateNode { /// # Examples /// /// ``` - /// use std::rc::Rc; + /// use std::sync::Arc; /// use wnfs::{ /// private::{ /// PrivateFile, PrivateNode, @@ -243,13 +243,13 @@ impl PrivateNode { /// let rng = &mut thread_rng(); /// let forest = &mut HamtForest::new_rsa_2048_rc(rng); /// let file = PrivateFile::new_rc(&forest.empty_name(), Utc::now(), rng); - /// let node = PrivateNode::File(Rc::clone(&file)); + /// let node = PrivateNode::File(Arc::clone(&file)); /// /// assert_eq!(node.as_file().unwrap(), file); /// ``` - pub fn as_file(&self) -> Result> { + pub fn as_file(&self) -> Result> { Ok(match self { - Self::File(file) => Rc::clone(file), + Self::File(file) => Arc::clone(file), _ => bail!(FsError::NotAFile), }) } @@ -309,7 +309,7 @@ impl PrivateNode { /// # Examples /// /// ``` - /// use std::rc::Rc; + /// use std::sync::Arc; /// use chrono::Utc; /// use rand::thread_rng; /// use wnfs::{ @@ -334,7 +334,7 @@ impl PrivateNode { /// rng /// ).await.unwrap(); /// - /// let dir_clone = &mut Rc::clone(&init_dir); + /// let dir_clone = &mut Arc::clone(&init_dir); /// /// dir_clone /// .mkdir(&["pictures".into(), "cats".into()], true, Utc::now(), forest, store, rng) @@ -472,7 +472,7 @@ impl PrivateNode { parent_name, ) .await?; - PrivateNode::File(Rc::new(file)) + PrivateNode::File(Arc::new(file)) } PrivateNodeContentSerializable::Dir(dir) => { let dir = PrivateDirectory::from_serializable( @@ -484,7 +484,7 @@ impl PrivateNode { parent_name, ) .await?; - PrivateNode::Dir(Rc::new(dir)) + PrivateNode::Dir(Arc::new(dir)) } }) } @@ -584,13 +584,13 @@ impl Id for PrivateNode { impl From for PrivateNode { fn from(file: PrivateFile) -> Self { - Self::File(Rc::new(file)) + Self::File(Arc::new(file)) } } impl From for PrivateNode { fn from(dir: PrivateDirectory) -> Self { - Self::Dir(Rc::new(dir)) + Self::Dir(Arc::new(dir)) } } @@ -629,8 +629,8 @@ mod tests { .await .unwrap(); - let file_node = PrivateNode::File(Rc::new(file)); - let dir_node = PrivateNode::Dir(Rc::clone(&directory)); + let file_node = PrivateNode::File(Arc::new(file)); + let dir_node = PrivateNode::Dir(Arc::clone(&directory)); let file_private_ref = file_node.store(forest, store, rng).await.unwrap(); let dir_private_ref = dir_node.store(forest, store, rng).await.unwrap(); diff --git a/wnfs/src/private/previous.rs b/wnfs/src/private/previous.rs index d252d2f1..4f56bd7f 100644 --- a/wnfs/src/private/previous.rs +++ b/wnfs/src/private/previous.rs @@ -6,7 +6,7 @@ use crate::error::FsError; use anyhow::{bail, Result}; use libipld_core::cid::Cid; use skip_ratchet::{PreviousIterator, Ratchet}; -use std::{collections::BTreeSet, rc::Rc}; +use std::{collections::BTreeSet, sync::Arc}; use wnfs_common::{BlockStore, PathNodes, PathNodesResult}; //-------------------------------------------------------------------------------------------------- @@ -30,7 +30,7 @@ pub struct PrivateNodeOnPathHistory { struct PathSegmentHistory { /// The directory that the history was originally created relative to. - dir: Rc, + dir: Arc, /// The history of said directory. history: PrivateNodeHistory, /// The name of the child node to follow for history next. @@ -158,7 +158,7 @@ impl PrivateNodeHistory { pub async fn get_previous_dir( &mut self, store: &impl BlockStore, - ) -> Result>> { + ) -> Result>> { match self.get_previous_node(store).await? { Some(PrivateNode::Dir(dir)) => Ok(Some(dir)), Some(_) => Err(FsError::NotADirectory.into()), @@ -174,7 +174,7 @@ impl PrivateNodeHistory { pub async fn get_previous_file( &mut self, store: &impl BlockStore, - ) -> Result>> { + ) -> Result>> { match self.get_previous_node(store).await? { Some(PrivateNode::File(file)) => Ok(Some(file)), Some(_) => Err(FsError::NotAFile.into()), @@ -195,8 +195,8 @@ impl PrivateNodeOnPathHistory { /// down to the child, and then look for the latest revision of the target node, /// including all in-between versions in the history. pub async fn of( - directory: Rc, - past_directory: Rc, + directory: Arc, + past_directory: Arc, discrepancy_budget: usize, path_segments: &[String], search_latest: bool, @@ -229,7 +229,7 @@ impl PrivateNodeOnPathHistory { }; let (path, target_history) = Self::path_nodes_and_target_history( - Rc::clone(&directory), + Arc::clone(&directory), discrepancy_budget, path_segments, target_path, @@ -267,14 +267,14 @@ impl PrivateNodeOnPathHistory { /// /// If `search_latest` is false, the target history is empty. async fn path_nodes_and_target_history( - dir: Rc, + dir: Arc, discrepancy_budget: usize, path_segments: &[String], target_path_segment: &String, search_latest: bool, forest: F, store: &impl BlockStore, - ) -> Result<(Vec<(Rc, String)>, PrivateNodeHistory)> { + ) -> Result<(Vec<(Arc, String)>, PrivateNodeHistory)> { // We only search for the latest revision in the private node. // It may have been deleted in future versions of its ancestor directories. let path_nodes = match dir @@ -311,17 +311,17 @@ impl PrivateNodeOnPathHistory { /// Takes a path of directories and initializes each path segment with an empty history. fn path_segment_empty_histories( - path: Vec<(Rc, String)>, + path: Vec<(Arc, String)>, forest: F, discrepancy_budget: usize, ) -> Result>> { let mut segments = Vec::new(); for (dir, path_segment) in path { segments.push(PathSegmentHistory { - dir: Rc::clone(&dir), + dir: Arc::clone(&dir), history: PrivateNodeHistory::of( - &PrivateNode::Dir(Rc::clone(&dir)), - &PrivateNode::Dir(Rc::clone(&dir)), + &PrivateNode::Dir(Arc::clone(&dir)), + &PrivateNode::Dir(Arc::clone(&dir)), discrepancy_budget, forest.clone(), )?, @@ -404,7 +404,7 @@ impl PrivateNodeOnPathHistory { async fn find_and_step_segment_history( &mut self, store: &impl BlockStore, - ) -> Result, String)>>> { + ) -> Result, String)>>> { let mut working_stack = Vec::with_capacity(self.path.len()); loop { @@ -439,7 +439,7 @@ impl PrivateNodeOnPathHistory { /// Returns false if there's no corresponding path in the previous revision. async fn repopulate_segment_histories( &mut self, - working_stack: Vec<(Rc, String)>, + working_stack: Vec<(Arc, String)>, store: &impl BlockStore, ) -> Result { // Work downwards from the previous history entry of a path segment we found @@ -506,8 +506,8 @@ mod tests { struct TestSetup { rng: ChaCha12Rng, store: MemoryBlockStore, - forest: Rc, - root_dir: Rc, + forest: Arc, + root_dir: Arc, discrepancy_budget: usize, } @@ -515,7 +515,7 @@ mod tests { fn new() -> Self { let mut rng = ChaCha12Rng::seed_from_u64(0); let store = MemoryBlockStore::default(); - let forest = Rc::new(HamtForest::new_rsa_2048(&mut rng)); + let forest = Arc::new(HamtForest::new_rsa_2048(&mut rng)); let root_dir = PrivateDirectory::new_rc(&forest.empty_name(), Utc::now(), &mut rng); Self { @@ -573,7 +573,7 @@ mod tests { discrepancy_budget, &[], true, - Rc::clone(forest), + Arc::clone(forest), store, ) .await @@ -660,7 +660,7 @@ mod tests { discrepancy_budget, &path, true, - Rc::clone(forest), + Arc::clone(forest), store, ) .await @@ -767,7 +767,7 @@ mod tests { discrepancy_budget, &path, true, - Rc::clone(forest), + Arc::clone(forest), store, ) .await @@ -895,7 +895,7 @@ mod tests { discrepancy_budget, &path, true, - Rc::clone(forest), + Arc::clone(forest), store, ) .await @@ -994,7 +994,7 @@ mod tests { let past_dir = root_dir.clone(); - let mut root_dir = Rc::new(root_dir.prepare_next_revision().unwrap().clone()); + let mut root_dir = Arc::new(root_dir.prepare_next_revision().unwrap().clone()); root_dir.store(forest, store, rng).await.unwrap(); @@ -1017,7 +1017,7 @@ mod tests { discrepancy_budget, &path, true, - Rc::clone(forest), + Arc::clone(forest), store, ) .await diff --git a/wnfs/src/private/share.rs b/wnfs/src/private/share.rs index 98f7d884..138f36a9 100644 --- a/wnfs/src/private/share.rs +++ b/wnfs/src/private/share.rs @@ -196,7 +196,7 @@ mod tests { use chrono::Utc; use rand_chacha::ChaCha12Rng; use rand_core::SeedableRng; - use std::rc::Rc; + use std::sync::Arc; use wnfs_common::{BlockStore, MemoryBlockStore}; mod helper { @@ -210,14 +210,14 @@ mod tests { use anyhow::Result; use chrono::Utc; use rand_core::CryptoRngCore; - use std::rc::Rc; + use std::sync::Arc; use wnfs_common::{BlockStore, CODEC_RAW}; pub(super) async fn create_sharer_dir( forest: &mut impl PrivateForest, store: &impl BlockStore, rng: &mut impl CryptoRngCore, - ) -> Result> { + ) -> Result> { let mut dir = PrivateDirectory::new_and_store( &forest.empty_name(), Utc::now(), @@ -243,7 +243,7 @@ mod tests { pub(super) async fn create_recipient_exchange_root( store: &impl BlockStore, - ) -> Result<(RsaPrivateKey, Rc)> { + ) -> Result<(RsaPrivateKey, Arc)> { let key = RsaPrivateKey::new()?; let exchange_key = key.get_public_key().get_public_key_modulus()?; let exchange_key_cid = store.put_block(exchange_key, CODEC_RAW).await?; @@ -389,7 +389,7 @@ mod tests { &access_key, i, sharer_root_did, - PublicLink::with_rc_dir(Rc::clone(&recipient_exchange_root)), + PublicLink::with_rc_dir(Arc::clone(&recipient_exchange_root)), forest, store, ) diff --git a/wnfs/src/public/directory.rs b/wnfs/src/public/directory.rs index 61ddb2a3..48b42f39 100644 --- a/wnfs/src/public/directory.rs +++ b/wnfs/src/public/directory.rs @@ -17,7 +17,7 @@ use serde::{ }; use std::{ collections::{BTreeMap, BTreeSet}, - rc::Rc, + sync::Arc, }; use wnfs_common::{utils::error, AsyncSerialize, BlockStore, Metadata, RemembersCid}; @@ -71,7 +71,7 @@ impl PublicDirectory { } } - /// Creates an `Rc` wrapped directory. + /// Creates an `Arc` wrapped directory. /// /// # Examples /// @@ -83,8 +83,8 @@ impl PublicDirectory { /// /// println!("Directory: {:?}", dir); /// ``` - pub fn new_rc(time: DateTime) -> Rc { - Rc::new(Self::new(time)) + pub fn new_rc(time: DateTime) -> Arc { + Arc::new(Self::new(time)) } /// Gets the previous Cids. @@ -93,7 +93,7 @@ impl PublicDirectory { /// /// ``` /// use wnfs::public::PublicDirectory; - /// use std::{rc::Rc, collections::BTreeSet}; + /// use std::{sync::Arc, collections::BTreeSet}; /// use chrono::Utc; /// /// let dir = PublicDirectory::new_rc(Utc::now()); @@ -101,7 +101,7 @@ impl PublicDirectory { /// assert_eq!(dir.get_previous(), &BTreeSet::new()); /// ``` #[inline] - pub fn get_previous<'a>(self: &'a Rc) -> &'a BTreeSet { + pub fn get_previous<'a>(self: &'a Arc) -> &'a BTreeSet { &self.previous } @@ -119,7 +119,7 @@ impl PublicDirectory { /// assert_eq!(dir.get_metadata(), &Metadata::new(time)); /// ``` #[inline] - pub fn get_metadata<'a>(self: &'a Rc) -> &'a Metadata { + pub fn get_metadata<'a>(self: &'a Arc) -> &'a Metadata { &self.metadata } @@ -129,7 +129,7 @@ impl PublicDirectory { } /// Returns a mutable reference to this directory's metadata and ratchets forward the history, if necessary. - pub fn get_metadata_mut_rc<'a>(self: &'a mut Rc) -> &'a mut Metadata { + pub fn get_metadata_mut_rc<'a>(self: &'a mut Arc) -> &'a mut Metadata { self.prepare_next_revision().get_metadata_mut() } @@ -137,12 +137,12 @@ impl PublicDirectory { /// directory was previously `.store()`ed. /// In any case it'll try to give you ownership of the directory if possible, /// otherwise it clones. - pub(crate) fn prepare_next_revision<'a>(self: &'a mut Rc) -> &'a mut Self { + pub(crate) fn prepare_next_revision<'a>(self: &'a mut Arc) -> &'a mut Self { let Some(previous_cid) = self.persisted_as.get().cloned() else { - return Rc::make_mut(self); + return Arc::make_mut(self); }; - let cloned = Rc::make_mut(self); + let cloned = Arc::make_mut(self); cloned.persisted_as = OnceCell::new(); cloned.previous = [previous_cid].into_iter().collect(); cloned @@ -168,7 +168,7 @@ impl PublicDirectory { } async fn get_leaf_dir_mut<'a>( - self: &'a mut Rc, + self: &'a mut Arc, path_segments: &[String], store: &impl BlockStore, ) -> Result> { @@ -197,7 +197,7 @@ impl PublicDirectory { } async fn get_or_create_leaf_dir_mut<'a>( - self: &'a mut Rc, + self: &'a mut Arc, path_segments: &[String], time: DateTime, store: &impl BlockStore, @@ -206,7 +206,7 @@ impl PublicDirectory { SearchResult::Found(dir) => Ok(dir), SearchResult::Missing(mut dir, depth) => { for segment in &path_segments[depth..] { - dir = Rc::make_mut( + dir = Arc::make_mut( dir.userland .entry(segment.to_string()) .or_insert_with(|| PublicLink::with_dir(Self::new(time))) @@ -281,13 +281,13 @@ impl PublicDirectory { /// public::PublicDirectory, /// common::MemoryBlockStore /// }; - /// use std::rc::Rc; + /// use std::sync::Arc; /// use chrono::Utc; /// use wnfs_common::libipld::{Ipld, Cid}; /// /// #[async_std::main] /// async fn main() -> Result<()> { - /// let dir = &mut Rc::new(PublicDirectory::new(Utc::now())); + /// let dir = &mut Arc::new(PublicDirectory::new(Utc::now())); /// let store = &MemoryBlockStore::new(); /// /// // Gain a mutable file reference @@ -307,7 +307,7 @@ impl PublicDirectory { /// } /// ``` pub async fn open_file_mut<'a>( - self: &'a mut Rc, + self: &'a mut Arc, path_segments: &[String], initial_content: Cid, time: DateTime, @@ -458,7 +458,7 @@ impl PublicDirectory { /// } /// ``` pub async fn write( - self: &mut Rc, + self: &mut Arc, path_segments: &[String], content_cid: Cid, time: DateTime, @@ -515,7 +515,7 @@ impl PublicDirectory { /// /// This method acts like `mkdir -p` in Unix because it creates intermediate directories if they do not exist. pub async fn mkdir( - self: &mut Rc, + self: &mut Arc, path_segments: &[String], time: DateTime, store: &impl BlockStore, @@ -636,7 +636,7 @@ impl PublicDirectory { /// } /// ``` pub async fn rm( - self: &mut Rc, + self: &mut Arc, path_segments: &[String], store: &impl BlockStore, ) -> Result { @@ -702,7 +702,7 @@ impl PublicDirectory { /// } /// ``` pub async fn basic_mv( - self: &mut Rc, + self: &mut Arc, path_segments_from: &[String], path_segments_to: &[String], time: DateTime, @@ -775,7 +775,7 @@ impl PublicDirectory { /// } /// ``` pub async fn cp( - self: &mut Rc, + self: &mut Arc, path_segments_from: &[String], path_segments_to: &[String], time: DateTime, @@ -1334,7 +1334,7 @@ mod tests { let previous_cid = &root_dir.store(store).await.unwrap(); let next_root_dir = root_dir.prepare_next_revision(); - let next_root_dir_clone = &mut Rc::new(next_root_dir.clone()); + let next_root_dir_clone = &mut Arc::new(next_root_dir.clone()); let yet_another_dir = next_root_dir_clone.prepare_next_revision(); assert_eq!( diff --git a/wnfs/src/public/file.rs b/wnfs/src/public/file.rs index b3560b65..e6d550f9 100644 --- a/wnfs/src/public/file.rs +++ b/wnfs/src/public/file.rs @@ -7,7 +7,7 @@ use async_once_cell::OnceCell; use chrono::{DateTime, Utc}; use libipld_core::cid::Cid; use serde::{de::Error as DeError, Deserialize, Deserializer, Serialize, Serializer}; -use std::{collections::BTreeSet, rc::Rc}; +use std::{collections::BTreeSet, sync::Arc}; use wnfs_common::{BlockStore, Metadata, RemembersCid}; /// A file in the WNFS public file system. @@ -58,7 +58,7 @@ impl PublicFile { } } - /// Creates an `Rc` wrapped file. + /// Creates an `Arc` wrapped file. /// /// # Examples /// @@ -71,20 +71,20 @@ impl PublicFile { /// /// println!("File: {:?}", file); /// ``` - pub fn new_rc(time: DateTime, content_cid: Cid) -> Rc { - Rc::new(Self::new(time, content_cid)) + pub fn new_rc(time: DateTime, content_cid: Cid) -> Arc { + Arc::new(Self::new(time, content_cid)) } /// Takes care of creating previous links, in case the current /// directory was previously `.store()`ed. /// In any case it'll try to give you ownership of the directory if possible, /// otherwise it clones. - pub(crate) fn prepare_next_revision<'a>(self: &'a mut Rc) -> &'a mut Self { + pub(crate) fn prepare_next_revision<'a>(self: &'a mut Arc) -> &'a mut Self { let Some(previous_cid) = self.persisted_as.get().cloned() else { - return Rc::make_mut(self); + return Arc::make_mut(self); }; - let cloned = Rc::make_mut(self); + let cloned = Arc::make_mut(self); cloned.persisted_as = OnceCell::new(); cloned.previous = [previous_cid].into_iter().collect(); @@ -93,7 +93,7 @@ impl PublicFile { /// Writes a new content cid to the file. /// This will create a new revision of the file. - pub(crate) fn write(self: &mut Rc, time: DateTime, content_cid: Cid) { + pub(crate) fn write(self: &mut Arc, time: DateTime, content_cid: Cid) { let file = self.prepare_next_revision(); file.userland = content_cid; file.metadata.upsert_mtime(time); @@ -126,7 +126,7 @@ impl PublicFile { } /// Returns a mutable reference to this file's metadata and ratchets forward the history, if necessary. - pub fn get_metadata_mut_rc<'a>(self: &'a mut Rc) -> &'a mut Metadata { + pub fn get_metadata_mut_rc<'a>(self: &'a mut Arc) -> &'a mut Metadata { self.prepare_next_revision().get_metadata_mut() } @@ -287,7 +287,7 @@ mod tests { let file = &mut PublicFile::new_rc(time, content_cid); let previous_cid = &file.store(store).await.unwrap(); let next_file = file.prepare_next_revision(); - let next_file_clone = &mut Rc::new(next_file.clone()); + let next_file_clone = &mut Arc::new(next_file.clone()); let yet_another_file = next_file_clone.prepare_next_revision(); assert_eq!( diff --git a/wnfs/src/public/link.rs b/wnfs/src/public/link.rs index 48542c59..0a7403cc 100644 --- a/wnfs/src/public/link.rs +++ b/wnfs/src/public/link.rs @@ -3,7 +3,7 @@ use super::{PublicDirectory, PublicFile, PublicNode}; use anyhow::Result; use libipld_core::cid::Cid; -use std::rc::Rc; +use std::sync::Arc; use wnfs_common::{BlockStore, Link}; //-------------------------------------------------------------------------------------------------- @@ -36,19 +36,19 @@ impl PublicLink { /// Creates a link to a directory node. #[inline] pub fn with_dir(dir: PublicDirectory) -> Self { - Self(Link::from(PublicNode::Dir(Rc::new(dir)))) + Self(Link::from(PublicNode::Dir(Arc::new(dir)))) } /// Creates a link to a directory node. #[inline] - pub fn with_rc_dir(dir: Rc) -> Self { + pub fn with_rc_dir(dir: Arc) -> Self { Self(Link::from(PublicNode::Dir(dir))) } /// Creates a link to a file node. #[inline] pub fn with_file(file: PublicFile) -> Self { - Self(Link::from(PublicNode::File(Rc::new(file)))) + Self(Link::from(PublicNode::File(Arc::new(file)))) } /// Gets the Cid stored in type. It attempts to get it from the store if it is not present in type. diff --git a/wnfs/src/public/node/node.rs b/wnfs/src/public/node/node.rs index 4f113e5c..b8a93338 100644 --- a/wnfs/src/public/node/node.rs +++ b/wnfs/src/public/node/node.rs @@ -12,7 +12,7 @@ use async_trait::async_trait; use chrono::{DateTime, Utc}; use libipld_core::cid::Cid; use serde::{de::Error as DeError, Deserialize, Deserializer, Serialize, Serializer}; -use std::{collections::BTreeSet, rc::Rc}; +use std::{collections::BTreeSet, sync::Arc}; use wnfs_common::{AsyncSerialize, BlockStore, RemembersCid}; //-------------------------------------------------------------------------------------------------- @@ -34,8 +34,8 @@ use wnfs_common::{AsyncSerialize, BlockStore, RemembersCid}; /// ``` #[derive(Debug, Clone)] pub enum PublicNode { - File(Rc), - Dir(Rc), + File(Arc), + Dir(Arc), } //-------------------------------------------------------------------------------------------------- @@ -69,10 +69,10 @@ impl PublicNode { pub fn upsert_mtime(&mut self, time: DateTime) { match self { Self::File(file) => { - Rc::make_mut(file).metadata.upsert_mtime(time); + Arc::make_mut(file).metadata.upsert_mtime(time); } Self::Dir(dir) => { - Rc::make_mut(dir).metadata.upsert_mtime(time); + Arc::make_mut(dir).metadata.upsert_mtime(time); } } } @@ -85,7 +85,7 @@ impl PublicNode { /// use wnfs::public::{PublicDirectory, PublicNode}; /// use chrono::Utc; /// use libipld_core::cid::Cid; - /// use std::{rc::Rc, collections::BTreeSet}; + /// use std::{sync::Arc, collections::BTreeSet}; /// /// let dir = PublicDirectory::new_rc(Utc::now()); /// let node = PublicNode::Dir(dir); @@ -105,12 +105,12 @@ impl PublicNode { Self::File(file) => { let mut file = (**file).clone(); file.previous = cids.into_iter().collect(); - Self::File(Rc::new(file)) + Self::File(Arc::new(file)) } Self::Dir(dir) => { let mut dir = (**dir).clone(); dir.previous = cids.into_iter().collect(); - Self::Dir(Rc::new(dir)) + Self::Dir(Arc::new(dir)) } } } @@ -145,24 +145,24 @@ impl PublicNode { /// # Examples /// /// ``` - /// use std::rc::Rc; + /// use std::sync::Arc; /// use wnfs::public::{PublicDirectory, PublicNode}; /// use chrono::Utc; /// /// let dir = PublicDirectory::new_rc(Utc::now()); - /// let node = PublicNode::Dir(Rc::clone(&dir)); + /// let node = PublicNode::Dir(Arc::clone(&dir)); /// /// assert_eq!(node.as_dir().unwrap(), dir); /// ``` - pub fn as_dir(&self) -> Result> { + pub fn as_dir(&self) -> Result> { Ok(match self { - Self::Dir(dir) => Rc::clone(dir), + Self::Dir(dir) => Arc::clone(dir), _ => bail!(FsError::NotADirectory), }) } /// Casts a node to a mutable directory. - pub(crate) fn as_dir_mut(&mut self) -> Result<&mut Rc> { + pub(crate) fn as_dir_mut(&mut self) -> Result<&mut Arc> { Ok(match self { Self::Dir(dir) => dir, _ => bail!(FsError::NotADirectory), @@ -174,25 +174,25 @@ impl PublicNode { /// # Examples /// /// ``` - /// use std::rc::Rc; + /// use std::sync::Arc; /// use wnfs::public::{PublicFile, PublicNode}; /// use chrono::Utc; /// use libipld_core::cid::Cid; /// /// let file = PublicFile::new_rc(Utc::now(), Cid::default()); - /// let node = PublicNode::File(Rc::clone(&file)); + /// let node = PublicNode::File(Arc::clone(&file)); /// /// assert_eq!(node.as_file().unwrap(), file); /// ``` - pub fn as_file(&self) -> Result> { + pub fn as_file(&self) -> Result> { Ok(match self { - Self::File(file) => Rc::clone(file), + Self::File(file) => Arc::clone(file), _ => bail!(FsError::NotAFile), }) } /// Tries to resolve this node as a file. Fails with `NotAFile` otherwise. - pub fn as_file_mut(&mut self) -> Result<&mut Rc> { + pub fn as_file_mut(&mut self) -> Result<&mut Arc> { match self { Self::File(file) => Ok(file), _ => bail!(FsError::NotAFile), @@ -262,10 +262,10 @@ impl PartialEq for PublicNode { fn eq(&self, other: &PublicNode) -> bool { match (self, other) { (Self::File(self_file), Self::File(other_file)) => { - Rc::ptr_eq(self_file, other_file) || self_file == other_file + Arc::ptr_eq(self_file, other_file) || self_file == other_file } (Self::Dir(self_dir), Self::Dir(other_dir)) => { - Rc::ptr_eq(self_dir, other_dir) || self_dir == other_dir + Arc::ptr_eq(self_dir, other_dir) || self_dir == other_dir } _ => false, } @@ -274,13 +274,13 @@ impl PartialEq for PublicNode { impl From for PublicNode { fn from(file: PublicFile) -> Self { - Self::File(Rc::new(file)) + Self::File(Arc::new(file)) } } impl From for PublicNode { fn from(dir: PublicDirectory) -> Self { - Self::Dir(Rc::new(dir)) + Self::Dir(Arc::new(dir)) } } @@ -292,11 +292,11 @@ impl<'de> Deserialize<'de> for PublicNode { Ok(match PublicNodeSerializable::deserialize(deserializer)? { PublicNodeSerializable::File(file) => { let file = PublicFile::from_serializable(file).map_err(DeError::custom)?; - Self::File(Rc::new(file)) + Self::File(Arc::new(file)) } PublicNodeSerializable::Dir(dir) => { let dir = PublicDirectory::from_serializable(dir).map_err(DeError::custom)?; - Self::Dir(Rc::new(dir)) + Self::Dir(Arc::new(dir)) } }) } diff --git a/wnfs/src/root_tree.rs b/wnfs/src/root_tree.rs index ac668452..b42e59dc 100644 --- a/wnfs/src/root_tree.rs +++ b/wnfs/src/root_tree.rs @@ -21,7 +21,7 @@ use rand_chacha::{rand_core::SeedableRng, ChaCha12Rng}; use rand_core::CryptoRngCore; use semver::Version; use serde::{Deserialize, Serialize}; -use std::{collections::HashMap, rc::Rc}; +use std::{collections::HashMap, sync::Arc}; #[cfg(test)] use wnfs_common::MemoryBlockStore; use wnfs_common::{BlockStore, Metadata, CODEC_RAW}; @@ -36,10 +36,10 @@ use wnfs_nameaccumulator::AccumulatorSetup; pub struct RootTree<'a, B: BlockStore, R: CryptoRngCore> { pub store: &'a B, pub rng: R, - pub forest: Rc, - pub public_root: Rc, - pub exchange_root: Rc, - pub private_map: HashMap, Rc>, + pub forest: Arc, + pub public_root: Arc, + pub exchange_root: Arc, + pub private_map: HashMap, Arc>, } #[derive(Debug, Serialize, Deserialize)] @@ -60,11 +60,11 @@ where R: CryptoRngCore, { pub async fn new( - forest: Rc, + forest: Arc, store: &'a B, rng: R, time: DateTime, - private_map: HashMap, Rc>, + private_map: HashMap, Arc>, ) -> RootTree<'a, B, R> { Self { store, @@ -321,12 +321,12 @@ where cid: &Cid, store: &'a B, rng: R, - private_map: HashMap, Rc>, + private_map: HashMap, Arc>, ) -> Result> { let deserialized: RootTreeSerializable = store.get_deserializable(cid).await?; - let forest = Rc::new(HamtForest::load(&deserialized.forest, store).await?); - let public_root = Rc::new(store.get_deserializable(&deserialized.public).await?); - let exchange_root = Rc::new(store.get_deserializable(&deserialized.exchange).await?); + let forest = Arc::new(HamtForest::load(&deserialized.forest, store).await?); + let public_root = Arc::new(store.get_deserializable(&deserialized.public).await?); + let exchange_root = Arc::new(store.get_deserializable(&deserialized.exchange).await?); Ok(Self { store, @@ -344,7 +344,7 @@ impl<'a, B: BlockStore> RootTree<'a, B, ChaCha12Rng> { pub fn with_store(store: &'a B) -> RootTree<'a, B, ChaCha12Rng> { let mut rng = ChaCha12Rng::seed_from_u64(0); let time = Utc.with_ymd_and_hms(1970, 1, 1, 0, 0, 0).unwrap(); - let forest = Rc::new(HamtForest::new(AccumulatorSetup::trusted(&mut rng))); + let forest = Arc::new(HamtForest::new(AccumulatorSetup::trusted(&mut rng))); Self { store, @@ -466,7 +466,7 @@ mod snapshot_tests { } let _ = root_tree.store(store).await.unwrap(); - let forest = &mut Rc::clone(&root_tree.forest); + let forest = &mut Arc::clone(&root_tree.forest); let root_dir = root_tree .private_map .get(&vec!["private".to_string()]) diff --git a/wnfs/src/utils/test.rs b/wnfs/src/utils/test.rs index 3fbd115e..9e31faee 100644 --- a/wnfs/src/utils/test.rs +++ b/wnfs/src/utils/test.rs @@ -5,7 +5,7 @@ use crate::private::{ use anyhow::Result; use libipld_core::ipld::Ipld; use rand_core::CryptoRngCore; -use std::rc::Rc; +use std::sync::Arc; use wnfs_common::{decode, libipld::cbor::DagCborCodec, utils::SnapshotBlockStore}; use wnfs_nameaccumulator::Name; @@ -15,8 +15,8 @@ use wnfs_nameaccumulator::Name; pub(crate) async fn walk_dir( store: &mut SnapshotBlockStore, - forest: &mut Rc, - root_dir: &Rc, + forest: &mut Arc, + root_dir: &Arc, rng: &mut impl CryptoRngCore, ) -> Result<()> { let mut stack = vec![root_dir.clone()];