### entry method example Source: https://docs.rs/polyvoice/latest/polyvoice/clusterer/assign/type.LocalGlobalDuration.html Gets the given key's corresponding entry in the map for in-place manipulation. The example counts character occurrences in a string using entry and and_modify/or_insert. ```rust use std::collections::HashMap; let mut letters = HashMap::new(); for ch in "a short treatise on fungi".chars() { letters.entry(ch).and_modify(|counter| *counter += 1).or_insert(1); } assert_eq!(letters[&'s'], 2); assert_eq!(letters[&'t'], 3); assert_eq!(letters[&'u'], 1); assert_eq!(letters.get(&'y'), None); ``` -------------------------------- ### StreamingPipeline with LatencyPreset example Source: https://docs.rs/polyvoice/latest/polyvoice/streaming/index.html Example of creating a `StreamingPipeline` with a `LatencyPreset::Balanced`, using `EnergyVad` and `DummyExtractor`. The pipeline feeds a 1-second chunk of audio and returns `SpeakerTurn`s. Note that `DummyExtractor` implements `Embedder` directly, and the example requires the `onnx` feature to be disabled for custom encoders. ```rust use polyvoice::streaming::{LatencyPreset, StreamingPipeline}; use polyvoice::{DummyExtractor, EnergyVad, VadConfig}; fn main() -> Result<(), Box> { let vad = EnergyVad::new(-40.0, 16000, 512); // DummyExtractor implements Embedder directly. let extractor = DummyExtractor::new(256); let mut pipeline = StreamingPipeline::with_latency_preset( vad, extractor, LatencyPreset::Balanced, VadConfig::default(), )?; let chunk = vec![0.0f32; 16000]; let _turns = pipeline.feed(&chunk)?; Ok(()) } ``` -------------------------------- ### Initialize EnergyVad Source: https://docs.rs/polyvoice/latest/polyvoice/vad/struct.EnergyVad.html Example showing how to create a new EnergyVad instance and verify its sample rate. ```rust use polyvoice::{EnergyVad, VoiceActivityDetector}; let vad = EnergyVad::new(-40.0, 16000, 512); assert_eq!(vad.sample_rate(), 16000); ``` -------------------------------- ### get method example Source: https://docs.rs/polyvoice/latest/polyvoice/clusterer/assign/type.LocalGlobalDuration.html Returns a reference to the value corresponding to the key. The key may be any borrowed form of the map's key type, but Hash and Eq on the borrowed form must match those for the key type. ```rust use std::collections::HashMap; let mut map = HashMap::new(); map.insert(1, "a"); assert_eq!(map.get(&1), Some(&"a")); assert_eq!(map.get(&2), None); ``` -------------------------------- ### remove_entry example Source: https://docs.rs/polyvoice/latest/polyvoice/clusterer/assign/type.LocalGlobalDuration.html Demonstrates using remove_entry to remove a key and return the stored key and value. The example is incomplete in the source, showing only the beginning of the code. ```rust use std::collections::HashMap; ``` -------------------------------- ### HashMap remove_entry example Source: https://docs.rs/polyvoice/latest/polyvoice/clusterer/assign/type.LocalGlobalDuration.html Demonstrates removing an entry from a HashMap using remove_entry and remove. The example creates a HashMap, inserts a key-value pair, and asserts the removal behavior. ```rust let mut map = HashMap::new(); map.insert(1, "a"); assert_eq!(map.remove_entry(&1), Some((1, "a"))); assert_eq!(map.remove(&1), None); ``` -------------------------------- ### hasher method example Source: https://docs.rs/polyvoice/latest/polyvoice/clusterer/assign/type.LocalGlobalDuration.html Returns a reference to the map's BuildHasher. The example creates a HashMap with a RandomState hasher and retrieves a reference to it. ```rust use std::collections::HashMap; use std::hash::RandomState; let hasher = RandomState::new(); let map: HashMap = HashMap::with_hasher(hasher); let hasher: &RandomState = map.hasher(); ``` -------------------------------- ### HashMap iteration example Source: https://docs.rs/polyvoice/latest/polyvoice/clusterer/assign/type.LocalGlobalDuration.html Shows how to create a HashMap from an array of key-value pairs and iterate over it using into_iter(). ```rust use std::collections::HashMap; let map = HashMap::from([ ("a", 1), ("b", 2), ("c", 3), ]); ``` -------------------------------- ### pub fn set_next_start(&mut self, start: usize) Source: https://docs.rs/polyvoice/latest/polyvoice/window/struct.WindowBuffer.html Sets the next-start offset to a specific value. ```APIDOC ## set_next_start ### Description Sets the next-start offset to a specific value. ### Method set_next_start ### Signature `pub fn set_next_start(&mut self, start: usize)` ### Parameters - **start** (usize) - Required - The new value for the next-start offset. ``` -------------------------------- ### Confidence::get example Source: https://docs.rs/polyvoice/latest/polyvoice/types/struct.Confidence.html Returns the raw confidence value. The example unwraps the `Option` from `new` and asserts equality. ```rust use polyvoice::Confidence; let c = Confidence::new(0.9).unwrap(); assert_eq!(c.get(), 0.9); ``` -------------------------------- ### insert example Source: https://docs.rs/polyvoice/latest/polyvoice/clusterer/assign/type.LocalGlobalDuration.html Shows how to insert a key-value pair into a HashMap. It demonstrates that insert returns None for a new key and Some(old_value) when updating an existing key. ```rust use std::collections::HashMap; let mut map = HashMap::new(); assert_eq!(map.insert(37, "a"), None); assert_eq!(map.is_empty(), false); map.insert(37, "b"); assert_eq!(map.insert(37, "c"), Some("b")); assert_eq!(map[&37], "c"); ``` -------------------------------- ### segment_speech usage example Source: https://docs.rs/polyvoice/latest/polyvoice/vad/fn.segment_speech.html An example demonstrating how to initialize an EnergyVad detector and use segment_speech to identify speech segments in a vector of audio samples. ```rust use polyvoice::{EnergyVad, segment_speech, DiarizationConfig, VadConfig}; let mut vad = EnergyVad::new(-40.0, 16000, 512); let samples = vec![0.5f32; 16000]; // 1 second of "loud" audio let config = DiarizationConfig::default(); let vad_config = VadConfig::default(); let segs = segment_speech(&mut vad, &samples, &config, &vad_config).unwrap(); assert!(!segs.is_empty()); assert!(segs.iter().all(|(s, e)| s < e)); ``` -------------------------------- ### From> for Arc example Source: https://docs.rs/polyvoice/latest/polyvoice/models/adapter/type.AdapterFactory.html Moves a boxed object into a new reference-counted allocation. The example converts a Box to Arc and asserts the content. ```rust let unique: Box = Box::from("eggplant"); let shared: Arc = Arc::from(unique); assert_eq!("eggplant", &shared[..]); ``` -------------------------------- ### HashMap from array example Source: https://docs.rs/polyvoice/latest/polyvoice/clusterer/assign/type.LocalGlobalDuration.html Shows how to create a HashMap from an array of key-value pairs using HashMap::from and the into() method, then asserts equality. ```rust let map1 = HashMap::from([(1, 2), (3, 4)]); let map2: HashMap<_, _> = [(1, 2), (3, 4)].into(); assert_eq!(map1, map2); ``` -------------------------------- ### get_mut example Source: https://docs.rs/polyvoice/latest/polyvoice/clusterer/assign/type.LocalGlobalDuration.html Demonstrates using get_mut to obtain a mutable reference to a value and modify it. The example inserts a key-value pair, modifies the value, and asserts the result. ```rust use std::collections::HashMap; let mut map = HashMap::new(); map.insert(1, "a"); if let Some(x) = map.get_mut(&1) { *x = "b"; } assert_eq!(map[&1], "b"); ``` -------------------------------- ### Test: reject_negative_or_non_finite_start Source: https://docs.rs/polyvoice/latest/src/polyvoice/rttm/mod.rs.html Verifies that negative, NaN, and infinite start times are rejected with an 'invalid start time' error message. ```rust #[test] fn reject_negative_or_non_finite_start() { let (_, reason) = parse_error("SPEAKER f 1 -0.5 1.0 A \n"); assert!(reason.contains("invalid start time: -0.5"), "{reason}"); // "NaN"/"inf" parse as f64 but fail the finite/non-negative check. let (_, reason) = parse_error("SPEAKER f 1 NaN 1.0 A \n"); assert!(reason.contains("invalid start time"), "{reason}"); let (_, reason) = parse_error("SPEAKER f 1 inf 1.0 A \n"); assert!(reason.contains("invalid start time"), "{reason}"); } ``` -------------------------------- ### strong_count_from_raw example Source: https://docs.rs/polyvoice/latest/polyvoice/models/adapter/type.AdapterFactory.html Shows how to get the strong count of an Arc from a raw pointer without consuming it. Requires the nightly feature arc_raw_get_strong. The pointer must point to a live Arc allocation with valid metadata. The example clones the Arc, converts to raw, and verifies the count is 2. ```rust #![feature(arc_raw_get_strong)] use std::sync::Arc; let five = Arc::new(5); let _also_five = Arc::clone(&five); let ptr = Arc::into_raw(five); unsafe { // This assertion is deterministic because we haven't shared // the `Arc` between threads. assert_eq!(2, Arc::strong_count_from_raw(ptr)); // Convert back to an `Arc` to avoid leaking memory. let five = Arc::from_raw(ptr); assert_eq!(2, Arc::strong_count(&five)); } ``` -------------------------------- ### Arc::get_mut example Source: https://docs.rs/polyvoice/latest/polyvoice/models/adapter/type.AdapterFactory.html Shows how to get a mutable reference to the inner value when there are no other Arc or Weak pointers. Returns None otherwise. The example demonstrates mutation and the effect of cloning. ```rust use std::sync::Arc; let mut x = Arc::new(3); *Arc::get_mut(&mut x).unwrap() = 4; assert_eq!(*x, 4); let _y = Arc::clone(&x); assert!(Arc::get_mut(&mut x).is_none()); ``` -------------------------------- ### HashMap::with_capacity_and_hasher() Example Source: https://docs.rs/polyvoice/latest/polyvoice/clusterer/assign/type.LocalGlobalDuration.html Creates an empty HashMap with at least the specified capacity using a custom hasher. This is a nightly-only experimental API. ```rust use std::collections::HashMap; use std::hash::RandomState; let s = RandomState::new(); let mut map = HashMap::with_capacity_and_hasher(10, s); map.insert(1, 2); ``` -------------------------------- ### with_capacity_and_hasher_in example Source: https://docs.rs/polyvoice/latest/polyvoice/clusterer/assign/type.LocalGlobalDuration.html Creates an empty HashMap with at least the specified capacity, using a custom hasher and allocator. Requires nightly feature allocator_api. Warning: manually setting the hasher can expose a DoS attack vector. ```rust #![feature(allocator_api)] use std::alloc::Global; use std::collections::HashMap; use std::hash::RandomState; let s = RandomState::new(); let map: HashMap = HashMap::with_capacity_and_hasher_in(10, s, Global); ``` -------------------------------- ### HashMap::new_in() Example (Nightly) Source: https://docs.rs/polyvoice/latest/polyvoice/clusterer/assign/type.LocalGlobalDuration.html Creates an empty HashMap using a given allocator. This is a nightly-only experimental API. ```rust use std::collections::HashMap; use std::alloc::Global; let map: HashMap = HashMap::new_in(Global); ``` -------------------------------- ### Arc::new_in example Source: https://docs.rs/polyvoice/latest/polyvoice/models/adapter/type.AdapterFactory.html Constructs a new Arc in a provided allocator. Requires the nightly feature allocator_api. The example uses the System allocator. ```rust #![feature(allocator_api)] use std::sync::Arc; use std::alloc::System; let five = Arc::new_in(5, System); ``` -------------------------------- ### Arc::strong_count example Source: https://docs.rs/polyvoice/latest/polyvoice/models/adapter/type.AdapterFactory.html Shows how to use Arc::strong_count to get the number of strong Arc pointers to an allocation. The assertion is deterministic only when the Arc is not shared between threads. ```rust use std::sync::Arc; let five = Arc::new(5); let _also_five = Arc::clone(&five); // This assertion is deterministic because we haven't shared // the `Arc` between threads. assert_eq!(2, Arc::strong_count(&five)); ``` -------------------------------- ### Arc::try_unwrap example Source: https://docs.rs/polyvoice/latest/polyvoice/models/adapter/type.AdapterFactory.html Shows how to use Arc::try_unwrap to get the inner value when there is exactly one strong reference, and how to handle the Err case when there are multiple references. ```rust use std::sync::Arc; let x = Arc::new(3); assert_eq!(Arc::try_unwrap(x), Ok(3)); let x = Arc::new(4); let _y = Arc::clone(&x); assert_eq!(*Arc::try_unwrap(x).unwrap_err(), 4); ``` -------------------------------- ### Arc::weak_count example Source: https://docs.rs/polyvoice/latest/polyvoice/models/adapter/type.AdapterFactory.html Shows how to use Arc::weak_count to get the number of Weak pointers to an allocation. The assertion is deterministic only when the Arc and Weak are not shared between threads. ```rust use std::sync::Arc; let five = Arc::new(5); let _weak_five = Arc::downgrade(&five); // This assertion is deterministic because we haven't shared // the `Arc` or `Weak` between threads. assert_eq!(1, Arc::weak_count(&five)); ``` -------------------------------- ### HashMap::with_capacity_in() Example (Nightly) Source: https://docs.rs/polyvoice/latest/polyvoice/clusterer/assign/type.LocalGlobalDuration.html Creates an empty HashMap with at least the specified capacity using the given allocator. This is a nightly-only experimental API. ```rust use std::collections::HashMap; use std::alloc::Global; let map: HashMap = HashMap::with_capacity_in(10, Global); ``` -------------------------------- ### Proptest configuration with 256 cases Source: https://docs.rs/polyvoice/latest/src/polyvoice/vad/mod.rs.html Starts a proptest block with a custom configuration of 256 cases. ```rust proptest! { #![proptest_config(ProptestConfig { cases: 256, ..ProptestConfig::default() })] ``` -------------------------------- ### get_disjoint_mut example with multiple keys Source: https://docs.rs/polyvoice/latest/polyvoice/clusterer/assign/type.LocalGlobalDuration.html Shows how to use get_disjoint_mut to obtain mutable references to multiple values at once. Demonstrates retrieving two existing keys, asserting the results, and handling a missing key by returning None. ```rust use std::collections::HashMap; let mut libraries = HashMap::new(); libraries.insert("Bodleian Library".to_string(), 1602); libraries.insert("Athenæum".to_string(), 1807); libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691); libraries.insert("Library of Congress".to_string(), 1800); // Get Athenæum and Bodleian Library let [Some(a), Some(b)] = libraries.get_disjoint_mut([ "Athenæum", "Bodleian Library", ]) else { panic!() }; // Assert values of Athenæum and Library of Congress let got = libraries.get_disjoint_mut([ "Athenæum", "Library of Congress", ]); assert_eq!( got, [ Some(&mut 1807), Some(&mut 1800), ], ); // Missing keys result in None let got = libraries.get_disjoint_mut([ "Athenæum", "New York Public Library", ]); assert_eq!( got, [ Some(&mut 1807), None ] ); ``` -------------------------------- ### From> for Arc example Source: https://docs.rs/polyvoice/latest/polyvoice/models/adapter/type.AdapterFactory.html Creates an atomically reference-counted pointer from a clone-on-write pointer by copying its content. The example converts a borrowed Cow to Arc. ```rust let cow: Cow<'_, str> = Cow::Borrowed("eggplant"); let shared: Arc = Arc::from(cow); assert_eq!("eggplant", &shared[..]); ``` -------------------------------- ### with_hasher_in example Source: https://docs.rs/polyvoice/latest/polyvoice/clusterer/assign/type.LocalGlobalDuration.html Creates an empty HashMap with a custom hash builder and allocator. Requires nightly feature allocator_api. Warning: manually setting the hash builder can expose a DoS attack vector. ```rust #![feature(allocator_api)] use std::alloc::Global; use std::collections::HashMap; use std::hash::RandomState; let s = RandomState::new(); let map: HashMap = HashMap::with_hasher_in(s, Global); ``` -------------------------------- ### HashMap::new() Example Source: https://docs.rs/polyvoice/latest/polyvoice/clusterer/assign/type.LocalGlobalDuration.html Creates an empty HashMap with a capacity of 0, which does not allocate until first insertion. ```rust use std::collections::HashMap; let mut map: HashMap<&str, i32> = HashMap::new(); ``` -------------------------------- ### remove example Source: https://docs.rs/polyvoice/latest/polyvoice/clusterer/assign/type.LocalGlobalDuration.html Shows how to remove a key from a HashMap using remove. It demonstrates that remove returns the value if the key was present, and None otherwise. ```rust use std::collections::HashMap; let mut map = HashMap::new(); map.insert(1, "a"); assert_eq!(map.remove(&1), Some("a")); assert_eq!(map.remove(&1), None); ``` -------------------------------- ### HashMap from array conversion example Source: https://docs.rs/polyvoice/latest/polyvoice/clusterer/assign/type.LocalGlobalDuration.html Shows converting an array of key-value pairs into a HashMap using the From implementation. If duplicate keys exist, all but one value are dropped. ```rust use std::collections::HashMap; ``` -------------------------------- ### run_with_clusterer with VbxClusterer example Source: https://docs.rs/polyvoice/latest/polyvoice/pipeline/struct.LegacyPipeline.html Example of using run_with_clusterer with a VbxClusterer loaded from a local PLDA directory. Requires the clusterer feature (and vbx for VbxClusterer). Embeddings come from the caller's Embedder; VBx restores scale via its configured emb_scale. Validates configuration first, returning InvalidConfig on failure. ```rust use polyvoice::{ EnergyVad, VadConfig, DiarizationConfig, clusterer::vbx::VbxClusterer, pipeline::LegacyPipeline, }; let vbx = VbxClusterer::from_dir(std::path::Path::new("plda/"), 20)?; let result = pipeline.run_with_clusterer(&samples, &embedder, &mut vad, &vbx)?; ``` -------------------------------- ### segment_speech usage example Source: https://docs.rs/polyvoice/latest/src/polyvoice/vad/mod.rs.html Example usage of segment_speech with an EnergyVad. Creates a 1-second loud audio buffer and asserts that the returned segments are non-empty and each start is less than its end. ```rust use polyvoice::{EnergyVad, segment_speech, DiarizationConfig, VadConfig}; let mut vad = EnergyVad::new(-40.0, 16000, 512); let samples = vec![0.5f32; 16000]; // 1 second of "loud" audio let config = DiarizationConfig::default(); let vad_config = VadConfig::default(); let segs = segment_speech(&mut vad, &samples, &config, &vad_config).unwrap(); assert!(!segs.is_empty()); assert!(segs.iter().all(|(s, e)| s < e)); ``` -------------------------------- ### HashMap::with_hasher() Example Source: https://docs.rs/polyvoice/latest/polyvoice/clusterer/assign/type.LocalGlobalDuration.html Creates an empty HashMap using a custom hash builder. Warning: setting the hasher manually can expose a DoS attack vector. ```rust use std::collections::HashMap; use std::hash::RandomState; let s = RandomState::new(); let mut map = HashMap::with_hasher(s); map.insert(1, 2); ``` -------------------------------- ### EnergyVad::new example Source: https://docs.rs/polyvoice/latest/src/polyvoice/vad/mod.rs.html Creates an EnergyVad with a -40 dB threshold, 16 kHz sample rate, and 512-sample frame size, then verifies the sample rate. The frame_size must be a positive multiple of the expected chunk size; passing 0 panics. ```rust use polyvoice::{EnergyVad, VoiceActivityDetector}; let vad = EnergyVad::new(-40.0, 16000, 512); assert_eq!(vad.sample_rate(), 16000); ``` -------------------------------- ### Create a validated SampleRate with SampleRate::new Source: https://docs.rs/polyvoice/latest/polyvoice/types/struct.SampleRate.html Example of using `SampleRate::new` to create a valid sample rate and checking that an out-of-range rate returns `None`. The `expect` call will panic if the rate is invalid. ```rust use polyvoice::SampleRate; let sr = SampleRate::new(16000).expect("valid rate"); assert_eq!(sr.get(), 16000); assert!(SampleRate::new(7000).is_none()); ``` -------------------------------- ### WindowIter::new Source: https://docs.rs/polyvoice/latest/src/polyvoice/window/mod.rs.html Creates a new WindowIter with the given total samples, window size, and hop size. Panics if win == 0, hop == 0, or hop > win. ```APIDOC ## WindowIter::new ### Description Creates a new iterator over (start, end) sample ranges. Panics if win == 0, hop == 0, or hop > win. Use try_new for a fallible alternative. ### Method pub fn new(total: usize, win: usize, hop: usize) -> Self ### Parameters - **total** (usize) - Required - Total number of samples in the audio region. - **win** (usize) - Required - Window size in samples. - **hop** (usize) - Required - Hop size in samples. ### Panics Panics if win == 0, hop == 0, or hop > win. ### Returns Self - A new WindowIter instance. ``` -------------------------------- ### From for Arc example Source: https://docs.rs/polyvoice/latest/polyvoice/models/adapter/type.AdapterFactory.html Converts a T into an Arc by moving the value into a newly allocated Arc, equivalent to Arc::new(t). The example compares the result of Arc::from(x) with Arc::new(5). ```rust let x = 5; let arc = Arc::new(5); assert_eq!(Arc::from(x), arc); ``` -------------------------------- ### GlobalGrid::from_windows - Compute global frame grid geometry Source: https://docs.rs/polyvoice/latest/src/polyvoice/segmentation/aggregator.rs.html Computes the global grid start, stride, and frame count from a slice of window outputs. Uses the first window's frame stride (clamped to a minimum of 1e-6) and the minimum start time and maximum end time across all windows. ```rust struct GlobalGrid { start: f32, stride: f32, frames: usize, } impl GlobalGrid { fn from_windows(windows: &[WindowOutput]) -> Self { let stride = windows[0].frame_stride().max(1e-6); let start = windows .iter() .map(|w| w.start_time) .fold(f32::INFINITY, f32::min); let end = windows .iter() .map(|w| w.end_time) .fold(f32::NEG_INFINITY, f32::max); let frames = ((end - start) / stride).ceil() as usize; Self { start, stride, frames, } } } ``` -------------------------------- ### Arc::is_unique example Source: https://docs.rs/polyvoice/latest/polyvoice/models/adapter/type.AdapterFactory.html Determines if the Arc is the unique reference. Returns true when no other Arc or Weak pointers exist. The example shows the effect of cloning and downgrading. ```rust #![feature(arc_is_unique)] use std::sync::Arc; let x = Arc::new(3); assert!(Arc::is_unique(&x)); let y = Arc::clone(&x); assert!(!Arc::is_unique(&x)); drop(y); // Weak references also count, because they could be upgraded at any time. let z = Arc::downgrade(&x); assert!(!Arc::is_unique(&x)); ``` -------------------------------- ### Ord implementation example for Arc Source: https://docs.rs/polyvoice/latest/polyvoice/models/adapter/type.AdapterFactory.html Compares two Arcs by calling cmp() on their inner values. The example asserts that Arc::new(5) is less than Arc::new(6). ```rust use std::sync::Arc; use std::cmp::Ordering; let five = Arc::new(5); assert_eq!(Ordering::Less, five.cmp(&Arc::new(6))); ``` -------------------------------- ### Create DummyExtractor and check dimension Source: https://docs.rs/polyvoice/latest/polyvoice/embedder/struct.DummyExtractor.html Example usage: creates a DummyExtractor with dimension 256 and asserts the dimension is 256. ```rust use polyvoice::{DummyExtractor, Embedder}; let extractor = DummyExtractor::new(256); assert_eq!(extractor.dim(), 256); ``` -------------------------------- ### pub fn new(win: usize, hop: usize) -> Self Source: https://docs.rs/polyvoice/latest/polyvoice/window/struct.WindowBuffer.html Creates a new WindowBuffer with the given window size and hop size. Panics if win is 0, hop is 0, or hop > win. ```APIDOC ## new ### Description Creates a new streaming buffer that accumulates samples and yields full windows. ### Method new ### Signature `pub fn new(win: usize, hop: usize) -> Self` ### Parameters - **win** (usize) - Required - Window size in samples. Must be greater than 0. - **hop** (usize) - Required - Hop size in samples. Must be greater than 0 and less than or equal to win. ### Panics Panics if `win == 0`, `hop == 0`, or `hop > win`. Use `try_new` for a fallible alternative. ``` -------------------------------- ### get_disjoint_unchecked_mut example Source: https://docs.rs/polyvoice/latest/polyvoice/clusterer/assign/type.LocalGlobalDuration.html Shows the unsafe usage of get_disjoint_unchecked_mut to get mutable references to multiple values without checking for overlapping keys. The example uses a SAFETY comment to assert that the keys are unique, and demonstrates retrieving two values. ```rust use std::collections::HashMap; let mut libraries = HashMap::new(); libraries.insert("Bodleian Library".to_string(), 1602); libraries.insert("Athenæum".to_string(), 1807); libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691); libraries.insert("Library of Congress".to_string(), 1800); // SAFETY: The keys do not overlap. let [Some(a), Some(b)] = (unsafe { libraries.get_disjoint_unchecked_mut([ "Athenæum", "Bodleian Library", ]) }) else { panic!() }; // SAFETY: The keys do not overlap. let got = unsafe { libraries.get_disjoint_unchecked_mut([ "Athenæum", "Library of Congress", ]) }; assert_eq!( got, [ Some(&mut 1807), Some(&mut 1800), ], ); ``` -------------------------------- ### Drop implementation example for Arc Source: https://docs.rs/polyvoice/latest/polyvoice/models/adapter/type.AdapterFactory.html Shows that dropping an Arc only prints when the strong reference count reaches zero. The example creates two clones and drops one without output, then drops the last one printing "dropped!". ```rust use std::sync::Arc; struct Foo; impl Drop for Foo { fn drop(&mut self) { println!("dropped!"); } } let foo = Arc::new(Foo); let foo2 = Arc::clone(&foo); drop(foo); // Doesn't print anything drop(foo2); // Prints "dropped!" ``` -------------------------------- ### Arc::get_mut_unchecked example Source: https://docs.rs/polyvoice/latest/polyvoice/models/adapter/type.AdapterFactory.html Demonstrates the unsafe method get_mut_unchecked, which returns a mutable reference without checks. Requires the nightly feature get_mut_unchecked. The example shows pushing to a String. ```rust #![feature(get_mut_unchecked)] use std::sync::Arc; let mut x = Arc::new(String::new()); unsafe { Arc::get_mut_unchecked(&mut x).push_str("foo") } assert_eq!(*x, "foo"); ``` -------------------------------- ### Arc::is_unique pointer invalidation example Source: https://docs.rs/polyvoice/latest/polyvoice/models/adapter/type.AdapterFactory.html Shows that is_unique does not invalidate pointers, unlike get_mut. The example holds a raw pointer and uses is_unique to safely dereference it. ```rust #![feature(arc_is_unique)] use std::sync::Arc; let arc = Arc::new(5); let pointer: *const i32 = &*arc; assert!(Arc::is_unique(&arc)); assert_eq!(unsafe { *pointer }, 5); ``` -------------------------------- ### new_uninit_in example Source: https://docs.rs/polyvoice/latest/polyvoice/models/adapter/type.AdapterFactory.html Constructs an Arc with uninitialized contents in the provided allocator. Requires nightly features allocator_api and get_mut_unchecked. Uses deferred initialization via get_mut_unchecked and assume_init. ```rust #![feature(get_mut_unchecked)] #![feature(allocator_api)] use std::sync::Arc; use std::alloc::System; let mut five = Arc::::new_uninit_in(System); let five = unsafe { // Deferred initialization: Arc::get_mut_unchecked(&mut five).as_mut_ptr().write(5); five.assume_init() }; assert_eq!(*five, 5) ``` -------------------------------- ### WindowBuffer len, empty, clear, and set_next_start test Source: https://docs.rs/polyvoice/latest/src/polyvoice/window/mod.rs.html Tests WindowBuffer's is_empty, len, set_next_start, try_pop, and clear methods. After setting next_start to 100, the popped window has start 100. ```rust let mut buf = WindowBuffer::new(4, 2); assert!(buf.is_empty()); assert_eq!(buf.len(), 0); buf.extend(&[1.0, 2.0]); assert!(!buf.is_empty()); assert_eq!(buf.len(), 2); buf.set_next_start(100); buf.extend(&[3.0, 4.0]); let (start, window) = buf.try_pop().unwrap(); assert_eq!(start, 100); assert_eq!(window, vec![1.0, 2.0, 3.0, 4.0]); buf.clear(); assert!(buf.is_empty()); assert!(buf.try_pop().is_none()); ``` -------------------------------- ### reserve method example Source: https://docs.rs/polyvoice/latest/polyvoice/clusterer/assign/type.LocalGlobalDuration.html Reserves capacity for at least additional more elements. After calling reserve, capacity will be greater than or equal to self.len() + additional. Does nothing if capacity is already sufficient. ```rust use std::collections::HashMap; let mut map: HashMap<&str, i32> = HashMap::new(); map.reserve(10); ``` -------------------------------- ### Get the raw sample rate value with SampleRate::get Source: https://docs.rs/polyvoice/latest/polyvoice/types/struct.SampleRate.html Example of using `SampleRate::get` to retrieve the raw sample rate value in Hz. The `unwrap` will panic if the rate is invalid. ```rust use polyvoice::SampleRate; let sr = SampleRate::new(44100).unwrap(); assert_eq!(sr.get(), 44100); ``` -------------------------------- ### try_insert example Source: https://docs.rs/polyvoice/latest/polyvoice/clusterer/assign/type.LocalGlobalDuration.html Demonstrates the nightly-only try_insert method. It shows that try_insert returns a mutable reference to the value on success, and an error containing the occupied entry, key, and value on failure. ```rust #![feature(map_try_insert)] use std::collections::HashMap; let mut map = HashMap::new(); assert_eq!(map.try_insert(37, "a").unwrap(), &"a"); let err = map.try_insert(37, "b").unwrap_err(); assert_eq!(err.entry.key(), &37); assert_eq!(err.entry.get(), &"a"); assert_eq!(err.key, 37); assert_eq!(err.value, "b"); ``` -------------------------------- ### Arc::unwrap_or_clone example Source: https://docs.rs/polyvoice/latest/polyvoice/models/adapter/type.AdapterFactory.html Shows that unwrap_or_clone returns the inner value without cloning when the Arc is unique, but clones when there are multiple references. The example uses pointer equality to verify whether cloning occurred. ```rust let inner = String::from("test"); let ptr = inner.as_ptr(); let arc = Arc::new(inner); let inner = Arc::unwrap_or_clone(arc); // The inner value was not cloned assert!(ptr::eq(ptr, inner.as_ptr())); let arc = Arc::new(inner); let arc2 = arc.clone(); let inner = Arc::unwrap_or_clone(arc); // Because there were 2 references, we had to clone the inner value. assert!(!ptr::eq(ptr, inner.as_ptr())); // `arc2` is the last reference, so when we unwrap it we get back // the original `String`. let inner = Arc::unwrap_or_clone(arc2); assert!(ptr::eq(ptr, inner.as_ptr())); ``` -------------------------------- ### Arc::get_mut_unchecked type mismatch example Source: https://docs.rs/polyvoice/latest/polyvoice/models/adapter/type.AdapterFactory.html Shows undefined behavior when other Arc pointers to the same allocation are not of the same type. The example uses Arc and Arc<[u8]> to illustrate the safety requirement. ```rust #![feature(get_mut_unchecked)] use std::sync::Arc; let x: Arc = Arc::from("Hello, world!"); let mut y: Arc<[u8]> = x.clone().into(); unsafe { // this is Undefined Behavior, because x's inner type is str, not [u8] Arc::get_mut_unchecked(&mut y).fill(0xff); // 0xff is invalid in UTF-8 } println!("{}", &*x); // Invalid UTF-8 in a str ``` -------------------------------- ### get_disjoint_mut panic on duplicate keys Source: https://docs.rs/polyvoice/latest/polyvoice/clusterer/assign/type.LocalGlobalDuration.html Demonstrates that calling get_disjoint_mut with duplicate keys causes a panic. The example inserts a single entry and then attempts to get mutable references for the same key twice, which triggers the panic. ```rust use std::collections::HashMap; let mut libraries = HashMap::new(); libraries.insert("Athenæum".to_string(), 1807); // Duplicate keys panic! let got = libraries.get_disjoint_mut([ "Athenæum", "Athenæum", ]); ``` -------------------------------- ### Arc::get_mut_unchecked lifetime mismatch example Source: https://docs.rs/polyvoice/latest/polyvoice/models/adapter/type.AdapterFactory.html Shows undefined behavior when other Arc pointers have different lifetimes. The example uses Arc<&str> with different lifetimes to illustrate the safety requirement. ```rust #![feature(get_mut_unchecked)] use std::sync::Arc; let x: Arc<&str> = Arc::new("Hello, world!"); { let s = String::from("Oh, no!"); let mut y: Arc<&str> = x.clone(); unsafe { // this is Undefined Behavior, because x's inner type // is &'long str, not &'short str *Arc::get_mut_unchecked(&mut y) = &s; } } println!("{}", &*x); // Use-after-free ``` -------------------------------- ### Arc::default example Source: https://docs.rs/polyvoice/latest/polyvoice/models/adapter/type.AdapterFactory.html Creates a new Arc with the Default value for T. Available on non-no_global_oom_handling only. ```rust use std::sync::Arc; let x: Arc = Default::default(); assert_eq!(*x, 0); ``` -------------------------------- ### decrement_strong_count example Source: https://docs.rs/polyvoice/latest/polyvoice/models/adapter/type.AdapterFactory.html Shows how to manually decrement the strong count of an Arc using a raw pointer obtained from Arc::into_raw. The pointer must be valid and the strong count at least 1. The example increments the count first, then decrements it, verifying the count changes as expected. ```rust use std::sync::Arc; let five = Arc::new(5); unsafe { let ptr = Arc::into_raw(five); Arc::increment_strong_count(ptr); // Those assertions are deterministic because we haven't shared // the `Arc` between threads. let five = Arc::from_raw(ptr); assert_eq!(2, Arc::strong_count(&five)); Arc::decrement_strong_count(ptr); assert_eq!(1, Arc::strong_count(&five)); } ``` -------------------------------- ### WindowBuffer::new Source: https://docs.rs/polyvoice/latest/src/polyvoice/window/mod.rs.html Creates a new WindowBuffer with the given window and hop sizes. Panics if the parameters are invalid. ```APIDOC ## WindowBuffer::new ### Description Creates a new WindowBuffer with the specified window size and hop size. Panics if the window geometry is invalid (win == 0, hop == 0, or hop > win). ### Method `pub fn new(win: usize, hop: usize) -> Self` ### Parameters - **win** (usize) - Required - Window size in samples (must be > 0). - **hop** (usize) - Required - Hop size in samples (must be > 0 and <= win). ### Returns - **Self** - A new WindowBuffer instance. ### Errors Panics with a message from WindowError if the parameters are invalid. ``` -------------------------------- ### TimeRange duration method example Source: https://docs.rs/polyvoice/latest/polyvoice/types/struct.TimeRange.html Example usage of the `duration` method, which returns the duration of the time range in seconds. The example creates a `TimeRange` and asserts the duration equals 2.5. ```rust use polyvoice::TimeRange; let tr = TimeRange { start: 1.0, end: 3.5 }; assert_eq!(tr.duration(), 2.5); ``` -------------------------------- ### Confidence::new example Source: https://docs.rs/polyvoice/latest/polyvoice/types/struct.Confidence.html Creates a validated confidence score. Returns `None` if the input is outside [0.0, 1.0]. ```rust use polyvoice::Confidence; assert!(Confidence::new(0.75).is_some()); assert!(Confidence::new(1.5).is_none()); ``` -------------------------------- ### Usage Example: merge_segments Source: https://docs.rs/polyvoice/latest/polyvoice/utils/fn.merge_segments.html Example usage of `merge_segments` with a vector of segments, demonstrating merging adjacent segments with the same speaker when the gap is less than 0.5 seconds. The example asserts the merged length and the end time of the first merged segment. ```rust use polyvoice::{merge_segments, Segment, SpeakerId, TimeRange}; let segs = vec![ Segment { time: TimeRange { start: 0.0, end: 1.0 }, speaker: Some(SpeakerId(0)), confidence: Some(0.8) }, Segment { time: TimeRange { start: 1.2, end: 2.0 }, speaker: Some(SpeakerId(0)), confidence: Some(0.9) }, Segment { time: TimeRange { start: 2.5, end: 3.0 }, speaker: Some(SpeakerId(1)), confidence: None }, ]; let merged = merge_segments(segs, 0.5); assert_eq!(merged.len(), 2); assert!((merged[0].time.end - 2.0).abs() < 1e-5); ``` -------------------------------- ### try_new_zeroed_in example Source: https://docs.rs/polyvoice/latest/polyvoice/models/adapter/type.AdapterFactory.html Constructs an Arc with uninitialized contents filled with 0 bytes in the provided allocator, returning an error if allocation fails. Requires nightly feature allocator_api. Uses assume_init to complete initialization. ```rust #![feature(allocator_api)] use std::sync::Arc; use std::alloc::System; let zero = Arc::::try_new_zeroed_in(System)?; let zero = unsafe { zero.assume_init() }; assert_eq!(*zero, 0); ``` -------------------------------- ### Arc::clone example Source: https://docs.rs/polyvoice/latest/polyvoice/models/adapter/type.AdapterFactory.html Creates another pointer to the same allocation, increasing the strong reference count. ```rust use std::sync::Arc; let five = Arc::new(5); let _ = Arc::clone(&five); ``` -------------------------------- ### HashMap::with_capacity() Example Source: https://docs.rs/polyvoice/latest/polyvoice/clusterer/assign/type.LocalGlobalDuration.html Creates an empty HashMap with at least the specified capacity, allowing it to hold that many elements without reallocating. ```rust use std::collections::HashMap; let mut map: HashMap<&str, i32> = HashMap::with_capacity(10); ``` -------------------------------- ### WindowBuffer::new Source: https://docs.rs/polyvoice/latest/src/polyvoice/window/mod.rs.html Creates a new WindowBuffer with the given window and hop sizes. Panics if win == 0, hop == 0, or hop > win. ```APIDOC ## WindowBuffer::new ### Description Create a new buffer. Panics if win == 0, hop == 0, or hop > win. Use try_new for a fallible alternative. ### Method pub fn new(win: usize, hop: usize) -> Self ### Parameters - **win** (usize) - Required - Window size in samples. - **hop** (usize) - Required - Hop size in samples. ### Panics Panics if win == 0, hop == 0, or hop > win. ### Returns Self - A new WindowBuffer instance. ``` -------------------------------- ### WindowIter property test start less than end Source: https://docs.rs/polyvoice/latest/src/polyvoice/window/mod.rs.html Property test for WindowIter that checks all yielded (start, end) pairs satisfy start < end. Uses proptest with 1000 cases and random total, win, hop, and include_partial values. ```rust proptest! { #![proptest_config(ProptestConfig { cases: 1000, ..ProptestConfig::default() })] /// All yielded (start, end) pairs satisfy start < end. #[test] fn window_iter_start_less_than_end( total in 0usize..10000, (win, hop) in (1usize..5000) .prop_flat_map(|w| (Just(w), 1usize..=w)), include_partial in any::(), ) { let iter = if include_partial { WindowIter::new(total, win, hop).include_partial() } else { WindowIter::new(total, win, hop) }; for (start, end) in iter { ``` -------------------------------- ### new_zeroed_in example Source: https://docs.rs/polyvoice/latest/polyvoice/models/adapter/type.AdapterFactory.html Constructs an Arc with uninitialized contents filled with 0 bytes in the provided allocator. Requires nightly feature allocator_api. Uses assume_init to complete initialization. ```rust #![feature(allocator_api)] use std::sync::Arc; use std::alloc::System; let zero = Arc::::new_zeroed_in(System); let zero = unsafe { zero.assume_init() }; assert_eq!(*zero, 0) ``` -------------------------------- ### LegacyPipeline::run Source: https://docs.rs/polyvoice/latest/polyvoice/pipeline/struct.LegacyPipeline.html Runs the full diarization pipeline on raw f32 samples. ```APIDOC ## LegacyPipeline::run ### Description Runs the full diarization pipeline on raw f32 samples. The `extractor` must implement `Embedder` (the supported BYO surface). Clustering defaults to free AHC (cosine threshold from `DiarizationConfig::cluster`). For a pluggable backend (VBx from a local PLDA directory, NME-SC, …) use `Self::run_with_clusterer` (feature `clusterer`). ### Method `pub fn run(&self, samples: &[f32], extractor: &E, vad: &mut V) -> Result` ### Parameters - `samples` (&[f32]) - Required - Raw audio samples. - `extractor` (&E) - Required - The embedder implementation. - `vad` (&mut V) - Required - The voice activity detector implementation. ### Returns - `Result` - The diarization result or an error. ### Errors - `LegacyPipelineError::InvalidConfig` - If `DiarizationConfig::validate` rejects the configuration (a zero or inverted window geometry previously panicked inside the window iterator). - `LegacyPipelineError::AudioTooLong` - If the input exceeds `config.max_duration_secs` (default 1 hour). ``` -------------------------------- ### Arc::clone_from_ref Example Source: https://docs.rs/polyvoice/latest/polyvoice/models/adapter/type.AdapterFactory.html Constructs a new Arc with a clone of the value. Requires the nightly-only clone_from_ref feature. ```rust #![feature(clone_from_ref)] use std::sync::Arc; let hello: Arc = Arc::clone_from_ref("hello"); ``` -------------------------------- ### Arc less-than-or-equal comparison with le Source: https://docs.rs/polyvoice/latest/polyvoice/models/adapter/type.AdapterFactory.html Example for PartialOrd::le on Arc. Compares by calling <= on inner values. ```rust use std::sync::Arc; let five = Arc::new(5); assert!(five <= Arc::new(5)); ``` -------------------------------- ### try_reserve method example Source: https://docs.rs/polyvoice/latest/polyvoice/clusterer/assign/type.LocalGlobalDuration.html Tries to reserve capacity for at least additional more elements. Returns an error if capacity overflows or the allocator reports a failure. ```rust use std::collections::HashMap; let mut map: HashMap<&str, isize> = HashMap::new(); map.try_reserve(10).expect("why is the test harness OOMing on a handful of bytes?"); ``` -------------------------------- ### Arc partial comparison with partial_cmp Source: https://docs.rs/polyvoice/latest/polyvoice/models/adapter/type.AdapterFactory.html Example for PartialOrd::partial_cmp on Arc. Compares by calling partial_cmp() on inner values. ```rust use std::sync::Arc; use std::cmp::Ordering; let five = Arc::new(5); assert_eq!(Some(Ordering::Less), five.partial_cmp(&Arc::new(6))); ``` -------------------------------- ### EmbedderPool::new constructor doc example Source: https://docs.rs/polyvoice/latest/src/polyvoice/embedder/mod.rs.html Documented behavior for building a pool from a list of embedders. All must share the same dim(), an empty list is allowed, and is_empty is true; embed calls fail when empty. ```rust pub fn new(embedders: Vec) -> Result ``` ```rust ret.is_ok() => ret.as_ref().unwrap().dim() == embedders.first().map_or(0, |e| e.dim()) ``` -------------------------------- ### Usage example for mean_vector Source: https://docs.rs/polyvoice/latest/polyvoice/utils/fn.mean_vector.html Example usage of `mean_vector` from `polyvoice::utils`, demonstrating how to compute the mean of two vectors and assert the results. ```rust use polyvoice::utils::mean_vector; let vectors = vec![vec![1.0, 2.0], vec![3.0, 4.0]]; let mean = mean_vector(&vectors).unwrap(); assert!((mean[0] - 2.0).abs() < 1e-5); assert!((mean[1] - 3.0).abs() < 1e-5); ``` -------------------------------- ### Arc greater-than-or-equal comparison with ge Source: https://docs.rs/polyvoice/latest/polyvoice/models/adapter/type.AdapterFactory.html Example for PartialOrd::ge on Arc. Compares by calling >= on inner values. ```rust use std::sync::Arc; let five = Arc::new(5); assert!(five >= Arc::new(5)); ``` -------------------------------- ### Arc less-than comparison with lt Source: https://docs.rs/polyvoice/latest/polyvoice/models/adapter/type.AdapterFactory.html Example for PartialOrd::lt on Arc. Compares by calling < on inner values. ```rust use std::sync::Arc; let five = Arc::new(5); assert!(five < Arc::new(6)); ``` -------------------------------- ### Arc greater-than comparison with gt Source: https://docs.rs/polyvoice/latest/polyvoice/models/adapter/type.AdapterFactory.html Example for PartialOrd::gt on Arc. Compares by calling > on inner values. ```rust use std::sync::Arc; let five = Arc::new(5); assert!(five > Arc::new(4)); ```