Skip to main content

FixedSet

Struct FixedSet 

Source
pub struct FixedSet<T, const SIZE: usize> { /* private fields */ }
Expand description

A fixed-capacity set for storing unique elements.

FixedSet maintains a collection of unique elements with compile-time capacity bounds. It provides efficient insertion, removal, and lookup operations while maintaining element uniqueness.

§Type Parameters

  • T - The element type. Must implement Default + Copy + PartialEq.
  • SIZE - The maximum number of elements the set can hold (compile-time constant).

§Examples

use satellite_bitcoin::generic::fixed_set::FixedSet;

let mut set: FixedSet<u32, 8> = FixedSet::new();

set.insert(3).unwrap();
set.insert(5).unwrap();
assert!(set.contains(&3));
assert_eq!(set.len(), 2);

// Duplicate insertion fails
assert!(set.insert(3).is_err());

// Remove elements
assert_eq!(set.remove(&3), Some(3));
assert_eq!(set.len(), 1);

§Memory Layout

The set stores elements in a contiguous array followed by a length field. Element order is not preserved across insertions and removals due to the swap-remove optimization used for O(1) removal.

§Bytemuck Compatibility

FixedSet implements Pod and Zeroable when T implements these traits, making it suitable for zero-copy serialization in on-chain programs.

Implementations§

Source§

impl<T, const SIZE: usize> FixedSet<T, SIZE>
where T: Default + Copy + PartialEq,

Source

pub fn new() -> FixedSet<T, SIZE>

Creates an empty FixedSet.

§Examples
use satellite_bitcoin::generic::fixed_set::FixedSet;

let set: FixedSet<u32, 10> = FixedSet::new();
assert!(set.is_empty());
assert_eq!(set.len(), 0);
Source

pub fn len(&self) -> usize

Returns the number of elements currently stored in the set.

§Examples
use satellite_bitcoin::generic::fixed_set::FixedSet;

let mut set: FixedSet<u32, 10> = FixedSet::new();
assert_eq!(set.len(), 0);

set.insert(42).unwrap();
assert_eq!(set.len(), 1);
Source

pub fn is_empty(&self) -> bool

Returns true if the set contains no elements.

§Examples
use satellite_bitcoin::generic::fixed_set::FixedSet;

let mut set: FixedSet<u32, 10> = FixedSet::new();
assert!(set.is_empty());

set.insert(42).unwrap();
assert!(!set.is_empty());
Source

pub fn iter(&self) -> impl Iterator<Item = &T>

Returns an iterator over all items currently in the set.

§Examples
use satellite_bitcoin::generic::fixed_set::FixedSet;

let mut set: FixedSet<u32, 10> = FixedSet::new();
set.insert(1).unwrap();
set.insert(2).unwrap();

let collected: Vec<_> = set.iter().copied().collect();
assert_eq!(collected.len(), 2);
assert!(collected.contains(&1));
assert!(collected.contains(&2));
Source

pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut T>

Returns a mutable iterator over all items currently in the set.

§Examples
use satellite_bitcoin::generic::fixed_set::FixedSet;

let mut set: FixedSet<u32, 10> = FixedSet::new();
set.insert(1).unwrap();
set.insert(2).unwrap();

for item in set.iter_mut() {
    *item *= 10;
}

assert!(set.contains(&10));
assert!(set.contains(&20));
Source

pub fn insert_or_modify<E, F>(&mut self, item: T, modify: F) -> Result<(), E>
where F: FnMut(&mut T) -> Result<(), E>, E: From<FixedSetError>,

Inserts item into the set if it is not already present. If it is present, modifies it using the provided function.

This is useful for implementing “upsert” semantics where you want to insert a new item or update an existing one.

§Examples
use satellite_bitcoin::generic::fixed_set::{FixedSet, FixedSetError};

#[derive(Clone, Copy, Debug, Default)]
struct Counter { id: u32, count: u32 }

impl PartialEq for Counter {
    fn eq(&self, other: &Self) -> bool {
        self.id == other.id // Only compare by ID
    }
}

impl Eq for Counter {}

#[derive(Debug)]
enum MyError {
    SetError(FixedSetError),
}

impl From<FixedSetError> for MyError {
    fn from(e: FixedSetError) -> Self {
        MyError::SetError(e)
    }
}

let mut set: FixedSet<Counter, 10> = FixedSet::new();

// Insert new item
set.insert_or_modify(
    Counter { id: 1, count: 1 },
    |_| Ok::<(), MyError>(())
).unwrap();

// Update existing item
set.insert_or_modify(
    Counter { id: 1, count: 0 }, // count doesn't matter for lookup
    |existing| { existing.count += 1; Ok::<(), MyError>(()) }
).unwrap();

assert_eq!(set.find(&Counter { id: 1, count: 0 }).unwrap().count, 2);
Source

pub fn contains<Q>(&self, item: &Q) -> bool
where T: PartialEq<Q>,

Returns true if the set already contains item.

§Examples
use satellite_bitcoin::generic::fixed_set::FixedSet;

let mut set: FixedSet<u32, 10> = FixedSet::new();
assert!(!set.contains(&42));

set.insert(42).unwrap();
assert!(set.contains(&42));
Source

pub fn find<Q>(&self, item: &Q) -> Option<&T>
where T: PartialEq<Q>,

Returns the first item equal to item in the set.

This is useful when you need to access the actual stored item that matches your query, especially when using custom equality implementations.

§Examples
use satellite_bitcoin::generic::fixed_set::FixedSet;

let mut set: FixedSet<u32, 10> = FixedSet::new();
set.insert(42).unwrap();

assert_eq!(set.find(&42), Some(&42));
assert_eq!(set.find(&99), None);
Source

pub fn find_mut<Q>(&mut self, item: &Q) -> Option<&mut T>
where T: PartialEq<Q>,

Returns the first item equal to item in the set (mutable reference).

§Examples
use satellite_bitcoin::generic::fixed_set::FixedSet;

let mut set: FixedSet<u32, 10> = FixedSet::new();
set.insert(42).unwrap();

if let Some(item) = set.find_mut(&42) {
    *item = 100;
}

assert!(set.contains(&100));
assert!(!set.contains(&42));
Source

pub fn insert(&mut self, item: T) -> Result<(), FixedSetError>

Attempts to insert item into the set.

§Errors
  • Returns Err(FixedSetError::Duplicate) if the item already exists in the set.
  • Returns Err(FixedSetError::Full) if the set is at full capacity.
§Examples
use satellite_bitcoin::generic::fixed_set::{FixedSet, FixedSetError};

let mut set: FixedSet<u32, 2> = FixedSet::new();
assert!(set.insert(1).is_ok());
assert!(set.insert(2).is_ok());

// Duplicate
assert_eq!(set.insert(1), Err(FixedSetError::Duplicate));
// Full
assert_eq!(set.insert(3), Err(FixedSetError::Full));
Source

pub fn remove<Q>(&mut self, item: &Q) -> Option<T>
where T: PartialEq<Q>,

Removes an item equal to item from the set and returns it.

Uses swap-remove for O(1) performance, which means element order is not preserved.

§Examples
use satellite_bitcoin::generic::fixed_set::FixedSet;

let mut set: FixedSet<u32, 10> = FixedSet::new();
set.insert(42).unwrap();

assert_eq!(set.remove(&42), Some(42));
assert_eq!(set.remove(&42), None);
assert_eq!(set.len(), 0);
Source

pub fn pop(&mut self) -> Option<T>

Removes and returns an arbitrary element from the set (the last one).

Source

pub fn as_slice(&self) -> &[T]

Returns the elements of the set as a slice.

Source

pub fn as_mut_slice(&mut self) -> &mut [T]

Returns the elements of the set as a mutable slice.

Source

pub fn try_from_iter<I>(iter: I) -> Result<FixedSet<T, SIZE>, FixedSetError>
where I: IntoIterator<Item = T>,

Creates a FixedSet from any iterator, returning an error if the number of unique elements exceeds the set’s capacity.

Duplicate elements yielded by the iterator are ignored (because a set cannot contain the same value twice). However, if inserting additional unique elements would exceed the compile-time capacity SIZE, the construction fails with FixedSetError::Full.

Source

pub fn get(&self) -> Option<&T>

Returns a reference to the first element in the set (if any).

This is a convenience helper useful when the set is known to hold at most one element (e.g. single‐rune outputs). It avoids having to call as_slice().first() at every call-site.

Trait Implementations§

Source§

impl<T, const SIZE: usize> Clone for FixedSet<T, SIZE>
where T: Clone,

Source§

fn clone(&self) -> FixedSet<T, SIZE>

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

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

Performs copy-assignment from source. Read more
Source§

impl<T, const SIZE: usize> Copy for FixedSet<T, SIZE>
where T: Copy,

Source§

impl<T, const SIZE: usize> Debug for FixedSet<T, SIZE>
where T: Debug,

Source§

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

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

impl<T, const SIZE: usize> Default for FixedSet<T, SIZE>
where T: Default + Copy + PartialEq,

Source§

fn default() -> FixedSet<T, SIZE>

Returns the “default value” for a type. Read more
Source§

impl<T, const SIZE: usize> FixedCapacitySet for FixedSet<T, SIZE>
where T: Default + Copy + PartialEq + Debug,

Source§

type Item = T

The element type stored in the set.
Source§

fn capacity(&self) -> usize

Maximum number of elements the set can hold.
Source§

fn len(&self) -> usize

Current number of stored elements.
Source§

fn contains<Q>(&self, item: &Q) -> bool
where <FixedSet<T, SIZE> as FixedCapacitySet>::Item: PartialEq<Q>,

Check whether the set currently contains item.
Source§

fn find<Q>( &self, item: &Q, ) -> Option<&<FixedSet<T, SIZE> as FixedCapacitySet>::Item>
where <FixedSet<T, SIZE> as FixedCapacitySet>::Item: PartialEq<Q>,

Find the first item equal to item in the set.
Source§

fn find_mut<Q>( &mut self, item: &Q, ) -> Option<&mut <FixedSet<T, SIZE> as FixedCapacitySet>::Item>
where <FixedSet<T, SIZE> as FixedCapacitySet>::Item: PartialEq<Q>,

Find the first item equal to item in the set and return it.
Source§

fn insert( &mut self, item: <FixedSet<T, SIZE> as FixedCapacitySet>::Item, ) -> Result<(), FixedSetError>

Attempt to insert item. Returns Ok(()) on success or an appropriate FixedSetError.
Source§

fn insert_or_modify<E, F>( &mut self, item: <FixedSet<T, SIZE> as FixedCapacitySet>::Item, modify: F, ) -> Result<(), E>
where F: FnMut(&mut <FixedSet<T, SIZE> as FixedCapacitySet>::Item) -> Result<(), E>, E: From<FixedSetError>,

Inserts item into the set if it is not already present. If it is present, modifies it using the provided function. Returns Ok(()) on success or an appropriate FixedSetError.
Source§

fn remove<Q>( &mut self, item: &Q, ) -> Option<<FixedSet<T, SIZE> as FixedCapacitySet>::Item>
where <FixedSet<T, SIZE> as FixedCapacitySet>::Item: PartialEq<Q>,

Remove item if present, returning it.
Source§

fn as_slice(&self) -> &[<FixedSet<T, SIZE> as FixedCapacitySet>::Item]

Access the underlying slice of active items.
Source§

fn as_mut_slice( &mut self, ) -> &mut [<FixedSet<T, SIZE> as FixedCapacitySet>::Item]

Returns the elements of the set as a mutable slice.
Source§

fn iter(&self) -> impl Iterator<Item = &Self::Item>

Iterate over the set.
Source§

fn iter_mut(&mut self) -> impl Iterator<Item = &mut Self::Item>

Iterate over the set mutably.
Source§

impl<T, const SIZE: usize> From<FixedList<T, SIZE>> for FixedSet<T, SIZE>
where T: Default + Copy + PartialEq,

Source§

fn from(list: FixedList<T, SIZE>) -> FixedSet<T, SIZE>

Converts to this type from the input type.
Source§

impl<T, const SIZE: usize> From<FixedSet<T, SIZE>> for FixedList<T, SIZE>
where T: Default + Clone + Copy + PartialEq,

Source§

fn from(set: FixedSet<T, SIZE>) -> FixedList<T, SIZE>

Converts to this type from the input type.
Source§

impl<T, const SIZE: usize> Pod for FixedSet<T, SIZE>
where T: Pod,

Source§

impl<T, const SIZE: usize> PushPopCollection<T> for FixedSet<T, SIZE>
where T: Default + Copy + PartialEq,

Source§

fn push(&mut self, item: T) -> Result<(), PushPopError>

Adds an element to the collection. Read more
Source§

fn pop(&mut self) -> Option<T>

Removes and returns the last element, or None if the collection is empty. Read more
Source§

fn as_slice(&self) -> &[T]

Returns a slice view of all elements in the collection. Read more
Source§

fn len(&self) -> usize

Returns the number of elements in the collection. Read more
Source§

fn max_size(&self) -> usize

Returns the maximum number of elements the collection can hold. Read more
Source§

impl<T, const SIZE: usize> TryFrom<&[T]> for FixedSet<T, SIZE>
where T: Default + Copy + PartialEq,

Source§

type Error = FixedSetError

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

fn try_from( slice: &[T], ) -> Result<FixedSet<T, SIZE>, <FixedSet<T, SIZE> as TryFrom<&[T]>>::Error>

Performs the conversion.
Source§

impl<T, const SIZE: usize> Zeroable for FixedSet<T, SIZE>
where T: Zeroable,

Source§

fn zeroed() -> Self

Auto Trait Implementations§

§

impl<T, const SIZE: usize> Freeze for FixedSet<T, SIZE>
where T: Freeze,

§

impl<T, const SIZE: usize> RefUnwindSafe for FixedSet<T, SIZE>
where T: RefUnwindSafe,

§

impl<T, const SIZE: usize> Send for FixedSet<T, SIZE>
where T: Send,

§

impl<T, const SIZE: usize> Sync for FixedSet<T, SIZE>
where T: Sync,

§

impl<T, const SIZE: usize> Unpin for FixedSet<T, SIZE>
where T: Unpin,

§

impl<T, const SIZE: usize> UnsafeUnpin for FixedSet<T, SIZE>
where T: UnsafeUnpin,

§

impl<T, const SIZE: usize> UnwindSafe for FixedSet<T, SIZE>
where T: UnwindSafe,

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> AnyBitPattern for T
where T: Pod,

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> CheckedBitPattern for T
where T: AnyBitPattern,

Source§

type Bits = T

Self must have the same layout as the specified Bits except for the possible invalid bit patterns being checked during is_valid_bit_pattern.
Source§

fn is_valid_bit_pattern(_bits: &T) -> bool

If this function returns true, then it must be valid to reinterpret bits as &Self.
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> NoUninit for T
where T: Pod,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
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, 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.
Source§

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

Source§

fn vzip(self) -> V