### Consistency example for load method Source: https://docs.rs/arc-swap/latest/arc_swap/type.ArcSwapOption.html Shows the recommended pattern of using load once to get a consistent snapshot, contrasting with a broken pattern that loads twice and may see inconsistent values. ```rust struct Point { x: usize, y: usize, } fn print_broken(p: &ArcSwap) { // This is broken, because the x and y may come from different points, // combining into an invalid point that never existed. println!("X: {}", p.load().x); // If someone changes the content now, between these two loads, we // have a problem println!("Y: {}", p.load().y); } fn print_correct(p: &ArcSwap) { // Here we take a snapshot of one specific point so both x and y come // from the same one. let point = p.load(); println!("X: {}", point.x); println!("Y: {}", point.y); } ``` -------------------------------- ### Example: using AccessConvert with Map to access nested fields Source: https://docs.rs/arc-swap/latest/arc_swap/access/struct.AccessConvert.html Example demonstrating the use of AccessConvert to wrap a DynAccess and use it with Map to access nested fields. It shows how to load a value and assert its content. ```rust use std::sync::Arc; use arc_swap::ArcSwap; use arc_swap::access::{AccessConvert, DynAccess, Map}; struct Inner { val: usize, } struct Middle { inner: Inner, } struct Outer { middle: Middle, } let outer = Arc::new(ArcSwap::from_pointee(Outer { middle: Middle { inner: Inner { val: 42, } } })); let middle: Arc> = Arc::new(Map::new(outer, |outer: &Outer| &outer.middle)); let inner: Arc> = Arc::new(Map::new(AccessConvert(middle), |middle: &Middle| &middle.inner)); let guard = inner.load(); assert_eq!(42, guard.val); ``` -------------------------------- ### ArcSwap usage example with threads Source: https://docs.rs/arc-swap/latest/arc_swap/index.html Shows how to create an ArcSwap from an Arc, store a new value from one thread, and load it from multiple threads until it becomes non-empty. Uses crossbeam_utils::thread for scoped threads. The example asserts that the loaded value equals the new configuration. ```rust use std::sync::Arc; use arc_swap::ArcSwap; use crossbeam_utils::thread; let config = ArcSwap::from(Arc::new(String::default())); thread::scope(|scope| { scope.spawn(|_| { let new_conf = Arc::new("New configuration".to_owned()); config.store(new_conf); }); for _ in 0..10 { scope.spawn(|_| { loop { let cfg = config.load(); if !cfg.is_empty() { assert_eq!(**cfg, "New configuration"); return; } } }); } }).unwrap(); ``` -------------------------------- ### Basic ArcSwap usage example Source: https://docs.rs/arc-swap/latest/arc_swap/struct.ArcSwapAny.html Shows how to create an ArcSwap from an Arc, load the value, and swap in a new Arc. Demonstrates that load can be called multiple times and that swap returns the previous value. ```rust let arc = Arc::new(42); let arc_swap = ArcSwap::from(arc); assert_eq!(42, **arc_swap.load()); // It can be read multiple times assert_eq!(42, **arc_swap.load()); // Put a new one in there let new_arc = Arc::new(0); assert_eq!(42, *arc_swap.swap(new_arc)); assert_eq!(0, **arc_swap.load()); ``` -------------------------------- ### Example: using AsRaw with compare_and_swap Source: https://docs.rs/arc-swap/latest/arc_swap/trait.AsRaw.html Shows how to use AsRaw via compare_and_swap on ArcSwapOption. Demonstrates passing various types that implement AsRaw, including references, Option, and raw pointers. Note that owned Arc and Option are not implemented due to technical limitations. ```rust use std::ptr; use std::sync::Arc; use arc_swap::ArcSwapOption; let a = Arc::new(42); let shared = ArcSwapOption::from(Some(Arc::clone(&a))); shared.compare_and_swap(&a, Some(Arc::clone(&a))); shared.compare_and_swap(&None::>, Some(Arc::clone(&a))); shared.compare_and_swap(shared.load(), Some(Arc::clone(&a))); shared.compare_and_swap(&shared.load(), Some(Arc::clone(&a))); shared.compare_and_swap(ptr::null(), Some(Arc::clone(&a))); ``` -------------------------------- ### Cache usage with threads Source: https://docs.rs/arc-swap/latest/arc_swap/cache/struct.Cache.html Example showing how to create a Cache from an ArcSwap, spawn multiple threads that repeatedly load from the cache, and update the shared value. ```rust use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use arc_swap::{ArcSwap, Cache}; let shared = Arc::new(ArcSwap::from_pointee(42)); let terminate = Arc::new(AtomicBool::new(false)); // Start 10 worker threads... for _ in 0..10 { let mut cache = Cache::new(Arc::clone(&shared)); let terminate = Arc::clone(&terminate); std::thread::spawn(move || { // Keep loading it like mad.. while !terminate.load(Ordering::Relaxed) { let value = cache.load(); do_something(value); } }); } shared.store(Arc::new(12)); ``` -------------------------------- ### Using from_pointee to create ArcSwapOption Source: https://docs.rs/arc-swap/latest/arc_swap/type.ArcSwapOption.html Shows how to create an ArcSwapOption directly from a pointed-to value, either None or a value that gets wrapped in Arc. ```rust use arc_swap::ArcSwapOption; let empty: ArcSwapOption = ArcSwapOption::from_pointee(None); assert!(empty.load().is_none()); let non_empty: ArcSwapOption = ArcSwapOption::from_pointee(42); assert_eq!(42, **non_empty.load().as_ref().unwrap()); ``` -------------------------------- ### Using DynAccess with Constant Source: https://docs.rs/arc-swap/latest/arc_swap/access/trait.DynAccess.html Shows how to use DynAccess as a trait object to load a value from a Constant. The example prints the loaded value. ```rust use arc_swap::access::{Constant, DynAccess}; fn do_something(value: Box + Send>) { let v = value.load(); println!("{}", *v); } do_something(Box::new(Constant(42))); ``` -------------------------------- ### Sharing configuration data with ArcSwap Source: https://docs.rs/arc-swap/latest/arc_swap/docs/patterns/index.html This example shows how to share configuration data between threads using Arc>. It creates a configuration thread that periodically updates the config, and multiple worker threads that load the current config before each work chunk. The example uses an AtomicBool for termination and joins all threads at the end. ```rust #[derive(Debug, Default)] struct Config { // ... Stuff in here ... } // We wrap the ArcSwap into an Arc, so we can share it between threads. let config = Arc::new(ArcSwap::from_pointee(Config::default())); let terminate = Arc::new(AtomicBool::new(false)); let mut threads = Vec::new(); // The configuration thread threads.push(thread::spawn({ let config = Arc::clone(&config); let terminate = Arc::clone(&terminate); move || { while !terminate.load(Ordering::Relaxed) { thread::sleep(Duration::from_secs(6)); // Actually, load it from somewhere let new_config = Arc::new(Config::default()); config.store(new_config); } } })); // The worker thread for _ in 0..10 { threads.push(thread::spawn({ let config = Arc::clone(&config); let terminate = Arc::clone(&terminate); move || { while !terminate.load(Ordering::Relaxed) { let work = Work::fetch(); let config = config.load(); work.perform(&config); } } })); } // Terminate gracefully terminate.store(true, Ordering::Relaxed); for thread in threads { thread.join().unwrap(); } ``` -------------------------------- ### Example: Using Access, Map, and Constant with ArcSwap Source: https://docs.rs/arc-swap/latest/arc_swap/access/index.html This example shows how to use the Access trait with ArcSwap, Map, and Constant. It defines a function that accepts any Access and spawns a thread that loads and prints the value until it reaches 42. It demonstrates passing the whole ArcSwap directly, mapping a subset of a struct, and using a constant for testing. Note that the Access trait is not object safe; use DynAccess for type erasure. ```rust use std::sync::Arc; use std::thread::{self, JoinHandle}; use std::time::Duration; use arc_swap::ArcSwap; use arc_swap::access::{Access, Constant, Map}; fn work_with_usize + Send + 'static>(a: A) -> JoinHandle<()> { thread::spawn(move || { let mut value = 0; while value != 42 { let guard = a.load(); value = *guard; println!("{}", value); // Not strictly necessary, but dropping the guard can free some resources, like // slots for tracking what values are still in use. We do it before the sleeping, // not at the end of the scope. drop(guard); thread::sleep(Duration::from_millis(50)); } }) } // Passing the whole thing directly // (If we kept another Arc to it, we could change the value behind the scenes) work_with_usize(Arc::new(ArcSwap::from_pointee(42))).join().unwrap(); // Passing a subset of a structure struct Cfg { value: usize, } let cfg = Arc::new(ArcSwap::from_pointee(Cfg { value: 0 })); let thread = work_with_usize(Map::new(Arc::clone(&cfg), |cfg: &Cfg| &cfg.value)); cfg.store(Arc::new(Cfg { value: 42 })); thread.join().unwrap(); // Passing a constant that can't change. Useful mostly for testing purposes. work_with_usize(Constant(42)).join().unwrap(); ``` -------------------------------- ### Cache usage with thread-local storage and explicit types Source: https://docs.rs/arc-swap/latest/arc_swap/cache/struct.Cache.html Example showing how to use Cache with a thread-local static and explicit type annotations, including a note about needing RefCell because load takes &mut. ```rust static CURRENT_CONFIG: Lazy> = Lazy::new(|| ArcSwap::from_pointee(Config::default())); thread_local! { static CACHE: RefCell, Arc>> = RefCell::new(Cache::from(CURRENT_CONFIG.deref())); } CACHE.with(|c| { // * RefCell needed, because load on cache is `&mut`. // * You want to operate inside the `with` ‒ cloning the Arc is comparably expensive as // ArcSwap::load itself and whatever you'd save by the cache would be lost on that. println!("{:?}", c.borrow_mut().load()); }); ``` -------------------------------- ### from_inner example Source: https://docs.rs/arc-swap/latest/arc_swap/struct.Guard.html Example usage of from_inner to create a second guard for the same object, using Arc::clone to share the underlying value. ```rust // Create two guards pointing to the same object let g1 = p.load(); let g2 = Guard::<_, DefaultStrategy>::from_inner(Arc::clone(&*g1)); ``` -------------------------------- ### rcu with cache to avoid expensive recomputation Source: https://docs.rs/arc-swap/latest/arc_swap/type.ArcSwapOption.html This example demonstrates using rcu with a cache (HashMap) to avoid recomputing expensive results. The expensive computation is done outside the rcu closure, while the cheaper clone of the cache is retried if needed. ```rust fn expensive_computation(x: usize) -> usize { x * 2 // Let's pretend multiplication is *really expensive expensive* } type Cache = HashMap; static CACHE: Lazy> = Lazy::new(|| ArcSwap::default()); fn cached_computation(x: usize) -> usize { let cache = CACHE.load(); if let Some(result) = cache.get(&x) { return *result; } // Not in cache. Compute and store. // The expensive computation goes outside, so it is not retried. let result = expensive_computation(x); CACHE.rcu(|cache| { // The cheaper clone of the cache can be retried if need be. let mut cache = HashMap::clone(&cache); cache.insert(x, result); cache }); result } assert_eq!(42, cached_computation(21)); assert_eq!(42, cached_computation(21)); ``` -------------------------------- ### Using ArcSwap::map to project a configuration field Source: https://docs.rs/arc-swap/latest/arc_swap/type.ArcSwapOption.html Shows how to use `map` to project a field from a shared `ArcSwap` configuration, allowing a component to access only its relevant part. The example spawns threads that read the mapped value and update the shared configuration, demonstrating concurrent access. ```rust use std::sync::Arc; use arc_swap::ArcSwap; use arc_swap::access::Access; struct Cfg { value: usize, } fn print_many_times>(value: V) { for _ in 0..25 { let value = value.load(); println!("{}", *value); } } let shared = ArcSwap::from_pointee(Cfg { value: 0 }); let mapped = shared.map(|c: &Cfg| &c.value); crossbeam_utils::thread::scope(|s| { // Will print some zeroes and some twos s.spawn(|_| print_many_times(mapped)); s.spawn(|_| shared.store(Arc::new(Cfg { value: 2 }))); }).expect("Something panicked in a thread"); ``` -------------------------------- ### Using Cache::map to project a field from a cached struct Source: https://docs.rs/arc-swap/latest/arc_swap/cache/struct.Cache.html Shows how to create a Cache from an ArcSwap, map it to access an inner field, and pass it to a function expecting an Access. The example prints the answer from the cached value and also demonstrates a direct cache without mapping. ```rust use arc_swap::ArcSwap; use arc_swap::cache::{Access, Cache}; struct InnerCfg { answer: usize, } struct FullCfg { inner: InnerCfg, } fn use_inner>(cache: &mut A) { let value = cache.load(); println!("The answer is: {}", value.answer); } let full_cfg = ArcSwap::from_pointee(FullCfg { inner: InnerCfg { answer: 42, } }); let cache = Cache::new(&full_cfg); use_inner(&mut cache.map(|full| &full.inner)); let inner_cfg = ArcSwap::from_pointee(InnerCfg { answer: 24 }); let mut inner_cache = Cache::new(&inner_cfg); use_inner(&mut inner_cache); ``` -------------------------------- ### new Source: https://docs.rs/arc-swap/latest/arc_swap/struct.ArcSwapAny.html Constructs a new storage with a default strategy. ```APIDOC ## new ### Description Constructs a new storage. ### Signature pub fn new(val: T) -> Self where S: Default ### Parameters - **val** (T) - Required - The initial value to store. ### Returns - **Self** - The newly constructed ArcSwapAny instance. ``` -------------------------------- ### Basic usage of ArcSwapOption Source: https://docs.rs/arc-swap/latest/arc_swap/type.ArcSwapOption.html Shows how to create an ArcSwapOption from None, load it, and swap in a new value. Demonstrates that load_full returns an Option>. ```rust use std::sync::Arc; use arc_swap::ArcSwapOption; let shared = ArcSwapOption::from(None); assert!(shared.load_full().is_none()); assert!(shared.swap(Some(Arc::new(42))).is_none()); assert_eq!(42, **shared.load_full().as_ref().unwrap()); ``` -------------------------------- ### with_strategy Source: https://docs.rs/arc-swap/latest/arc_swap/struct.ArcSwapAny.html Constructs a new storage while customizing the protection strategy. ```APIDOC ## with_strategy ### Description Constructs a new storage while customizing the protection strategy. ### Signature pub fn with_strategy(val: T, strategy: S) -> Self ### Parameters - **val** (T) - Required - The initial value to store. - **strategy** (S) - Required - The protection strategy to use. ### Returns - **Self** - The newly constructed ArcSwapAny instance. ``` -------------------------------- ### new Source: https://docs.rs/arc-swap/latest/arc_swap/type.ArcSwap.html Constructs a new storage with the given value. ```APIDOC ## Method: new ### Description Constructs a new storage. ### Signature ```rust pub fn new(val: T) -> Self where S: Default, ``` ### Parameters - **val** (T) - Required - The initial value to store. ### Returns - **Self** - A new ArcSwap instance. ``` -------------------------------- ### Workaround for unsized types using Box<[u8]> Source: https://docs.rs/arc-swap/latest/arc_swap/docs/limitations/index.html Shows how to use ArcSwap with unsized types via double indirection. The commented-out line demonstrates the unsupported usage with [u8], while the working example uses Box<[u8]>. ```rust // This doesn't work: // let data: ArcSwap<[u8]> = ArcSwap::new(Arc::from([1, 2, 3])); // But this does: let data: ArcSwap> = ArcSwap::from_pointee(Box::new([1, 2, 3])); ``` -------------------------------- ### Emulate Clone behavior with load_full Source: https://docs.rs/arc-swap/latest/arc_swap/docs/limitations/index.html Shows how to create a new ArcSwap instance that shares the same underlying value as an existing one, emulating the removed Clone implementation. ```rust let new = ArcSwap::new(old.load_full()); ``` -------------------------------- ### Correct rcu usage: atomic increment with retries Source: https://docs.rs/arc-swap/latest/arc_swap/type.ArcSwapOption.html This example shows the correct way to increment a shared counter using the rcu method, which retries the closure if another thread updates the value in between. The assertion at the end is expected to succeed. ```rust let cnt = ArcSwap::from_pointee(0); thread::scope(|scope| { for _ in 0..10 { scope.spawn(|_| cnt.rcu(|inner| **inner + 1)); } }).unwrap(); assert_eq!(10, *cnt.load_full()); ``` -------------------------------- ### Incorrect rcu usage: non-atomic increment Source: https://docs.rs/arc-swap/latest/arc_swap/type.ArcSwapOption.html This example shows a naive approach to incrementing a shared counter using load_full and store, which can fail because another thread might update the value between the load and store. The commented assertion is likely to fail. ```rust let cnt = ArcSwap::from_pointee(0); thread::scope(|scope| { for _ in 0..10 { scope.spawn(|_| { let inner = cnt.load_full(); // Another thread might have stored some other number than what we have // between the load and store. cnt.store(Arc::new(*inner + 1)); }); } }).unwrap(); // This will likely fail: // assert_eq!(10, *cnt.load_full()); ``` -------------------------------- ### Component with DynAccess and Map projection Source: https://docs.rs/arc-swap/latest/arc_swap/docs/patterns/index.html Shows a Component that holds a Box>, and creates a Map to project from the ArcSwap into the component field. Use Box::new(Constant(ComponentConfig)) in unit tests instead. ```rust #[derive(Debug, Default)] struct ComponentConfig; struct Component { config: Box>, } #[derive(Debug, Default)] struct Config { component: ComponentConfig, } let config = Arc::new(ArcSwap::from_pointee(Config::default())); let component = Component { config: Box::new(Map::new(Arc::clone(&config), |config: &Config| &config.component)), }; ``` -------------------------------- ### from_pointee Source: https://docs.rs/arc-swap/latest/arc_swap/struct.ArcSwapAny.html A convenience constructor directly from a pointed-to value. This allocates the Arc under the hood. ```APIDOC ## from_pointee ### Description A convenience constructor directly from a pointed-to value. This allocates the `Arc` under the hood. ### Method Constructor ### Signature `pub fn from_pointee>>(val: V) -> Self` ### Parameters - **val** (V) - Required - The value to wrap in an `Option` and store. ### Example ```rust use arc_swap::ArcSwapOption; let empty: ArcSwapOption = ArcSwapOption::from_pointee(None); assert!(empty.load().is_none()); let non_empty: ArcSwapOption = ArcSwapOption::from_pointee(42); assert_eq!(42, **non_empty.load().as_ref().unwrap()); ``` ``` -------------------------------- ### ArcSwapAny::with_strategy Source: https://docs.rs/arc-swap/latest/arc_swap/type.ArcSwapOption.html Constructs a new storage while customizing the protection strategy. ```APIDOC ## ArcSwapAny::with_strategy ### Description Constructs a new storage while customizing the protection strategy. ### Method `pub fn with_strategy(val: T, strategy: S) -> Self` ### Parameters - **val** (`T`) - Required - The initial value to store. - **strategy** (`S`) - Required - The protection strategy to use. ### Return Value - `Self` - A new `ArcSwapAny` instance with the specified strategy. ``` -------------------------------- ### From::from Source: https://docs.rs/arc-swap/latest/arc_swap/struct.ArcSwapAny.html Converts to this type from the input type. ```APIDOC ## From::from ### Description Converts to this type from the input type. ### Method Trait method ### Signature `fn from(val: T) -> Self` ``` -------------------------------- ### load Source: https://docs.rs/arc-swap/latest/arc_swap/struct.ArcSwapAny.html Provides a temporary borrow of the object inside. ```APIDOC ## load ### Description Provides a temporary borrow of the object inside. This returns a proxy object allowing access to the thing held inside. However, there’s only limited amount of possible cheap proxies in existence for each thread ‒ if more are created, it falls back to equivalent of `load_full` internally. This is therefore a good choice to use for eg. searching a data structure or juggling the pointers around a bit, but not as something to store in larger amounts. The rule of thumb is this is suited for local variables on stack, but not in long-living data structures. ### Signature pub fn load(&self) -> Guard ### Returns - **Guard** - A proxy object allowing access to the held value. ### Consistency In case multiple related operations are to be done on the loaded value, it is generally recommended to call `load` just once and keep the result over calling it multiple times. First, keeping it is usually faster. But more importantly, the value can change between the calls to load, returning different objects, which could lead to logical inconsistency. Keeping the result makes sure the same object is used. ``` -------------------------------- ### ArcSwap load pattern Source: https://docs.rs/arc-swap/latest/arc_swap/index.html Shows the recommended approach using ArcSwap to load the routing table atomically without locking. It provides better performance in both contended and non-contended scenarios. ```rust static ROUTING_TABLE: Lazy> = Lazy::new(|| { ArcSwap::from_pointee(RoutingTable) }); fn process_packet(packet: Packet) { let table = ROUTING_TABLE.load(); table.route(packet); } ``` -------------------------------- ### load Source: https://docs.rs/arc-swap/latest/arc_swap/type.ArcSwap.html Provides a temporary borrow of the object inside, returning a Guard proxy object. ```APIDOC ## Method: load ### Description Provides a temporary borrow of the object inside. This returns a proxy object allowing access to the thing held inside. However, there’s only limited amount of possible cheap proxies in existence for each thread ‒ if more are created, it falls back to equivalent of `load_full` internally. This is therefore a good choice to use for eg. searching a data structure or juggling the pointers around a bit, but not as something to store in larger amounts. The rule of thumb is this is suited for local variables on stack, but not in long-living data structures. ### Signature ```rust pub fn load(&self) -> Guard ``` ### Returns - **Guard** - A proxy object allowing access to the held value. ### Consistency In case multiple related operations are to be done on the loaded value, it is generally recommended to call `load` just once and keep the result over calling it multiple times. First, keeping it is usually faster. But more importantly, the value can change between the calls to load, returning different objects, which could lead to logical inconsistency. Keeping the result makes sure the same object is used. ``` -------------------------------- ### store Source: https://docs.rs/arc-swap/latest/arc_swap/struct.ArcSwapAny.html Replaces the value inside this instance. ```APIDOC ## store ### Description Replaces the value inside this instance. Further loads will yield the new value. Uses `swap` internally. ### Signature pub fn store(&self, val: T) ### Parameters - **val** (T) - Required - The new value to store. ``` -------------------------------- ### load_full Source: https://docs.rs/arc-swap/latest/arc_swap/struct.ArcSwapAny.html Loads the value by making another copy of the held pointer and returning it atomically. ```APIDOC ## load_full ### Description Loads the value. This makes another copy of the held pointer and returns it, atomically (it is safe even when other thread stores into the same instance at the same time). The method is lock-free and wait-free, but usually more expensive than `load`. ### Signature pub fn load_full(&self) -> T ### Returns - **T** - A copy of the held pointer. ``` -------------------------------- ### swap Source: https://docs.rs/arc-swap/latest/arc_swap/struct.ArcSwapAny.html Exchanges the value inside this instance. ```APIDOC ## swap ### Description Exchanges the value inside this instance. ### Signature pub fn swap(&self, new: T) -> T ### Parameters - **new** (T) - Required - The new value to store. ### Returns - **T** - The previous value. ``` -------------------------------- ### impl RefCnt for Option Source: https://docs.rs/arc-swap/latest/arc_swap/trait.RefCnt.html Implementation of RefCnt for Option, providing conversion between Option and raw pointers. ```APIDOC ## impl RefCnt for Option ### Description Provides RefCnt implementation for Option, allowing conversion between Option and raw pointers. ### Associated Type - **Base** = `::Base` ### Methods #### fn into_ptr(me: Option) -> *mut T::Base Converts an Option into a raw pointer. #### fn as_ptr(me: &Option) -> *mut T::Base Returns a raw pointer to the underlying value. #### unsafe fn from_ptr(ptr: *const T::Base) -> Option Reconstructs an Option from a raw pointer. Safety: The pointer must be valid and properly aligned. ``` -------------------------------- ### Consistent snapshot: load once and reuse Source: https://docs.rs/arc-swap/latest/arc_swap/docs/patterns/index.html Loads the configuration once and reuses the same value across multiple phases of a work chunk, ensuring the configuration does not change mid-processing. ```rust let work = Work::fetch(); let config = config.load(); work.phase_1(&config); // We keep the same config value here work.phase_2(&config); ``` -------------------------------- ### empty Source: https://docs.rs/arc-swap/latest/arc_swap/struct.ArcSwapAny.html A convenience constructor for an empty value. Equivalent to `ArcSwapOption::new(None)`. ```APIDOC ## empty ### Description A convenience constructor for an empty value. Equivalent to `ArcSwapOption::new(None)`. ### Method Constructor ### Signature `pub fn empty() -> Self` ``` -------------------------------- ### Using const_empty for static ArcSwapOption Source: https://docs.rs/arc-swap/latest/arc_swap/type.ArcSwapOption.html Demonstrates using const_empty to create a static ArcSwapOption that can be used in a const context. Shows loading and storing values. ```rust static GLOBAL_DATA: ArcSwapOption = ArcSwapOption::const_empty(); assert!(GLOBAL_DATA.load().is_none()); GLOBAL_DATA.store(Some(Arc::new(42))); assert_eq!(42, **GLOBAL_DATA.load().as_ref().unwrap()); ``` -------------------------------- ### impl RefCnt for Weak (feature weak) Source: https://docs.rs/arc-swap/latest/arc_swap/trait.RefCnt.html Implementation of RefCnt for Weak, available only with the weak feature, providing conversion between Weak and raw pointers. ```APIDOC ## impl RefCnt for Weak ### Description Provides RefCnt implementation for Weak, available only with the weak feature, allowing conversion between Weak and raw pointers. ### Associated Type - **Base** = `T` ### Methods #### fn as_ptr(me: &Self) -> *mut T Returns a raw pointer to the underlying value. #### fn into_ptr(me: Self) -> *mut T Converts a Weak into a raw pointer. #### unsafe fn from_ptr(ptr: *const T) -> Self Reconstructs a Weak from a raw pointer. Safety: The pointer must be valid and properly aligned. ``` -------------------------------- ### ArcSwapOption::empty Source: https://docs.rs/arc-swap/latest/arc_swap/type.ArcSwapOption.html Convenience constructor for an empty ArcSwapOption, equivalent to ArcSwapOption::new(None). ```APIDOC ## ArcSwapOption::empty ### Description Convenience constructor for an empty `ArcSwapOption`, equivalent to `ArcSwapOption::new(None)`. ### Method `pub fn empty() -> Self` ### Parameters None ### Return Value - `Self` - An `ArcSwapOption` holding `None`. ``` -------------------------------- ### from_pointee Source: https://docs.rs/arc-swap/latest/arc_swap/struct.ArcSwapAny.html A convenience constructor that creates an ArcSwapAny directly from a pointed-to value, equivalent to wrapping the value in an Arc. ```APIDOC ## from_pointee ### Description A convenience constructor directly from the pointed-to value. Direct equivalent for `ArcSwap::new(Arc::new(val))`. ### Method from_pointee ### Signature pub fn from_pointee(val: T) -> Self where S: Default ### Parameters - **val** (T) - Required - The value to store. ### Return Value - **Self** - The constructed ArcSwapAny instance. ``` -------------------------------- ### impl RefCnt for Pin> Source: https://docs.rs/arc-swap/latest/arc_swap/trait.RefCnt.html Implementation of RefCnt for Pin>, providing conversion between Pin> and raw pointers. ```APIDOC ## impl RefCnt for Pin> ### Description Provides RefCnt implementation for Pin>, allowing conversion between Pin> and raw pointers. ### Associated Type - **Base** = `T` ### Methods #### fn into_ptr(me: Pin>) -> *mut T Converts a Pin> into a raw pointer. #### fn as_ptr(me: &Pin>) -> *mut T Returns a raw pointer to the underlying value. #### unsafe fn from_ptr(ptr: *const T) -> Self Reconstructs a Pin> from a raw pointer. Safety: The pointer must be valid and properly aligned. ``` -------------------------------- ### ArcSwapOption::from_pointee Source: https://docs.rs/arc-swap/latest/arc_swap/type.ArcSwapOption.html Convenience constructor that directly creates an ArcSwapOption from a pointed-to value, allocating the Arc under the hood. ```APIDOC ## ArcSwapOption::from_pointee ### Description Convenience constructor that directly creates an `ArcSwapOption` from a pointed-to value, allocating the `Arc` under the hood. ### Method `pub fn from_pointee>>(val: V) -> Self` ### Parameters - **val** (`V`) - Required - The value to store, can be `None` or a value convertible to `Option`. ### Return Value - `Self` - An `ArcSwapOption` containing the given value. ### Example ```rust use arc_swap::ArcSwapOption; let empty: ArcSwapOption = ArcSwapOption::from_pointee(None); assert!(empty.load().is_none()); let non_empty: ArcSwapOption = ArcSwapOption::from_pointee(42); assert_eq!(42, **non_empty.load().as_ref().unwrap()); ``` ``` -------------------------------- ### RwLock> read pattern Source: https://docs.rs/arc-swap/latest/arc_swap/index.html Shows the traditional approach using RwLock> to read a routing table. It locks, clones the Arc, and unlocks, which suffers from CPU-level contention and may block updates under steady read inflow. ```rust static ROUTING_TABLE: Lazy>> = Lazy::new(|| { RwLock::new(Arc::new(RoutingTable)) }); fn process_packet(packet: Packet) { let table = Arc::clone(&ROUTING_TABLE.read().unwrap()); table.route(packet); } ``` -------------------------------- ### Display::fmt Source: https://docs.rs/arc-swap/latest/arc_swap/struct.ArcSwapAny.html Formats the value using the given formatter. ```APIDOC ## Display::fmt ### Description Formats the value using the given formatter. ### Method Trait method ### Signature `fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult` ``` -------------------------------- ### impl RefCnt for Rc Source: https://docs.rs/arc-swap/latest/arc_swap/trait.RefCnt.html Implementation of RefCnt for Rc, providing conversion between Rc and raw pointers. ```APIDOC ## impl RefCnt for Rc ### Description Provides RefCnt implementation for Rc, allowing conversion between Rc and raw pointers. ### Associated Type - **Base** = `T` ### Methods #### fn into_ptr(me: Rc) -> *mut T Converts an Rc into a raw pointer. #### fn as_ptr(me: &Rc) -> *mut T Returns a raw pointer to the underlying value. #### unsafe fn from_ptr(ptr: *const T) -> Rc Reconstructs an Rc from a raw pointer. Safety: The pointer must be valid and properly aligned. ```