Enum Selection

Source
#[non_exhaustive]
pub enum Selection { False, True, All(Box<Selection>), First(Box<Selection>), Range(Range, Box<Selection>), Label(Vec<LabelKey>, Box<Selection>), Any(Box<Selection>), Intersection(Box<Selection>, Box<Selection>), Union(Box<Selection>, Box<Selection>), }
Expand description

An algebra for expressing node selection.

Variants (Non-exhaustive)§

This enum is marked as non-exhaustive
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.
§

False

A selection that never matches any node.

§

True

A selection that always matches any node.

§

All(Box<Selection>)

Selects all values along the current dimension, continuing with the given selection.

§

First(Box<Selection>)

Selects the first value along the current dimension for which applying the inner selection yields any results.

§

Range(Range, Box<Selection>)

Selects values within a given range along the current dimension, continuing with the given selection.

§

Label(Vec<LabelKey>, Box<Selection>)

Selects values based on metadata (i.e., labels) along the current dimension. This provides attribute-based selection.

§

Any(Box<Selection>)

Selects a random index along the current dimension, continuing with the given selection.

§

Intersection(Box<Selection>, Box<Selection>)

The intersection (logical AND) of two selections.

§

Union(Box<Selection>, Box<Selection>)

The union (logical OR) of two selections.

Implementations§

Source§

impl Selection

Source

pub fn eval<'a>( &self, opts: &EvalOpts, slice: &'a Slice, ) -> Result<Box<dyn Iterator<Item = usize> + 'a>, ShapeError>

Lazily evaluates this selection against the given slice yielding flat indices.

Returns a boxed iterator that produces indices of elements matching the selection expression when evaluated over slice.

§Lifetimes

The returned iterator borrows slice because the internal iterators are implemented as closures that capture &slice in their environment. Evaluation is lazy, so these closures dereference slice each time a coordinate is visited. The 'a lifetime ensures that the iterator cannot outlive the slice it reads from.

§Why Box<dyn Iterator>

The selection algebra supports multiple recursive strategies (All, Range, Intersection, etc.) that return different iterator types (e.g. Selection::True => std::iter::once(...), Selection::False => std::iter::empty()). Returning impl Iterator is not feasible because the precise type depends on dynamic selection structure. Boxing erases this variability and allows a uniform return type.

§Canonical handling of 0-dimensional slices

A Slice with zero dimensions represents the empty product ∏_{i=1}^{0} Xᵢ, which has exactly one element: the empty tuple. To ensure that evaluation behaves uniformly across dimensions, we canonically embed the 0-dimensional case into a 1-dimensional slice of extent 1. That is, we reinterpret the 0D slice as Slice::new(offset, [1], [1]), which is semantically equivalent and enables evaluation to proceed through the normal recursive machinery without special-casing. The result is that selection expressions are always evaluated over a slice with at least one dimension, and uniform logic applies.

Source

pub fn is_equivalent_to_true(sel: &Selection) -> bool

Returns true if this selection is equivalent to True under the algebra.

In the selection algebra, All(True) is considered equivalent to True, and this identity extends recursively. For example:

  • All(True)True
  • All(All(True))True
  • All(All(All(True)))True

This method checks whether the selection is structurally identical to True, possibly wrapped in one or more All(…) layers. It does not perform full normalization—only structural matching sufficient to recognize this identity.

Used to detect when a selection trivially selects all elements at all levels.

§Limitations

This is a syntactic check only. It does not recognize semantically equivalent expressions such as:

  • Union(True, True)
  • All(Union(True, False))
  • A union of all singleton ranges covering the full space

For a semantic check, use evaluation against a known slice.

Source

pub fn contains(&self, coords: &[usize]) -> bool

Evaluates whether the specified coordinates are part of the selection. Returns true if they are, false otherwise.

Example: let selection = union( range(0..2, range(0..1, range(0..2, true_()))), range(0..2, range(1..2, range(0..2, true_()))), );

assert!(selection.contains(&[0, 0, 1])); assert!(!selection.contains(&[2, 0, 1]));

Source

pub fn reduce_intersection(self: Selection, b: Selection) -> Selection

Simplifies the intersection of two Selection expressions.

Applies short-circuit logic to avoid constructing redundant or degenerate intersections:

  • If either side is False, the result is False.
  • If either side is True, the result is the other side.
  • Otherwise, constructs an explicit Intersection.

This is required during routing to make progress when evaluating intersections. Without this reduction, routing may stall — for example, in intersections like Intersection(True, X), which should simplify to X.

Source

pub fn fold<S: SelectionSYM>(&self) -> S

Recursively folds the Selection into an abstract syntax via the SelectionSYM interface.

This method structurally traverses the Selection tree and reconstructs it using the operations provided by the SelectionSYM trait. It is typically used to reify a Selection into alternate forms, such as pretty-printers.

§Type Parameters
  • S: An implementation of the SelectionSYM trait, providing the constructors for the target representation.
Source

pub fn difference<'a>( &self, opts: &EvalOpts, slice: &'a Slice, exclusions: &'a HashSet<usize>, ) -> Result<impl Iterator<Item = usize> + use<'a>, ShapeError>

Iterator over indices selected by self and not in exclusions.

Evaluates the selection against slice using opts, then filters out any indices present in the exclusion set. Evaluation is lazy and streaming; the exclusion set is used directly for fast membership checks.

Source

pub fn without( &self, slice: &Slice, exclusions: &HashSet<usize>, ) -> Result<Selection, ShapeError>

Calculate a new Selection that excludes the specified flat ranks.

This computes self \ exclusions by evaluating self, removing the given ranks, and reconstructing a Selection that selects exactly the remaining elements.

The result is a concrete, structurally uniform expression with predictable construction order and exact correspondence to the surviving ranks.

Source

pub fn of_ranks( slice: &Slice, ranks: &BTreeSet<usize>, ) -> Result<Selection, SliceError>

Converts a set of flat indices into a symbolic Selection expression over the given slice. Returns an error if any index is invalid.

Each flat index is converted into coordinates using slice.coordinates, then folded into a nested chain of singleton ranges. The resulting selection evaluates exactly to the input indices.

The selections are combined left-associatively using union, but since union is associative, the grouping does not affect correctness.

The input BTreeSet ensures:

  • all indices are unique (no redundant singleton ranges),
  • the resulting selection has a stable, deterministic structure,
  • and iteration proceeds in ascending order, which helps produce predictable routing trees and consistent test results.

This choice avoids an explicit sort and makes downstream behavior more reproducible and auditable.

Trait Implementations§

Source§

impl Clone for Selection

Source§

fn clone(&self) -> Selection

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Selection

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de> Deserialize<'de> for Selection

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Display for Selection

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl From<NormalizedSelection> for Selection

Source§

fn from(norm: NormalizedSelection) -> Self

Converts the normalized form back into a standard Selection.

Logical semantics are preserved, but normalized shape (e.g., set-based unions and intersections) is reconstructed as left-associated binary trees.

Source§

impl SelectionSYM for Selection

Source§

fn false_() -> Self

The identity selection (matches no nodes).
Source§

fn true_() -> Self

The universal selection (matches all nodes).
Source§

fn all(selection: Self) -> Self

Selects all values along the current dimension, then applies the inner selection.
Source§

fn first(selection: Self) -> Self

Selects the first index along the current dimension for which the inner selection is non-empty.
Source§

fn range<R: Into<Range>>(range: R, selection: Self) -> Self

Selects values within the given range along the current dimension, then applies the inner selection.
Source§

fn label<L: Into<LabelKey>>(labels: Vec<L>, selection: Selection) -> Selection

Selects values along the current dimension that match the given labels, then applies the inner selection.
Source§

fn any(selection: Self) -> Self

Selects a random index along the current dimension, then applies the inner selection.
Source§

fn intersection(lhs: Self, rhs: Self) -> Self

The intersection (logical AND) of two selection expressions.
Source§

fn union(lhs: Self, rhs: Self) -> Self

The union (logical OR) of two selection expressions.
Source§

impl Serialize for Selection

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,