[−][src]Crate os_str_bytes
Traits for converting between byte sequences and platform-native strings.
This crate allows interacting with the bytes stored internally by OsStr
and OsString
, without resorting to panics or data corruption for
invalid UTF-8. Thus, methods can be used that are already defined on
[u8]
and Vec<u8>
.
Typically, the only way to losslessly construct OsStr
or OsString
from a byte sequence is to use OsString::from(String::from(bytes)?)
,
which requires the bytes to be valid in UTF-8. However, since this crate
makes conversions directly between the platform encoding and raw bytes,
even some strings invalid in UTF-8 can be converted.
Implementation
All traits are sealed, meaning that they can only be implemented by this crate. Otherwise, backwards compatibility would be more difficult to maintain for new features.
Complexity
The time complexities of methods will vary based on what functionality is
available for the platform. The most efficient implementation will be used,
but it is important to use the most applicable method. For example,
OsStringBytes::from_vec
will be at least as efficient as
OsStringBytes::from_bytes
, but the latter should be used when only a
slice is available.
Safety
A moderately unsafe assumption is made that invalid characters created by
[char::from_u32_unchecked
] are partially usable. The alternative would be
to always encode and decode strings manually, which would be more
dangerous, as it would create a reliance on how the standard library
encodes invalid UTF-8 strings.
The standard library [makes the same assumption][assumption], since there
are no methods on u32
for encoding. Tests exist to validate the
implementation in this crate.
Examples
use std::env::args_os; use std::fs::read_to_string; use std::fs::write; use os_str_bytes::OsStrBytes; for file in args_os().skip(1) { if file.to_bytes().first() != Some(&b'-') { let string = "hello world"; write(&file, string)?; assert_eq!(string, read_to_string(file)?); } }
Structs
EncodingError | The error that occurs when a byte sequence is not representable in the platform encoding. |
Traits
OsStrBytes | A platform agnostic variant of |
OsStringBytes | A platform agnostic variant of |