mirror of
https://github.com/Lokathor/bytemuck.git
synced 2024-11-21 22:32:23 +00:00
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:
parent
6029639753
commit
7fa51a420d
4
.github/workflows/rust.yml
vendored
4
.github/workflows/rust.yml
vendored
@ -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
|
||||
|
25
src/lib.rs
25
src/lib.rs
@ -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
|
||||
|
Loading…
Reference in New Issue
Block a user