Skip to content

Zero-Copy Slice Readers #530

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions rbx_binary/src/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,43 @@ pub trait RbxWriteExt: Write {

impl<W> RbxWriteExt for W where W: Write {}

/// Read a binary "string" in the format that Roblox's model files use.
///
/// This function is safer than read_string because Roblox generally makes
/// no guarantees about encoding of things it calls strings. rbx_binary
/// makes a semantic differentiation between strings and binary buffers,
/// which makes it more strict than Roblox but more likely to be correct.
///
/// This function is not part of RbxReadExt, and unlike
/// RbxReadExt::read_binary_string, this function only operates on a byte slice.
pub fn read_binary_string_slice<'a>(slice: &mut &'a [u8]) -> io::Result<&'a [u8]> {
let length = slice.read_le_u32()?;

let out;
// split_at can panic if the slice is shorter than length
// but we do not expect that to happen.
(out, *slice) = slice.split_at(length as usize);

Ok(out)
}

/// Read a UTF-8 encoded string encoded how Roblox model files encode
/// strings. This function isn't always appropriate because Roblox's formats
/// generally aren't dilligent about data being valid Unicode.
///
/// This function is not part of RbxReadExt, and unlike
/// RbxReadExt::read_string, this function only operates on a byte slice.
pub fn read_string_slice<'a>(slice: &mut &'a [u8]) -> io::Result<&'a str> {
let out = read_binary_string_slice(slice)?;

core::str::from_utf8(out).map_err(|_| {
io::Error::new(
io::ErrorKind::InvalidData,
"stream did not contain valid UTF-8",
)
})
}

/// Applies the 'zigzag' transformation done by Roblox to many `i32` values.
pub fn transform_i32(value: i32) -> i32 {
(value << 1) ^ (value >> 31)
Expand Down
Loading