### Option::cloned Example Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/closest_edge_query/type.ShapeFilter.html Demonstrates cloning the contents of an Option containing a reference. ```rust let x = 12; let opt_x = Some(&x); assert_eq!(opt_x, Some(&12)); let cloned = opt_x.cloned(); assert_eq!(cloned, Some(12)); ``` -------------------------------- ### Option::copied Example Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/closest_edge_query/type.ShapeFilter.html Demonstrates copying the contents of an Option containing a reference. ```rust let x = 12; let opt_x = Some(&x); assert_eq!(opt_x, Some(&12)); let copied = opt_x.copied(); assert_eq!(copied, Some(12)); ``` -------------------------------- ### Option::as_ref Example Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/closest_edge_query/type.ShapeFilter.html Converts an Option to an Option<&T>. ```rust let text: Option = Some("Hello, world!".to_string()); // First, cast `Option` to `Option<&String>` with `as_ref`, // then consume *that* with `map`, leaving `text` on the stack. let text_length: Option = text.as_ref().map(|s| s.len()); println!("still can print text: {text:?}"); ``` -------------------------------- ### Arc::clone_from_ref Example Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/builder/layer/type.IsFullPolygonPredicate.html Demonstrates constructing an Arc from a reference using the experimental clone_from_ref API. ```rust #![feature(clone_from_ref)] use std::sync::Arc; let hello: Arc = Arc::clone_from_ref("hello"); ``` -------------------------------- ### Hash Implementation for Vec Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/builder/lax_polygon_layer/type.LabelSetIds.html Example showing the import required for hashing vectors. ```rust use std::hash::BuildHasher; ``` -------------------------------- ### Rect Usage Examples Source: https://docs.rs/s2rst/0.4.0/s2rst/r2/struct.Rect.html Demonstrates creating a rectangle from points, testing point containment, and handling empty rectangles. ```rust use s2rst::r2::{Point, Rect}; // Create a rectangle from corner points. let r = Rect::from_points(Point::new(1.0, 2.0), Point::new(4.0, 6.0)); assert_eq!(r.size(), Point::new(3.0, 4.0)); assert_eq!(r.center(), Point::new(2.5, 4.0)); // Containment test. assert!(r.contains_point(Point::new(2.0, 3.0))); assert!(!r.contains_point(Point::new(5.0, 3.0))); // Empty rectangle. assert!(Rect::empty().is_empty()); ``` -------------------------------- ### Interval Usage Examples Source: https://docs.rs/s2rst/0.4.0/s2rst/r1/struct.Interval.html Demonstrates creating intervals, performing containment tests, calculating intersections, and handling empty intervals. ```rust use s2rst::r1::Interval; // Create an interval [2, 5]. let i = Interval::new(2.0, 5.0); assert_eq!(i.length(), 3.0); assert_eq!(i.center(), 3.5); // Containment tests. assert!(i.contains(3.0)); assert!(!i.contains(6.0)); // Intersection of [2, 5] and [3, 7] is [3, 5]. let j = Interval::new(3.0, 7.0); let inter = i.intersection(j); assert_eq!(inter.lo, 3.0); assert_eq!(inter.hi, 5.0); // Empty interval. assert!(Interval::empty().is_empty()); ``` -------------------------------- ### Vector Capacity and Allocation Examples Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/builder/lax_polygon_layer/type.LabelSetIds.html Demonstrates how vector capacity behaves during push operations and the behavior of zero-sized types. ```rust // The vector contains no items, even though it has capacity for more assert_eq!(vec.len(), 0); assert!(vec.capacity() >= 10); // These are all done without reallocating... for i in 0..10 { vec.push(i); } assert_eq!(vec.len(), 10); assert!(vec.capacity() >= 10); // ...but this may make the vector reallocate vec.push(11); assert_eq!(vec.len(), 11); assert!(vec.capacity() >= 11); // A vector of a zero-sized type will always over-allocate, since no // allocation is necessary let vec_units = Vec::<(), System>::with_capacity_in(10, System); assert_eq!(vec_units.capacity(), usize::MAX); ``` -------------------------------- ### Angle Usage Examples Source: https://docs.rs/s2rst/0.4.0/s2rst/s1/struct.Angle.html Demonstrates creating angles from degrees, performing arithmetic, and converting between different angle representations. ```rust use s2rst::s1::Angle; // Create from degrees and radians let a = Angle::from_degrees(90.0); assert!((a.radians() - std::f64::consts::FRAC_PI_2).abs() < 1e-15); // Arithmetic let b = Angle::from_degrees(45.0); let sum = a + b; assert!((sum.degrees() - 135.0).abs() < 1e-13); // E6/E7 conversions assert_eq!(Angle::from_degrees(12.345678).e6(), 12345678); assert_eq!(Angle::from_e7(900000000).degrees(), 90.0); ``` -------------------------------- ### Usage examples for ChordAngle Source: https://docs.rs/s2rst/0.4.0/s2rst/s1/struct.ChordAngle.html Demonstrates creating ChordAngle from angles or points and performing efficient comparisons. ```rust use s2rst::s1::{Angle, ChordAngle}; use s2rst::s2::Point; // Create from an Angle let ca = ChordAngle::from_angle(Angle::from_degrees(90.0)); assert!((ca.degrees() - 90.0).abs() < 1e-13); // Create from two points on the unit sphere let p = Point::from_coords(1.0, 0.0, 0.0); let q = Point::from_coords(0.0, 1.0, 0.0); let ca2 = p.chord_angle(q); assert!((ca2.length2() - 2.0).abs() < 1e-15); // 90 degrees = length2 of 2 // Comparisons are efficient (no trig needed) assert!(ChordAngle::RIGHT < ChordAngle::STRAIGHT); ``` -------------------------------- ### Indexing with Axis Source: https://docs.rs/s2rst/0.4.0/s2rst/r3/enum.Axis.html Example demonstrating how to use the Axis enum to index into a Vector. ```rust use s2rst::r3::{Axis, Vector}; let v = Vector::new(1.0, 2.0, 3.0); assert_eq!(v[Axis::X], 1.0); assert_eq!(v[Axis::Y], 2.0); assert_eq!(v[Axis::Z], 3.0); ``` -------------------------------- ### Use Interval operations Source: https://docs.rs/s2rst/0.4.0/s2rst/s1/struct.Interval.html Examples demonstrating interval creation, containment checks, and handling of inverted or full-circle intervals. ```rust use std::f64::consts::PI; use s2rst::s1::Interval; // A simple interval from 0 to π/2 (first quadrant). let i = Interval::new(0.0, PI / 2.0); assert!(!i.is_empty()); assert!(i.contains(PI / 4.0)); assert!(!i.contains(PI)); // An inverted interval that wraps through -π/π. let wrap = Interval::new(3.0, -3.0); assert!(wrap.is_inverted()); assert!(wrap.contains(PI)); // π is between 3.0 and -3.0 the "long way" // The full circle. let full = Interval::full(); assert!(full.is_full()); assert_eq!(full.length(), 2.0 * PI); ``` -------------------------------- ### Use Point for geometric calculations Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/struct.Point.html Example demonstrating point creation, unit verification, and distance calculation between two points. ```rust use s2rst::s2::Point; let p = Point::from_coords(1.0, 0.0, 0.0); assert!(p.is_unit()); assert_eq!(p.x(), 1.0); // Distance between two points let q = Point::from_coords(0.0, 1.0, 0.0); let dist = p.distance(q); assert!((dist.radians() - std::f64::consts::FRAC_PI_2).abs() < 1e-15); ``` -------------------------------- ### Matrix3x3 Usage Examples Source: https://docs.rs/s2rst/0.4.0/s2rst/r3/matrix/struct.Matrix3x3.html Demonstrates creating an identity matrix, performing vector multiplication, and constructing a matrix from column vectors for rotation. ```rust use s2rst::r3::{Matrix3x3, Vector}; // The identity matrix leaves vectors unchanged. let id = Matrix3x3::identity(); let v = Vector::new(1.0, 2.0, 3.0); assert_eq!(id * v, v); // Build a matrix from column vectors and multiply. let m = Matrix3x3::from_cols( Vector::new(0.0, 1.0, 0.0), Vector::new(-1.0, 0.0, 0.0), Vector::new(0.0, 0.0, 1.0), ); // This rotates 90° around Z: (1,0,0) → (0,1,0). let rotated = m * Vector::new(1.0, 0.0, 0.0); assert!((rotated.x - 0.0).abs() < 1e-15); assert!((rotated.y - 1.0).abs() < 1e-15); ``` -------------------------------- ### Option::as_mut Example Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/closest_edge_query/type.ShapeFilter.html Converts an Option to an Option<&mut T>. ```rust let mut x = Some(2); match x.as_mut() { Some(v) => *v = 42, None => {}, } assert_eq!(x, Some(42)); ``` -------------------------------- ### Arc::try_clone_from_ref Example Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/builder/layer/type.IsFullPolygonPredicate.html Demonstrates constructing an Arc from a reference with error handling for allocation failures. ```rust #![feature(clone_from_ref)] #![feature(allocator_api)] use std::sync::Arc; let hello: Arc = Arc::try_clone_from_ref("hello")?; ``` -------------------------------- ### Option::is_none_or Example Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/closest_edge_query/type.ShapeFilter.html Checks if an Option is None or matches a predicate. ```rust let x: Option = Some(2); assert_eq!(x.is_none_or(|x| x > 1), true); let x: Option = Some(0); assert_eq!(x.is_none_or(|x| x > 1), false); let x: Option = None; assert_eq!(x.is_none_or(|x| x > 1), true); let x: Option = Some("ownership".to_string()); assert_eq!(x.as_ref().is_none_or(|x| x.len() > 1), true); println!("still alive {:?}", x); ``` -------------------------------- ### Chain::new Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/shape/struct.Chain.html Creates a new Chain instance with a specified start edge ID and length. ```APIDOC ## pub fn new(start: usize, length: usize) -> Self ### Description Creates a new chain representing a contiguous range of edge IDs. ### Parameters - **start** (usize) - The first edge ID in this chain. - **length** (usize) - The number of edges in this chain. ### Returns - **Self** - A new Chain instance. ``` -------------------------------- ### Check slice prefix Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/lax_polyline/struct.LaxPolyline.html Verifies if a slice starts with a specific sequence. ```rust let v = [10, 40, 30]; assert!(v.starts_with(&[10])); assert!(v.starts_with(&[10, 40])); assert!(v.starts_with(&v)); assert!(!v.starts_with(&[50])); assert!(!v.starts_with(&[10, 50])); ``` ```rust let v = &[10, 40, 30]; assert!(v.starts_with(&[])); let v: &[u8] = &[]; assert!(v.starts_with(&[])); ``` -------------------------------- ### Recycle buffer pattern Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/builder/lax_polygon_layer/type.LabelSetIds.html Example of reusing a buffer from storage to process input strings. ```rust for input in inputs { let mut buffer: Vec<&str> = storage.recycle(); buffer.extend(input.split(" ")); process(&buffer); storage = buffer.recycle(); } ``` -------------------------------- ### LoopOrder::new Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/loop_measures/struct.LoopOrder.html Creates a new instance of LoopOrder with the specified starting vertex and traversal direction. ```APIDOC ## LoopOrder::new(first: i32, dir: i32) -> Self ### Description Creates a new `LoopOrder` instance with the given starting vertex index and direction of traversal. ### Parameters - **first** (i32) - The index of the starting vertex. - **dir** (i32) - The direction of traversal (+1 or -1). ``` -------------------------------- ### Creating contiguous windows Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/lax_polyline/struct.LaxPolyline.html Examples of using windows to iterate over overlapping segments of a slice, including handling cases where the slice is shorter than the window size and using Cell for mutation. ```rust let slice = ['l', 'o', 'r', 'e', 'm']; let mut iter = slice.windows(3); assert_eq!(iter.next().unwrap(), &['l', 'o', 'r']); assert_eq!(iter.next().unwrap(), &['o', 'r', 'e']); assert_eq!(iter.next().unwrap(), &['r', 'e', 'm']); assert!(iter.next().is_none()); ``` ```rust let slice = ['f', 'o', 'o']; let mut iter = slice.windows(4); assert!(iter.next().is_none()); ``` ```rust use std::cell::Cell; let mut array = ['R', 'u', 's', 't', ' ', '2', '0', '1', '5']; let slice = &mut array[..]; let slice_of_cells: &[Cell] = Cell::from_mut(slice).as_slice_of_cells(); for w in slice_of_cells.windows(3) { Cell::swap(&w[0], &w[2]); } assert_eq!(array, ['s', 't', ' ', '2', '0', '1', '5', 'u', 'R']); ``` -------------------------------- ### Constructing and Using S2Builder Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/builder/struct.S2Builder.html Demonstrates initializing an S2Builder with default options, adding edges to a polyline layer, and extracting the processed output. ```rust use s2rst::s2::builder::{Options, S2Builder}; use s2rst::s2::builder::polyline_vector_layer::S2PolylineVectorLayer; use s2rst::s2::LatLng; // Create a builder with default (identity snap) options. let mut builder = S2Builder::new(Options::default()); builder.start_layer(Box::new(S2PolylineVectorLayer::new())); // Add edges forming a polyline. let p0 = LatLng::from_degrees(0.0, 0.0).to_point(); let p1 = LatLng::from_degrees(1.0, 0.0).to_point(); let p2 = LatLng::from_degrees(2.0, 0.0).to_point(); builder.add_edge(p0, p1); builder.add_edge(p1, p2); // Build and extract the layer output. let mut layers = builder.build().expect("build should succeed"); let layer = layers.remove(0) .into_any() .downcast::() .expect("wrong layer type"); let result = layer.into_output(); assert_eq!(result.len(), 1); // one polyline assert_eq!(result[0].num_vertices(), 3); // three vertices ``` -------------------------------- ### Option::is_none Example Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/closest_edge_query/type.ShapeFilter.html Checks if an Option is None. ```rust let x: Option = Some(2); assert_eq!(x.is_none(), false); let x: Option = None; assert_eq!(x.is_none(), true); ``` -------------------------------- ### Option::is_some_and Example Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/closest_edge_query/type.ShapeFilter.html Checks if an Option is Some and matches a predicate. ```rust let x: Option = Some(2); assert_eq!(x.is_some_and(|x| x > 1), true); let x: Option = Some(0); assert_eq!(x.is_some_and(|x| x > 1), false); let x: Option = None; assert_eq!(x.is_some_and(|x| x > 1), false); let x: Option = Some("ownership".to_string()); assert_eq!(x.as_ref().is_some_and(|x| x.len() > 1), true); println!("still alive {:?}", x); ``` -------------------------------- ### Initialize and build a CellIndex Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/cell_index/struct.CellIndex.html Demonstrates the standard workflow of creating a new index, adding entries, and finalizing the structure with build(). ```rust let mut index = CellIndex::new(); index.add(cell_id_1, 0); index.add(cell_id_2, 1); index.build(); ``` -------------------------------- ### Option::is_some Example Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/closest_edge_query/type.ShapeFilter.html Checks if an Option contains a value. ```rust let x: Option = Some(2); assert_eq!(x.is_some(), true); let x: Option = None; assert_eq!(x.is_some(), false); ``` -------------------------------- ### Create and build a ShapeIndex Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/shape_index/struct.ShapeIndex.html Demonstrates initializing a ShapeIndex, adding a LaxLoop shape, building the index, and iterating over its cells. ```rust use s2rst::s2::shape_index::ShapeIndex; use s2rst::s2::lax_loop::LaxLoop; use s2rst::s2::LatLng; // Create a triangle as a LaxLoop shape. let vertices = vec![ LatLng::from_degrees(0.0, 0.0).to_point(), LatLng::from_degrees(0.0, 10.0).to_point(), LatLng::from_degrees(10.0, 0.0).to_point(), ]; let shape = LaxLoop::new(vertices); // Build the spatial index. let mut index = ShapeIndex::new(); index.add(Box::new(shape)); index.build(); assert_eq!(index.len(), 1); assert_eq!(index.num_edges(), 3); // Iterate over index cells. let mut it = index.iter(); let mut cell_count = 0; while !it.done() { cell_count += 1; it.next(); } assert!(cell_count > 0); ``` -------------------------------- ### Arc::weak_count Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/builder/layer/type.IsFullPolygonPredicate.html Gets the number of Weak pointers to this allocation. ```APIDOC ## pub fn weak_count(this: &Arc) -> usize ### Description Gets the number of `Weak` pointers to this allocation. Note that another thread can change the weak count at any time. ``` -------------------------------- ### Create and inspect a LaxPolyline Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/lax_polyline/struct.LaxPolyline.html Demonstrates initializing a LaxPolyline from a vector of points and verifying its properties. ```rust use s2rst::s2::lax_polyline::LaxPolyline; use s2rst::s2::shape::{Dimension, Shape}; use s2rst::s2::LatLng; let line = LaxPolyline::new(vec![ LatLng::from_degrees(0.0, 0.0).to_point(), LatLng::from_degrees(1.0, 0.0).to_point(), LatLng::from_degrees(2.0, 0.0).to_point(), ]); assert_eq!(line.num_edges(), 2); assert_eq!(line.dimension(), Dimension::Polyline); ``` -------------------------------- ### Construct an empty Vec Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/builder/lax_polygon_layer/type.LabelSetIds.html Example of creating a new, empty vector. ```rust let mut vec: Vec = Vec::new(); ``` -------------------------------- ### Mutate BTreeMap Values Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/incident_edge_tracker/type.IncidentEdgeMap.html Get a mutable iterator over the values of the map. ```rust use std::collections::BTreeMap; let mut a = BTreeMap::new(); a.insert(1, String::from("hello")); a.insert(2, String::from("goodbye")); for value in a.values_mut() { value.push_str("!"); } let values: Vec = a.values().cloned().collect(); assert_eq!(values, [String::from("hello!"), String::from("goodbye!")]); ``` -------------------------------- ### Arc::strong_count Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/builder/layer/type.IsFullPolygonPredicate.html Gets the number of strong (Arc) pointers to this allocation. ```APIDOC ## pub fn strong_count(this: &Arc) -> usize ### Description Gets the number of strong (`Arc`) pointers to this allocation. Note that another thread can change the strong count at any time. ``` -------------------------------- ### Create and manipulate a Polyline in Rust Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/polyline/struct.Polyline.html Demonstrates initializing a Polyline from points, calculating its length, and interpolating a midpoint. ```rust use s2rst::s2::LatLng; use s2rst::s2::polyline::Polyline; let polyline = Polyline::new(vec![ LatLng::from_degrees(0.0, 0.0).to_point(), LatLng::from_degrees(0.0, 90.0).to_point(), ]); // Length of a quarter great circle is pi/2 radians. let length = polyline.length(); assert!((length.radians() - std::f64::consts::FRAC_PI_2).abs() < 1e-13); // Interpolate to the midpoint (0, 45). let (mid, _next) = polyline.interpolate(0.5); let expected = LatLng::from_degrees(0.0, 45.0).to_point(); assert!(mid.distance(expected).radians() < 1e-10); ``` -------------------------------- ### Use DistanceTarget with PointTarget Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/distance_target/trait.DistanceTarget.html Example of using a PointTarget to retrieve a bounding cap. ```rust use s2rst::s2::distance_target::DistanceTarget; use s2rst::s2::closest_edge_query::PointTarget; use s2rst::s2::LatLng; let target = PointTarget::new(LatLng::from_degrees(0.0, 0.0).to_point()); let cap = target.cap_bound(); assert!(!cap.is_empty()); ``` -------------------------------- ### Perform a Winding Operation in Rust Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/winding_operation/struct.S2WindingOperation.html Demonstrates initializing a winding operation, adding loops, and building the result using a reference point. ```rust use s2rst::s2::winding_operation::{S2WindingOperation, WindingOptions, WindingRule}; use s2rst::s2::builder::polygon_layer::S2PolygonLayer; use s2rst::s2::LatLng; // Create a winding operation to compute a union via winding numbers. let layer = S2PolygonLayer::new(); let mut op = S2WindingOperation::new(Box::new(layer), WindingOptions::new()); // Add a loop (closed polygon boundary). let loop_pts: Vec<_> = vec![ LatLng::from_degrees(0.0, 0.0), LatLng::from_degrees(0.0, 1.0), LatLng::from_degrees(1.0, 1.0), LatLng::from_degrees(1.0, 0.0), ].into_iter().map(|ll| ll.to_point()).collect(); op.add_loop(&loop_pts); // Build with a reference point outside the loop, winding = 0. let ref_point = LatLng::from_degrees(45.0, 45.0).to_point(); op.build(ref_point, 0, WindingRule::Positive).unwrap(); ``` -------------------------------- ### Retrieve BTreeMap Values Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/incident_edge_tracker/type.IncidentEdgeMap.html Get an iterator over the values of the map in order by key. ```rust use std::collections::BTreeMap; let mut a = BTreeMap::new(); a.insert(1, "hello"); a.insert(2, "goodbye"); let values: Vec<&str> = a.values().cloned().collect(); assert_eq!(values, ["hello", "goodbye"]); ``` -------------------------------- ### WindingOptions::new Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/winding_operation/struct.WindingOptions.html Creates a new instance of WindingOptions with default settings. ```APIDOC ## pub fn new() -> Self ### Description Creates default winding options. ### Returns - **Self** - A new instance of WindingOptions. ``` -------------------------------- ### Retrieve BTreeMap Keys Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/incident_edge_tracker/type.IncidentEdgeMap.html Get an iterator over the keys of the map in sorted order. ```rust use std::collections::BTreeMap; let mut a = BTreeMap::new(); a.insert(2, "b"); a.insert(1, "a"); let keys: Vec<_> = a.keys().cloned().collect(); assert_eq!(keys, [1, 2]); ``` -------------------------------- ### Use LatLng for coordinate operations Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/struct.LatLng.html Demonstrates creating LatLng instances, converting to points, and calculating distances. ```rust use s2rst::s2::LatLng; // Create from degrees let paris = LatLng::from_degrees(48.8566, 2.3522); assert!(paris.is_valid()); // Convert to Point and back let point = paris.to_point(); let back = LatLng::from_point(point); assert!((back.lat.degrees() - 48.8566).abs() < 1e-13); // Distance between two locations let london = LatLng::from_degrees(51.5074, -0.1278); let dist = paris.get_distance(london); assert!(dist.degrees() > 3.0 && dist.degrees() < 4.0); ``` -------------------------------- ### Get mutable reference to Arc Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/builder/layer/type.IsFullPolygonPredicate.html Returns a mutable reference if there are no other pointers to the allocation. ```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()); ``` -------------------------------- ### Using SequenceLexicon to map sequences Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/sequence_lexicon/index.html Demonstrates initializing a SequenceLexicon, adding a sequence to retrieve an ID, and retrieving the original sequence from that ID. ```rust use s2rst::s2::sequence_lexicon::SequenceLexicon; let mut lex = SequenceLexicon::new(); let pets = vec!["cat", "dog", "parrot"]; let pets_id = lex.add(&pets); assert_eq!(pets_id, lex.add(&pets)); let seq: Vec<_> = lex.sequence(pets_id).collect(); assert_eq!(seq, vec![&"cat", &"dog", &"parrot"]); ``` -------------------------------- ### Construct a Vec with capacity Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/builder/lax_polygon_layer/type.LabelSetIds.html Example of creating a vector with pre-allocated capacity to avoid reallocations. ```rust let mut vec = Vec::with_capacity(10); // The vector contains no items, even though it has capacity for more assert_eq!(vec.len(), 0); assert!(vec.capacity() >= 10); // These are all done without reallocating... for i in 0..10 { vec.push(i); } assert_eq!(vec.len(), 10); assert!(vec.capacity() >= 10); // ...but this may make the vector reallocate vec.push(11); assert_eq!(vec.len(), 11); assert!(vec.capacity() >= 11); // A vector of a zero-sized type will always over-allocate, since no // allocation is necessary let vec_units = Vec::<()>::with_capacity(10); assert_eq!(vec_units.capacity(), usize::MAX); ``` -------------------------------- ### Get element or subslice Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/lax_polyline/struct.LaxPolyline.html Returns a reference to an element or subslice depending on the type of index. ```rust let v = [10, 40, 30]; assert_eq!(Some(&40), v.get(1)); assert_eq!(Some(&[10, 40][..]), v.get(0..2)); assert_eq!(None, v.get(3)); assert_eq!(None, v.get(0..4)); ``` -------------------------------- ### Constructing an S2Polygon using S2PolygonLayer Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/builder/polygon_layer/struct.S2PolygonLayer.html Demonstrates how to initialize an S2Builder with an S2PolygonLayer, add edges, and extract the resulting polygon. ```rust use s2rst::s2::builder::{S2Builder, Options}; use s2rst::s2::builder::polygon_layer::S2PolygonLayer; use s2rst::s2::text_format::parse_point; let mut builder = S2Builder::new(Options::default()); builder.start_layer(Box::new(S2PolygonLayer::new())); builder.add_edge(parse_point("0:0"), parse_point("0:10")); builder.add_edge(parse_point("0:10"), parse_point("10:0")); builder.add_edge(parse_point("10:0"), parse_point("0:0")); let mut layers = builder.build().unwrap(); let layer = layers.remove(0) .into_any() .downcast::() .expect("wrong layer type"); let polygon = layer.into_output(); assert_eq!(polygon.num_loops(), 1); ``` -------------------------------- ### Get all intersecting shards Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/region_sharder/struct.RegionSharder.html Returns a vector of indices for all shards that intersect the provided region. ```rust pub fn get_intersecting_shards(&self, region: &dyn Region) -> Vec ``` -------------------------------- ### Create New BTreeMap Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/incident_edge_tracker/type.IncidentEdgeMap.html Initialize an empty BTreeMap. ```rust use std::collections::BTreeMap; let mut map = BTreeMap::new(); // entries can now be inserted into the empty map map.insert(1, "a"); ``` -------------------------------- ### Get unit-length face normal Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/coords/fn.get_norm.html Returns the unit-length face normal for the specified face. ```rust pub fn get_norm(face: Face) -> Vector ``` -------------------------------- ### Querying for closest points in Rust Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/closest_point_query/struct.ClosestPointQuery.html Demonstrates initializing an S2PointIndex, creating a ClosestPointQuery, and finding the closest points to a target location. ```rust use s2rst::s2::closest_point_query::{ClosestPointQuery, Options, PointTarget}; use s2rst::s2::point_index::S2PointIndex; use s2rst::s2::LatLng; let mut index = S2PointIndex::new(); index.add(LatLng::from_degrees(0.0, 0.0).to_point(), 0u32); index.add(LatLng::from_degrees(1.0, 0.0).to_point(), 1u32); index.add(LatLng::from_degrees(2.0, 0.0).to_point(), 2u32); let query = ClosestPointQuery::new(&index, Options::default()); let mut target = PointTarget::new(LatLng::from_degrees(0.5, 0.0).to_point()); let results = query.find_closest_points(&mut target); assert!(!results.is_empty()); ``` -------------------------------- ### rchunks Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/lax_loop/struct.LaxLoop.html Returns an iterator over chunk_size elements of the slice at a time, starting at the end of the slice. ```APIDOC ## pub fn rchunks(&self, chunk_size: usize) -> RChunks<'_, T> ### Description Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end of the slice. The chunks are slices and do not overlap. ### Panics Panics if `chunk_size` is zero. ``` -------------------------------- ### Create a FeatureMap from shapes Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/density_tree/struct.FeatureMap.html Demonstrates initializing a FeatureMap with shape IDs, feature keys, and weights. Shapes sharing the same key are mapped to the same feature ID. ```rust // Two shapes map to feature "building_42" (weight 1), one to "road_7" (weight 5). let map = FeatureMap::from_shapes(3, [ (0, "building_42", 1), (1, "building_42", 1), // same key → same feature ID, weight reused (2, "road_7", 5), ]); assert_eq!(map.num_features(), 2); ``` -------------------------------- ### Option::into_flat_iter Example Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/closest_edge_query/type.ShapeFilter.html Transforms an optional iterator into an iterator, requiring the nightly feature flag. ```rust #![feature(option_into_flat_iter)] let o1 = Some([1, 2]); let o2 = None::<&[usize]>; assert_eq!(o1.into_flat_iter().collect::>(), [1, 2]); assert_eq!(o2.into_flat_iter().collect::>(), Vec::<&usize>::new()); ``` -------------------------------- ### Convert Option to Slice Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/closest_edge_query/type.ShapeFilter.html Demonstrates converting an Option to a slice using as_slice and comparing it with array indexing. ```rust assert_eq!( [Some(1234).as_slice(), None.as_slice()], [&[1234][..], &[][..]], ); ``` ```rust for i in [Some(1234_u16), None] { assert_eq!(i.as_ref(), i.as_slice().first()); } ``` -------------------------------- ### Compute Convex Hull with Rust Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/convex_hull_query/struct.ConvexHullQuery.html Demonstrates initializing a query, adding points, and calculating the resulting convex hull loop. ```rust use s2rst::s2::convex_hull_query::ConvexHullQuery; use s2rst::s2::LatLng; let mut q = ConvexHullQuery::new(); q.add_point(LatLng::from_degrees(0.0, 0.0).to_point()); q.add_point(LatLng::from_degrees(0.0, 10.0).to_point()); q.add_point(LatLng::from_degrees(10.0, 5.0).to_point()); let hull = q.convex_hull(); assert!(hull.num_vertices() >= 3); assert!(hull.area() > 0.0); ``` -------------------------------- ### ShapeEdge::new Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/shape/struct.ShapeEdge.html Creates a new instance of ShapeEdge. ```APIDOC ## pub fn new(id: ShapeEdgeId, edge: Edge) -> Self ### Description Creates a new `ShapeEdge` instance by combining a `ShapeEdgeId` and an `Edge`. ### Parameters - **id** (ShapeEdgeId) - The shape and edge identifiers. - **edge** (Edge) - The edge geometry. ### Returns - **Self** - A new `ShapeEdge` instance. ``` -------------------------------- ### SequenceLexicon::new Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/sequence_lexicon/struct.SequenceLexicon.html Creates a new empty lexicon instance. ```APIDOC ## pub fn new() -> Self ### Description Creates a new empty lexicon. ``` -------------------------------- ### Retrieve a value by key Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/incident_edge_tracker/type.IncidentEdgeMap.html Use get to return a reference to the value associated with a given key. ```rust use std::collections::BTreeMap; let mut map = BTreeMap::new(); map.insert(1, "a"); assert_eq!(map.get(&1), Some(&"a")); assert_eq!(map.get(&2), None); ``` -------------------------------- ### with_options(options: Options) Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/builder/indexed_layers/struct.IndexedS2PolylineVectorLayer.html Creates a new instance of the IndexedS2PolylineVectorLayer with specific configuration options. ```APIDOC ## pub fn with_options(options: Options) -> Self ### Description Creates a new indexed layer with the provided options. ### Parameters - **options** (Options) - Required - The configuration options for the layer. ``` -------------------------------- ### Get edge length in (i,j)-space Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/fn.size_ij.html Calculates the edge length of cells at a given level. ```rust pub fn size_ij(level: impl Into) -> i32 ``` -------------------------------- ### Interpolate points on a LaxPolyline Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/chain_interpolation_query/struct.S2ChainInterpolationQuery.html Demonstrates initializing a query for a polyline and interpolating a point at 50% of its total length. ```rust use s2rst::s2::chain_interpolation_query::S2ChainInterpolationQuery; use s2rst::s2::lax_polyline::LaxPolyline; use s2rst::s2::shape::Shape; use s2rst::s2::LatLng; let line = LaxPolyline::new(vec![ LatLng::from_degrees(0.0, 0.0).to_point(), LatLng::from_degrees(1.0, 0.0).to_point(), LatLng::from_degrees(2.0, 0.0).to_point(), ]); let query = S2ChainInterpolationQuery::new(&line); // Interpolate at 50% of the total length. let result = query.at_fraction(0.5); assert!(result.is_some()); let r = result.unwrap(); // Should be near (1.0, 0.0). let ll = LatLng::from_point(r.point); assert!((ll.lat.degrees() - 1.0).abs() < 0.01); ``` -------------------------------- ### Reverse split slice into N parts Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/lax_polyline/struct.LaxPolyline.html Splits a slice into at most N subslices starting from the end. ```rust let v = [10, 40, 30, 20, 60, 50]; for group in v.rsplitn(2, |num| *num % 3 == 0) { println!("{group:?}"); } ``` -------------------------------- ### and usage Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/closest_edge_query/type.ShapeFilter.html Returns the provided Option if the current one is Some, otherwise returns None. ```rust let x = Some(2); let y: Option<&str> = None; assert_eq!(x.and(y), None); let x: Option = None; let y = Some("foo"); assert_eq!(x.and(y), None); let x = Some(2); let y = Some("foo"); assert_eq!(x.and(y), Some("foo")); let x: Option = None; let y: Option<&str> = None; assert_eq!(x.and(y), None); ``` -------------------------------- ### Track incident edges with IncidentEdgeTracker Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/incident_edge_tracker/index.html Demonstrates initializing the tracker, adding edges for a shape, and verifying the presence of a vertex in the resulting incident edge map. ```rust use s2rst::s2::incident_edge_tracker::IncidentEdgeTracker; use s2rst::s2::{LatLng, Point}; let a = LatLng::from_degrees(1.0, 1.0).to_point(); let b = LatLng::from_degrees(1.0, 2.0).to_point(); let c = LatLng::from_degrees(2.0, 1.0).to_point(); let mut tracker = IncidentEdgeTracker::new(); tracker.start_shape(0); tracker.add_edge(0, a, b); tracker.add_edge(1, b, a); tracker.add_edge(2, a, c); tracker.add_edge(3, c, a); tracker.finish_shape(); let map = tracker.incident_edges(); // Vertex 'a' has 4 incident edges, so it appears in the map. use s2rst::s2::incident_edge_tracker::IncidentEdgeKey; assert!(map.contains_key(&IncidentEdgeKey { shape_id: 0, vertex: a })); ``` -------------------------------- ### Downcasting a Layer Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/builder/layer/trait.Layer.html Example of retrieving a specific layer type from the builder output using into_any and downcast. ```rust let layers = builder.build()?; let layer = layers.into_iter().next().unwrap() .into_any().downcast::().unwrap(); let polygon = layer.into_output(); ``` -------------------------------- ### Initialize BTreeMap with custom allocator Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/incident_edge_tracker/type.IncidentEdgeMap.html Requires the btreemap_alloc feature. Creates a new empty map using the provided allocator. ```rust use std::collections::BTreeMap; use std::alloc::Global; let map: BTreeMap = BTreeMap::new_in(Global); ``` -------------------------------- ### as_array(&self) Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/point_vector/struct.PointVector.html Gets a reference to the underlying array if the length matches N. ```APIDOC ## pub fn as_array(&self) -> Option<&[T; N]> ### Description Gets a reference to the underlying array. If `N` is not exactly equal to the length of `self`, then this method returns `None`. ``` -------------------------------- ### Chain Struct Definition Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/shape/struct.Chain.html The structure definition for Chain, containing the start index and the length of the edge sequence. ```rust pub struct Chain { pub start: usize, pub length: usize, } ``` -------------------------------- ### Initialize Vec via as_mut_ptr Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/builder/lax_polygon_layer/type.LabelSetIds.html Demonstrates initializing a vector's buffer using a raw mutable pointer and setting the length manually. ```rust // Allocate vector big enough for 4 elements. let size = 4; let mut x: Vec = Vec::with_capacity(size); let x_ptr = x.as_mut_ptr(); // Initialize elements via raw pointer writes, then set length. unsafe { for i in 0..size { *x_ptr.add(i) = i as i32; } x.set_len(size); } assert_eq!(&*x, &[0, 1, 2, 3]); ``` -------------------------------- ### Using ValueLexicon for Deduplication Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/value_lexicon/index.html Demonstrates initializing a ValueLexicon, adding values, and retrieving them by their assigned ID. ```rust use s2rst::s2::value_lexicon::ValueLexicon; let mut lex = ValueLexicon::new(); let cat_id = lex.add("cat".to_string()); assert_eq!(cat_id, lex.add("cat".to_string())); assert_eq!("cat", lex.value(cat_id)); ``` -------------------------------- ### rchunks_exact Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/lax_loop/struct.LaxLoop.html Returns an iterator over chunk_size elements of the slice at a time, starting at the end of the slice, with exact sizing. ```APIDOC ## pub fn rchunks_exact(&self, chunk_size: usize) -> RChunksExact<'_, T> ### Description Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end of the slice. If `chunk_size` does not divide the length of the slice, the remainder can be retrieved from the `remainder` function of the iterator. ### Panics Panics if `chunk_size` is zero. ``` -------------------------------- ### Convert slice or array to Vec Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/builder/graph/type.EdgeLoop.html Examples of creating a Vec from slices, mutable slices, and arrays using the From trait. ```rust assert_eq!(Vec::from(&[1, 2, 3][..]), vec![1, 2, 3]); ``` ```rust assert_eq!(Vec::from(&[1, 2, 3]), vec![1, 2, 3]); ``` ```rust assert_eq!(Vec::from(&mut [1, 2, 3][..]), vec![1, 2, 3]); ``` ```rust assert_eq!(Vec::from(&mut [1, 2, 3]), vec![1, 2, 3]); ``` ```rust assert_eq!(Vec::from([1, 2, 3]), vec![1, 2, 3]); ``` -------------------------------- ### Options Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/builder/closed_set_normalizer/index.html Configuration struct for the ClosedSetNormalizer. ```APIDOC ## Struct: Options ### Description Represents the configuration options used to initialize or control the behavior of the `ClosedSetNormalizer`. ``` -------------------------------- ### Extract elements conditionally Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/builder/lax_polygon_layer/type.LabelSetIds.html Demonstrates the logic behind extract_if and provides examples for splitting or filtering vector contents. ```rust let mut i = range.start; let end_items = vec.len() - range.end; while i < vec.len() - end_items { if some_predicate(&mut vec[i]) { let val = vec.remove(i); // your code here } else { i += 1; } } ``` ```rust let mut numbers = vec![1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15]; let evens = numbers.extract_if(.., |x| *x % 2 == 0).collect::>(); let odds = numbers; assert_eq!(evens, vec![2, 4, 6, 8, 14]); assert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]); ``` ```rust let mut items = vec![0, 0, 0, 0, 0, 0, 0, 1, 2, 1, 2, 1, 2]; let ones = items.extract_if(7.., |x| *x == 1).collect::>(); assert_eq!(items, vec![0, 0, 0, 0, 0, 0, 0, 2, 2, 2]); assert_eq!(ones.len(), 3); ``` -------------------------------- ### Parse and create S2 geometries from text Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/text_format/index.html Demonstrates creating points, loops, and polygons from string representations. ```rust let p = parse_point("37.7749:-122.4194"); let loop_ = make_loop("0:0, 0:10, 10:0"); let polygon = make_polygon("0:0, 0:10, 10:0; 1:1, 1:5, 5:1"); ``` -------------------------------- ### Deallocate Vec using Box Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/builder/lax_polygon_layer/type.LabelSetIds.html Example of manually deallocating a vector's memory using Box and ManuallyDrop. ```rust use std::mem::{ManuallyDrop, MaybeUninit}; let mut v = ManuallyDrop::new(vec![0, 1, 2]); let ptr = v.as_mut_ptr(); let capacity = v.capacity(); let slice_ptr: *mut [MaybeUninit] = std::ptr::slice_from_raw_parts_mut(ptr.cast(), capacity); drop(unsafe { Box::from_raw(slice_ptr) }); ``` -------------------------------- ### S2PolylineLayer::new Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/builder/polyline_layer/struct.S2PolylineLayer.html Creates a new S2PolylineLayer instance with default configuration. ```APIDOC ## pub fn new() -> Self ### Description Creates a new layer with default options. ``` -------------------------------- ### Perform exact arithmetic with ExactFloat Source: https://docs.rs/s2rst/0.4.0/s2rst/r3/exact_float/struct.ExactFloat.html Demonstrates performing exact addition and multiplication using ExactFloat, highlighting that it avoids standard floating-point rounding issues. ```rust use s2rst::r3::ExactFloat; // Exact arithmetic with no rounding errors. let a = ExactFloat::from(0.1); let b = ExactFloat::from(0.2); let sum = a.add(&b); // Compare with exact 0.3 — note that 0.1 + 0.2 ≠ 0.3 in f64, // but ExactFloat faithfully represents the f64 inputs. let c = ExactFloat::from(0.3_f64); assert!(sum != c); // 0.1_f64 + 0.2_f64 ≠ 0.3_f64, even exactly! // Multiplication is also exact. let x = ExactFloat::from(3.0); let y = ExactFloat::from(7.0); let product = x.mul(&y); assert_eq!(product.to_f64(), 21.0); ``` -------------------------------- ### Options Struct Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/closest_edge_query/struct.Options.html Configuration struct for closest edge queries. ```APIDOC ## Struct: Options ### Description Options for a closest edge query. ### Fields - **max_results** (i32) - Maximum number of results to return (default: i32::MAX). - **max_distance** (ChordAngle) - Maximum distance for edges to be included (default: infinity). - **max_error** (ChordAngle) - Maximum error allowed (trades accuracy for speed). - **include_interiors** (bool) - Whether to include polygon interiors (distance 0 for contained targets). - **use_brute_force** (bool) - Force brute-force search (useful for testing/benchmarking). ``` -------------------------------- ### Get element unchecked Source: https://docs.rs/s2rst/0.4.0/s2rst/s2/lax_polyline/struct.LaxPolyline.html Returns a reference to an element or subslice without bounds checking. Use with caution as it is unsafe. ```rust let x = &[1, 2, 4]; unsafe { assert_eq!(x.get_unchecked(1), &2); } ```