heika_transaction/
bounded.rs1use alloc::vec::Vec;
4use core::fmt;
5use core::ops::Deref;
6
7#[derive(Clone, PartialEq, Eq, Hash, Debug, Default)]
9pub struct BoundedVec<T, const MAX: usize>(Vec<T>);
10
11impl<T, const MAX: usize> BoundedVec<T, MAX> {
12 pub fn new() -> Self {
13 Self(Vec::new())
14 }
15
16 pub fn into_inner(self) -> Vec<T> {
17 self.0
18 }
19}
20
21impl<T, const MAX: usize> TryFrom<Vec<T>> for BoundedVec<T, MAX> {
22 type Error = TooLong;
23
24 fn try_from(items: Vec<T>) -> Result<Self, TooLong> {
25 if items.len() > MAX {
26 return Err(TooLong {
27 length: items.len(),
28 max: MAX,
29 });
30 }
31 Ok(Self(items))
32 }
33}
34
35impl<T, const MAX: usize> Deref for BoundedVec<T, MAX> {
36 type Target = [T];
37
38 fn deref(&self) -> &[T] {
39 &self.0
40 }
41}
42
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub struct TooLong {
46 pub length: usize,
47 pub max: usize,
48}
49
50impl fmt::Display for TooLong {
51 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52 write!(
53 f,
54 "{} 個までしか書けませんが、{} 個ありました",
55 self.max, self.length
56 )
57 }
58}
59
60impl core::error::Error for TooLong {}
61
62#[cfg(test)]
63mod tests {
64 use super::*;
65
66 #[test]
67 fn refuses_more_than_the_maximum() {
68 let items: BoundedVec<u8, 2> = vec![1, 2].try_into().unwrap();
69 assert_eq!(*items, [1, 2]);
70 assert_eq!(
71 BoundedVec::<u8, 2>::try_from(vec![1, 2, 3]),
72 Err(TooLong { length: 3, max: 2 })
73 );
74 }
75}