pod_read_unaligned and try_pod_read_unaligned (#92)

* pod_read_unaligned and try_pod_read_unaligned

* only do all-features on nightly.

* I forgot we can't use .cast on 1.34
This commit is contained in:
Lokathor 2022-03-01 18:09:49 -07:00 committed by GitHub
parent 6029639753
commit 7fa51a420d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 29 additions and 0 deletions

View File

@ -35,6 +35,7 @@ jobs:
- uses: actions/checkout@v2
- run: cargo test --verbose
- run: cargo test --verbose --no-default-features
- run: cargo test --verbose
- run: cargo test --verbose --all-features
if: matrix.rust == 'nightly'
- run: cargo test --verbose --manifest-path=derive/Cargo.toml --all-features
@ -54,8 +55,11 @@ jobs:
- uses: actions/checkout@v2
- run: cargo install cross
- run: cross test --verbose --target=${{ matrix.target }} --no-default-features
- run: cross test --verbose --target=${{ matrix.target }}
- run: cross test --verbose --target=${{ matrix.target }} --all-features
if: matrix.rust == 'nightly'
- run: cross test --verbose --target=${{ matrix.target }} --manifest-path=derive/Cargo.toml --all-features
if: matrix.rust == 'nightly'
miri-test:
name: Test with miri

View File

@ -186,6 +186,31 @@ pub fn from_bytes_mut<T: Pod>(s: &mut [u8]) -> &mut T {
}
}
/// Reads from the bytes as if they were a `T`.
///
/// ## Failure
/// * If the `bytes` length is not equal to `size_of::<T>()`.
#[inline]
pub fn try_pod_read_unaligned<T: Pod>(bytes: &[u8]) -> Result<T, PodCastError> {
if bytes.len() != size_of::<T>() {
Err(PodCastError::SizeMismatch)
} else {
Ok(unsafe { (bytes.as_ptr() as *const T).read_unaligned() })
}
}
/// Reads the slice into a `T` value.
///
/// ## Panics
/// * This is like `try_pod_read_unaligned` but will panic on failure.
#[inline]
pub fn pod_read_unaligned<T: Pod>(bytes: &[u8]) -> T {
match try_pod_read_unaligned(bytes) {
Ok(t) => t,
Err(e) => something_went_wrong("pod_read_unaligned", e),
}
}
/// Re-interprets `&[u8]` as `&T`.
///
/// ## Failure