Skip to content

Commit 7db8ad1

Browse files
committed
[flash] Add convenience functions to Region
Signed-off-by: Miguel Young de la Sota <[email protected]>
1 parent 16cfe6c commit 7db8ad1

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

src/hardware/flash.rs

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -626,4 +626,58 @@ impl Region {
626626
len,
627627
}
628628
}
629+
630+
/// Returns a `Region` big enough to hold a `T`.
631+
pub const fn for_type<T>() -> Self {
632+
Self::new(0, mem::size_of::<T>() as u32)
633+
}
634+
635+
/// Returns a `Region` big enough to hold a `[T]` with the given number of
636+
/// elements.
637+
///
638+
/// Returns `None` on overflow`.
639+
pub fn for_slice<T>(n: usize) -> Option<Self> {
640+
Some(Self::new(0, mem::size_of::<T>().checked_mul(n)? as u32))
641+
}
642+
643+
/// Returns the end address of `self`, pointing one past the end of it.
644+
pub fn end(self) -> u32 {
645+
self.ptr.address.saturating_add(self.len)
646+
}
647+
648+
/// Returns a new `Region` that comes immediately after `self`, with the
649+
/// given length.
650+
pub fn and_then(self, len: u32) -> Self {
651+
Self::new(self.end(), len)
652+
}
653+
654+
/// Interprets `sub` as a subregion of `self`, returning a new `Region` of
655+
/// the same size as `sub`.
656+
///
657+
/// Returns `None` if `sub` is not a subregion of `self`.
658+
pub fn subregion(self, sub: Region) -> Option<Self> {
659+
if sub.len.saturating_add(sub.ptr.address) > self.len {
660+
return None;
661+
}
662+
663+
Some(Region::new(
664+
self.ptr.address.checked_add(sub.ptr.address)?,
665+
sub.len,
666+
))
667+
}
668+
669+
/// Contracts `self` by dropping the first `n` bytes.
670+
///
671+
/// Returns `None` if `n` is greater than `self.len`, or if any overflow
672+
/// occurs.
673+
pub fn skip(self, n: u32) -> Option<Self> {
674+
Some(Region::new(self.ptr.address.checked_add(n)?, self.len.checked_sub(n)?))
675+
}
676+
677+
/// Contracts `self` by dropping the last `n` bytes.
678+
///
679+
/// Returns `None` if `n` is greater than `self.len`.
680+
pub fn skip_back(self, n: u32) -> Option<Self> {
681+
Some(Region::new(self.ptr.address, self.len.checked_sub(n)?))
682+
}
629683
}

0 commit comments

Comments
 (0)