Skip to content

Commit c20e75e

Browse files
committed
rust: types: add little-endian type
It allows us to read/write data in little-endian format. Compared to just using the correctly-sized integer type, it has the advantage of forcing users to convert to and from little endian format (which will be no-ops in little-endian architectures). Signed-off-by: Wedson Almeida Filho <walmeida@microsoft.com>
1 parent e05fa90 commit c20e75e

1 file changed

Lines changed: 45 additions & 0 deletions

File tree

rust/kernel/types.rs

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -395,3 +395,48 @@ pub enum Either<L, R> {
395395
/// Constructs an instance of [`Either`] containing a value of type `R`.
396396
Right(R),
397397
}
398+
399+
/// A type that can be represented in little-endian bytes.
400+
pub trait LittleEndian {
401+
/// Converts from native to little-endian encoding.
402+
fn to_le(self) -> Self;
403+
404+
/// Converts from little-endian to native encoding.
405+
fn to_native(self) -> Self;
406+
}
407+
408+
macro_rules! define_le {
409+
($($t:ty),+) => {
410+
$(
411+
impl LittleEndian for $t {
412+
fn to_le(self) -> Self {
413+
Self::to_le(self)
414+
}
415+
416+
fn to_native(self) -> Self {
417+
Self::from_le(self)
418+
}
419+
}
420+
)*
421+
};
422+
}
423+
424+
define_le!(u16, u32, u64);
425+
426+
/// A little-endian representation of `T`.
427+
#[derive(Clone, Copy)]
428+
#[repr(transparent)]
429+
pub struct LE<T: LittleEndian + Copy>(T);
430+
431+
impl<T: LittleEndian + Copy> LE<T> {
432+
/// Returns the native-endian value.
433+
pub fn value(&self) -> T {
434+
self.0.to_native()
435+
}
436+
}
437+
438+
impl<T: LittleEndian + Copy> core::convert::From<T> for LE<T> {
439+
fn from(value: T) -> LE<T> {
440+
LE(value.to_le())
441+
}
442+
}

0 commit comments

Comments
 (0)