10 hours ago · 8 min read1618 words · Tech · hide · 0 comments

When you need to parse data for downstream processing, the enthusiasm to get the processing outcome quickly might induce you to overlook one interesting nuance of the cost of how it’s parsed. See this “parse me a u64” function for example: fn parse_id(bytes: &[u8]) -> Result<u64, ParserError> { if bytes.len() < 8 { return Err(ParserError::InputTooShortForU64); } let owned = bytes[..8].to_vec(); Ok(u64::from_le_bytes(owned.try_into().map_err(ParserError::InvalidU64)?)) } It checks the length, takes the right amount of bytes from the slice copying them into a Vec and uses it to parse it as u64. All looks short and safe. Now let’s examine it more carefully. For a data type as simple as a number the memory heap should be used or not? What about syscalls? In Rust, a Vec always uses the heap. That allocation might or, if lucky, might not require a syscall. That would depend on whether the allocator already has a free block or has to ask the OS for more memory which can easily happen under…

No comments yet. Log in to reply on the Fediverse. Comments will appear here.