Skip to main content

ring_seq/
lib.rs

1//! Circular (ring) sequence operations for Rust slices.
2//!
3//! Reach the circular API by calling [`AsCircular::circular`] on any slice,
4//! [`Vec<T>`](alloc::vec::Vec), array, or [`Box<[T]>`](alloc::boxed::Box).
5//! The returned [`Circular`] wrapper is the single home for every circular
6//! operation; every transform it offers is lazy and allocation-free.
7//!
8//! # Quick start
9//!
10// The example calls alloc-gated methods (`canonical`), so only compile it
11// as a doctest when the feature is on; render it unchanged either way.
12#![cfg_attr(feature = "alloc", doc = " ```")]
13#![cfg_attr(not(feature = "alloc"), doc = " ```ignore")]
14//! use ring_seq::AsCircular;
15//!
16//! let r = [10, 20, 30].circular();
17//!
18//! // Indexing wraps in both directions
19//! assert_eq!(*r.apply(4), 20);
20//! assert_eq!(*r.apply(-1), 30);
21//!
22//! // Reindexed views — no allocation
23//! let rotated: Vec<_> = r.rotate_right(1).iter().copied().collect();
24//! assert_eq!(rotated, vec![30, 10, 20]);
25//!
26//! // Comparisons up to rotation/reflection
27//! assert!(r.is_rotation_of(&[20, 30, 10]));
28//! assert!(r.is_reflection_of(&[10, 30, 20]));
29//!
30//! // Canonical (necklace) form — O(n) minimal rotation
31//! assert_eq!(r.canonical(), vec![10, 20, 30]);
32//!
33//! // Lazy iterators of views
34//! let firsts: Vec<i32> = r.rotations().map(|v| *v.apply(0)).collect();
35//! assert_eq!(firsts, vec![10, 20, 30]);
36//! ```
37//!
38//! # `no_std`
39//!
40//! The crate is `#![no_std]`. The default `alloc` feature enables only the
41//! methods that return owned collections ([`Circular::to_vec`],
42//! [`Circular::canonical`], [`Circular::bracelet`],
43//! [`Circular::symmetry_indices`],
44//! [`Circular::reflectional_symmetry_axes`]).
45//! With `--no-default-features` everything else — the wrapper, its
46//! element/view iterators, and all scalar queries including
47//! [`Circular::canonical_index`] — remains available and depends only on
48//! `core`.
49
50#![no_std]
51
52#[cfg(feature = "alloc")]
53extern crate alloc;
54
55mod circular;
56
57pub use circular::{
58    AsCircular, Chunks, Circular, CircularIter, Enumerate, Reflections, Reversions, Rotations,
59    RotationsAndReflections, Windows,
60};
61
62// ============================================================================
63// AxisLocation
64// ============================================================================
65
66/// A location on a circular sequence where a reflectional-symmetry axis
67/// passes.
68///
69/// # Variants
70///
71/// * [`Vertex`](AxisLocation::Vertex) — the axis passes through the
72///   element at the given index.
73/// * [`Edge`](AxisLocation::Edge) — the axis passes between two
74///   consecutive elements.
75#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
76pub enum AxisLocation {
77    /// The axis passes through the element at this index.
78    Vertex(usize),
79    /// The axis passes between the elements at these two consecutive indices.
80    /// The invariant `j == (i + 1) % n` is maintained by
81    /// [`AxisLocation::edge`].
82    Edge(usize, usize),
83}
84
85impl AxisLocation {
86    /// Constructs an [`Edge`](AxisLocation::Edge) between consecutive
87    /// elements of a ring of size `n`, starting at index `i`.
88    ///
89    /// The second index is computed as `(i + 1) % n`.
90    ///
91    /// # Panics
92    ///
93    /// Panics if `n` is zero.
94    ///
95    /// # Examples
96    ///
97    /// ```
98    /// use ring_seq::AxisLocation;
99    ///
100    /// assert_eq!(AxisLocation::edge(2, 3), AxisLocation::Edge(2, 0));
101    /// assert_eq!(AxisLocation::edge(0, 4), AxisLocation::Edge(0, 1));
102    /// ```
103    #[must_use]
104    pub fn edge(i: usize, n: usize) -> Self {
105        assert!(n > 0, "ring size must be positive");
106        let ii = i % n;
107        AxisLocation::Edge(ii, (ii + 1) % n)
108    }
109}
110
111#[cfg(test)]
112mod axis_tests {
113    use super::*;
114
115    #[test]
116    fn edge_constructor() {
117        assert_eq!(AxisLocation::edge(2, 3), AxisLocation::Edge(2, 0));
118        assert_eq!(AxisLocation::edge(0, 4), AxisLocation::Edge(0, 1));
119        assert_eq!(AxisLocation::edge(3, 4), AxisLocation::Edge(3, 0));
120    }
121
122    #[test]
123    #[should_panic(expected = "ring size must be positive")]
124    fn edge_zero_size_panics() {
125        let _ = AxisLocation::edge(0, 0);
126    }
127}