Skip to content

Commit 7f1a6cd

Browse files
committed
refactor: Remove redundant, private OsStr::bytes
1 parent 8d2beb5 commit 7f1a6cd

File tree

9 files changed

+41
-48
lines changed

9 files changed

+41
-48
lines changed

library/std/src/ffi/os_str.rs

Lines changed: 9 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -702,7 +702,7 @@ impl OsStr {
702702
/// [conversions]: super#conversions
703703
#[inline]
704704
#[unstable(feature = "os_str_bytes", issue = "111544")]
705-
pub fn from_os_str_bytes_unchecked(bytes: &[u8]) -> &Self {
705+
pub unsafe fn from_os_str_bytes_unchecked(bytes: &[u8]) -> &Self {
706706
Self::from_inner(Slice::from_os_str_bytes_unchecked(bytes))
707707
}
708708

@@ -891,15 +891,6 @@ impl OsStr {
891891
self.inner.as_os_str_bytes()
892892
}
893893

894-
/// Gets the underlying byte representation.
895-
///
896-
/// Note: it is *crucial* that this API is not externally public, to avoid
897-
/// revealing the internal, platform-specific encodings.
898-
#[inline]
899-
pub(crate) fn bytes(&self) -> &[u8] {
900-
self.as_os_str_bytes()
901-
}
902-
903894
/// Converts this string to its ASCII lower case equivalent in-place.
904895
///
905896
/// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
@@ -1185,7 +1176,7 @@ impl Default for &OsStr {
11851176
impl PartialEq for OsStr {
11861177
#[inline]
11871178
fn eq(&self, other: &OsStr) -> bool {
1188-
self.bytes().eq(other.bytes())
1179+
self.as_os_str_bytes().eq(other.as_os_str_bytes())
11891180
}
11901181
}
11911182

@@ -1212,23 +1203,23 @@ impl Eq for OsStr {}
12121203
impl PartialOrd for OsStr {
12131204
#[inline]
12141205
fn partial_cmp(&self, other: &OsStr) -> Option<cmp::Ordering> {
1215-
self.bytes().partial_cmp(other.bytes())
1206+
self.as_os_str_bytes().partial_cmp(other.as_os_str_bytes())
12161207
}
12171208
#[inline]
12181209
fn lt(&self, other: &OsStr) -> bool {
1219-
self.bytes().lt(other.bytes())
1210+
self.as_os_str_bytes().lt(other.as_os_str_bytes())
12201211
}
12211212
#[inline]
12221213
fn le(&self, other: &OsStr) -> bool {
1223-
self.bytes().le(other.bytes())
1214+
self.as_os_str_bytes().le(other.as_os_str_bytes())
12241215
}
12251216
#[inline]
12261217
fn gt(&self, other: &OsStr) -> bool {
1227-
self.bytes().gt(other.bytes())
1218+
self.as_os_str_bytes().gt(other.as_os_str_bytes())
12281219
}
12291220
#[inline]
12301221
fn ge(&self, other: &OsStr) -> bool {
1231-
self.bytes().ge(other.bytes())
1222+
self.as_os_str_bytes().ge(other.as_os_str_bytes())
12321223
}
12331224
}
12341225

@@ -1247,7 +1238,7 @@ impl PartialOrd<str> for OsStr {
12471238
impl Ord for OsStr {
12481239
#[inline]
12491240
fn cmp(&self, other: &OsStr) -> cmp::Ordering {
1250-
self.bytes().cmp(other.bytes())
1241+
self.as_os_str_bytes().cmp(other.as_os_str_bytes())
12511242
}
12521243
}
12531244

@@ -1297,7 +1288,7 @@ impl_cmp!(Cow<'a, OsStr>, OsString);
12971288
impl Hash for OsStr {
12981289
#[inline]
12991290
fn hash<H: Hasher>(&self, state: &mut H) {
1300-
self.bytes().hash(state)
1291+
self.as_os_str_bytes().hash(state)
13011292
}
13021293
}
13031294

library/std/src/path.rs

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -193,7 +193,7 @@ impl<'a> Prefix<'a> {
193193
fn len(&self) -> usize {
194194
use self::Prefix::*;
195195
fn os_str_len(s: &OsStr) -> usize {
196-
s.bytes().len()
196+
s.as_os_str_bytes().len()
197197
}
198198
match *self {
199199
Verbatim(x) => 4 + os_str_len(x),
@@ -330,15 +330,15 @@ fn has_physical_root(s: &[u8], prefix: Option<Prefix<'_>>) -> bool {
330330

331331
// basic workhorse for splitting stem and extension
332332
fn rsplit_file_at_dot(file: &OsStr) -> (Option<&OsStr>, Option<&OsStr>) {
333-
if file.bytes() == b".." {
333+
if file.as_os_str_bytes() == b".." {
334334
return (Some(file), None);
335335
}
336336

337337
// The unsafety here stems from converting between &OsStr and &[u8]
338338
// and back. This is safe to do because (1) we only look at ASCII
339339
// contents of the encoding and (2) new &OsStr values are produced
340340
// only from ASCII-bounded slices of existing &OsStr values.
341-
let mut iter = file.bytes().rsplitn(2, |b| *b == b'.');
341+
let mut iter = file.as_os_str_bytes().rsplitn(2, |b| *b == b'.');
342342
let after = iter.next();
343343
let before = iter.next();
344344
if before == Some(b"") {
@@ -349,7 +349,7 @@ fn rsplit_file_at_dot(file: &OsStr) -> (Option<&OsStr>, Option<&OsStr>) {
349349
}
350350

351351
fn split_file_at_dot(file: &OsStr) -> (&OsStr, Option<&OsStr>) {
352-
let slice = file.bytes();
352+
let slice = file.as_os_str_bytes();
353353
if slice == b".." {
354354
return (file, None);
355355
}
@@ -1481,17 +1481,17 @@ impl PathBuf {
14811481
fn _set_extension(&mut self, extension: &OsStr) -> bool {
14821482
let file_stem = match self.file_stem() {
14831483
None => return false,
1484-
Some(f) => f.bytes(),
1484+
Some(f) => f.as_os_str_bytes(),
14851485
};
14861486

14871487
// truncate until right after the file stem
14881488
let end_file_stem = file_stem[file_stem.len()..].as_ptr().addr();
1489-
let start = self.inner.bytes().as_ptr().addr();
1489+
let start = self.inner.as_os_str_bytes().as_ptr().addr();
14901490
let v = self.as_mut_vec();
14911491
v.truncate(end_file_stem.wrapping_sub(start));
14921492

14931493
// add the new extension, if any
1494-
let new = extension.bytes();
1494+
let new = extension.as_os_str_bytes();
14951495
if !new.is_empty() {
14961496
v.reserve_exact(new.len() + 1);
14971497
v.push(b'.');
@@ -2015,7 +2015,7 @@ impl Path {
20152015
}
20162016
// The following (private!) function reveals the byte encoding used for OsStr.
20172017
fn as_u8_slice(&self) -> &[u8] {
2018-
self.inner.bytes()
2018+
self.inner.as_os_str_bytes()
20192019
}
20202020

20212021
/// Directly wraps a string slice as a `Path` slice.

library/std/src/sys/common/small_c_string.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ pub fn run_path_with_cstr<T, F>(path: &Path, f: F) -> io::Result<T>
1919
where
2020
F: FnOnce(&CStr) -> io::Result<T>,
2121
{
22-
run_with_cstr(path.as_os_str().bytes(), f)
22+
run_with_cstr(path.as_os_str().as_os_str_bytes(), f)
2323
}
2424

2525
#[inline]

library/std/src/sys/common/tests.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use core::iter::repeat;
88
fn stack_allocation_works() {
99
let path = Path::new("abc");
1010
let result = run_path_with_cstr(path, |p| {
11-
assert_eq!(p, &*CString::new(path.as_os_str().bytes()).unwrap());
11+
assert_eq!(p, &*CString::new(path.as_os_str().as_os_str_bytes()).unwrap());
1212
Ok(42)
1313
});
1414
assert_eq!(result.unwrap(), 42);
@@ -25,7 +25,7 @@ fn heap_allocation_works() {
2525
let path = repeat("a").take(384).collect::<String>();
2626
let path = Path::new(&path);
2727
let result = run_path_with_cstr(path, |p| {
28-
assert_eq!(p, &*CString::new(path.as_os_str().bytes()).unwrap());
28+
assert_eq!(p, &*CString::new(path.as_os_str().as_os_str_bytes()).unwrap());
2929
Ok(42)
3030
});
3131
assert_eq!(result.unwrap(), 42);

library/std/src/sys/unix/path.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ pub(crate) fn absolute(path: &Path) -> io::Result<PathBuf> {
3030

3131
// Get the components, skipping the redundant leading "." component if it exists.
3232
let mut components = path.strip_prefix(".").unwrap_or(path).components();
33-
let path_os = path.as_os_str().bytes();
33+
let path_os = path.as_os_str().as_os_str_bytes();
3434

3535
let mut normalized = if path.is_absolute() {
3636
// "If a pathname begins with two successive <slash> characters, the

library/std/src/sys/unix/process/process_common.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -164,9 +164,9 @@ pub enum ProgramKind {
164164

165165
impl ProgramKind {
166166
fn new(program: &OsStr) -> Self {
167-
if program.bytes().starts_with(b"/") {
167+
if program.as_os_str_bytes().starts_with(b"/") {
168168
Self::Absolute
169-
} else if program.bytes().contains(&b'/') {
169+
} else if program.as_os_str_bytes().contains(&b'/') {
170170
// If the program has more than one component in it, it is a relative path.
171171
Self::Relative
172172
} else {

library/std/src/sys/windows/args.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -226,7 +226,7 @@ pub(crate) fn append_arg(cmd: &mut Vec<u16>, arg: &Arg, force_quotes: bool) -> i
226226
// that it actually gets passed through on the command line or otherwise
227227
// it will be dropped entirely when parsed on the other end.
228228
ensure_no_nuls(arg)?;
229-
let arg_bytes = arg.bytes();
229+
let arg_bytes = arg.as_os_str_bytes();
230230
let (quote, escape) = match quote {
231231
Quote::Always => (true, true),
232232
Quote::Auto => {
@@ -297,7 +297,9 @@ pub(crate) fn make_bat_command_line(
297297
// * `|<>` pipe/redirect characters.
298298
const SPECIAL: &[u8] = b"\t &()[]{}^=;!'+,`~%|<>";
299299
let force_quotes = match arg {
300-
Arg::Regular(arg) if !force_quotes => arg.bytes().iter().any(|c| SPECIAL.contains(c)),
300+
Arg::Regular(arg) if !force_quotes => {
301+
arg.as_os_str_bytes().iter().any(|c| SPECIAL.contains(c))
302+
}
301303
_ => force_quotes,
302304
};
303305
append_arg(&mut cmd, arg, force_quotes)?;

library/std/src/sys/windows/path.rs

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -33,12 +33,12 @@ pub fn is_verbatim_sep(b: u8) -> bool {
3333

3434
/// Returns true if `path` looks like a lone filename.
3535
pub(crate) fn is_file_name(path: &OsStr) -> bool {
36-
!path.bytes().iter().copied().any(is_sep_byte)
36+
!path.as_os_str_bytes().iter().copied().any(is_sep_byte)
3737
}
3838
pub(crate) fn has_trailing_slash(path: &OsStr) -> bool {
39-
let is_verbatim = path.bytes().starts_with(br"\\?\");
39+
let is_verbatim = path.as_os_str_bytes().starts_with(br"\\?\");
4040
let is_separator = if is_verbatim { is_verbatim_sep } else { is_sep_byte };
41-
if let Some(&c) = path.bytes().last() { is_separator(c) } else { false }
41+
if let Some(&c) = path.as_os_str_bytes().last() { is_separator(c) } else { false }
4242
}
4343

4444
/// Appends a suffix to a path.
@@ -60,7 +60,7 @@ impl<'a, const LEN: usize> PrefixParser<'a, LEN> {
6060
fn get_prefix(path: &OsStr) -> [u8; LEN] {
6161
let mut prefix = [0; LEN];
6262
// SAFETY: Only ASCII characters are modified.
63-
for (i, &ch) in path.bytes().iter().take(LEN).enumerate() {
63+
for (i, &ch) in path.as_os_str_bytes().iter().take(LEN).enumerate() {
6464
prefix[i] = if ch == b'/' { b'\\' } else { ch };
6565
}
6666
prefix
@@ -93,15 +93,15 @@ impl<'a> PrefixParserSlice<'a, '_> {
9393
}
9494

9595
fn prefix_bytes(&self) -> &'a [u8] {
96-
&self.path.bytes()[..self.index]
96+
&self.path.as_os_str_bytes()[..self.index]
9797
}
9898

9999
fn finish(self) -> &'a OsStr {
100100
// SAFETY: The unsafety here stems from converting between &OsStr and
101101
// &[u8] and back. This is safe to do because (1) we only look at ASCII
102102
// contents of the encoding and (2) new &OsStr values are produced only
103103
// from ASCII-bounded slices of existing &OsStr values.
104-
unsafe { bytes_as_os_str(&self.path.bytes()[self.index..]) }
104+
unsafe { bytes_as_os_str(&self.path.as_os_str_bytes()[self.index..]) }
105105
}
106106
}
107107

@@ -173,7 +173,7 @@ fn parse_drive(path: &OsStr) -> Option<u8> {
173173
drive.is_ascii_alphabetic()
174174
}
175175

176-
match path.bytes() {
176+
match path.as_os_str_bytes() {
177177
[drive, b':', ..] if is_valid_drive_letter(drive) => Some(drive.to_ascii_uppercase()),
178178
_ => None,
179179
}
@@ -182,7 +182,7 @@ fn parse_drive(path: &OsStr) -> Option<u8> {
182182
// Parses a drive prefix exactly, e.g. "C:"
183183
fn parse_drive_exact(path: &OsStr) -> Option<u8> {
184184
// only parse two bytes: the drive letter and the drive separator
185-
if path.bytes().get(2).map(|&x| is_sep_byte(x)).unwrap_or(true) {
185+
if path.as_os_str_bytes().get(2).map(|&x| is_sep_byte(x)).unwrap_or(true) {
186186
parse_drive(path)
187187
} else {
188188
None
@@ -196,15 +196,15 @@ fn parse_drive_exact(path: &OsStr) -> Option<u8> {
196196
fn parse_next_component(path: &OsStr, verbatim: bool) -> (&OsStr, &OsStr) {
197197
let separator = if verbatim { is_verbatim_sep } else { is_sep_byte };
198198

199-
match path.bytes().iter().position(|&x| separator(x)) {
199+
match path.as_os_str_bytes().iter().position(|&x| separator(x)) {
200200
Some(separator_start) => {
201201
let separator_end = separator_start + 1;
202202

203-
let component = &path.bytes()[..separator_start];
203+
let component = &path.as_os_str_bytes()[..separator_start];
204204

205205
// Panic safe
206206
// The max `separator_end` is `bytes.len()` and `bytes[bytes.len()..]` is a valid index.
207-
let path = &path.bytes()[separator_end..];
207+
let path = &path.as_os_str_bytes()[separator_end..];
208208

209209
// SAFETY: `path` is a valid wtf8 encoded slice and each of the separators ('/', '\')
210210
// is encoded in a single byte, therefore `bytes[separator_start]` and
@@ -329,7 +329,7 @@ pub(crate) fn absolute(path: &Path) -> io::Result<PathBuf> {
329329
// Verbatim paths should not be modified.
330330
if prefix.map(|x| x.is_verbatim()).unwrap_or(false) {
331331
// NULs in verbatim paths are rejected for consistency.
332-
if path.bytes().contains(&0) {
332+
if path.as_os_str_bytes().contains(&0) {
333333
return Err(io::const_io_error!(
334334
io::ErrorKind::InvalidInput,
335335
"strings passed to WinAPI cannot contain NULs",

library/std/src/sys/windows/process.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -395,7 +395,7 @@ fn resolve_exe<'a>(
395395
// Test if the file name has the `exe` extension.
396396
// This does a case-insensitive `ends_with`.
397397
let has_exe_suffix = if exe_path.len() >= EXE_SUFFIX.len() {
398-
exe_path.bytes()[exe_path.len() - EXE_SUFFIX.len()..]
398+
exe_path.as_os_str_bytes()[exe_path.len() - EXE_SUFFIX.len()..]
399399
.eq_ignore_ascii_case(EXE_SUFFIX.as_bytes())
400400
} else {
401401
false
@@ -425,7 +425,7 @@ fn resolve_exe<'a>(
425425
// From the `CreateProcessW` docs:
426426
// > If the file name does not contain an extension, .exe is appended.
427427
// Note that this rule only applies when searching paths.
428-
let has_extension = exe_path.bytes().contains(&b'.');
428+
let has_extension = exe_path.as_os_str_bytes().contains(&b'.');
429429

430430
// Search the directories given by `search_paths`.
431431
let result = search_paths(parent_paths, child_paths, |mut path| {

0 commit comments

Comments
 (0)