Skip to content

Commit

Permalink
bounded principal
Browse files Browse the repository at this point in the history
  • Loading branch information
F3kilo committed May 30, 2024
1 parent a354ee5 commit ff20f46
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
2 changes: 1 addition & 1 deletion ic-stable-structures/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ version.workspace = true
edition.workspace = true

[dependencies]
candid = { workspace = true }
dfinity-stable-structures = { workspace = true }
memmap2 = { workspace = true, optional = true }
parking_lot = { workspace = true }
Expand All @@ -12,7 +13,6 @@ thiserror = { workspace = true }

[dev-dependencies]
anyhow = { workspace = true }
candid = { workspace = true }
criterion = { workspace = true }
did = { path = "./tests/did" }
ic-cdk = { workspace = true }
Expand Down
33 changes: 33 additions & 0 deletions ic-stable-structures/src/structure/common/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
pub mod ring_buffer;

use candid::Principal;
pub use ring_buffer::{StableRingBuffer, StableRingBufferIndices};

/// A trait for types that have a minimum and maximum value.
Expand Down Expand Up @@ -82,3 +83,35 @@ impl<const N: usize> Bounded for [u8; N] {
const MIN: [u8; N] = [u8::MIN; N];
const MAX: [u8; N] = [u8::MAX; N];
}

/// Principal sorted by two fields:
/// 1) `len: u8` -> min = 0, max = 29;
/// 2) `bytes: [u8; Self::MAX_LENGTH_IN_BYTES]` -> min = [], max = [0xFF; 29];
impl Bounded for Principal {
const MIN: Self = Principal::from_slice(&[]); // Management canister principal;
const MAX: Self = Principal::from_slice(&[0xFF; 29]);
}

#[cfg(test)]
mod tests {
use candid::Principal;

use crate::Bounded;

#[test]
fn correct_principal_bounds() {
let min_principal = Principal::MIN;
let max_principal = Principal::MAX;

let mut some_principals = vec![Principal::anonymous(), Principal::management_canister()];

let other_principals_iter =
(1..30).map(|i| Principal::from_slice(&vec![i as u8; i as usize]));
some_principals.extend(other_principals_iter);

for principal in some_principals {
assert!(principal >= min_principal);
assert!(principal <= max_principal);
}
}
}

0 comments on commit ff20f46

Please sign in to comment.