-
Notifications
You must be signed in to change notification settings - Fork 13k
/
Copy pathos_str.rs
1724 lines (1598 loc) · 55.1 KB
/
os_str.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! The [`OsStr`] and [`OsString`] types and associated utilities.
#[cfg(test)]
mod tests;
use crate::borrow::{Borrow, Cow};
use crate::cmp;
use crate::collections::TryReserveError;
use crate::fmt;
use crate::hash::{Hash, Hasher};
use crate::ops::{self, Range};
use crate::rc::Rc;
use crate::slice;
use crate::str::FromStr;
use crate::sync::Arc;
use crate::sys::os_str::{Buf, Slice};
use crate::sys_common::{AsInner, FromInner, IntoInner};
/// A type that can represent owned, mutable platform-native strings, but is
/// cheaply inter-convertible with Rust strings.
///
/// The need for this type arises from the fact that:
///
/// * On Unix systems, strings are often arbitrary sequences of non-zero
/// bytes, in many cases interpreted as UTF-8.
///
/// * On Windows, strings are often arbitrary sequences of non-zero 16-bit
/// values, interpreted as UTF-16 when it is valid to do so.
///
/// * In Rust, strings are always valid UTF-8, which may contain zeros.
///
/// `OsString` and [`OsStr`] bridge this gap by simultaneously representing Rust
/// and platform-native string values, and in particular allowing a Rust string
/// to be converted into an "OS" string with no cost if possible. A consequence
/// of this is that `OsString` instances are *not* `NUL` terminated; in order
/// to pass to e.g., Unix system call, you should create a [`CStr`].
///
/// `OsString` is to <code>&[OsStr]</code> as [`String`] is to <code>&[str]</code>: the former
/// in each pair are owned strings; the latter are borrowed
/// references.
///
/// Note, `OsString` and [`OsStr`] internally do not necessarily hold strings in
/// the form native to the platform; While on Unix, strings are stored as a
/// sequence of 8-bit values, on Windows, where strings are 16-bit value based
/// as just discussed, strings are also actually stored as a sequence of 8-bit
/// values, encoded in a less-strict variant of UTF-8. This is useful to
/// understand when handling capacity and length values.
///
/// # Capacity of `OsString`
///
/// Capacity uses units of UTF-8 bytes for OS strings which were created from valid unicode, and
/// uses units of bytes in an unspecified encoding for other contents. On a given target, all
/// `OsString` and `OsStr` values use the same units for capacity, so the following will work:
/// ```
/// use std::ffi::{OsStr, OsString};
///
/// fn concat_os_strings(a: &OsStr, b: &OsStr) -> OsString {
/// let mut ret = OsString::with_capacity(a.len() + b.len()); // This will allocate
/// ret.push(a); // This will not allocate further
/// ret.push(b); // This will not allocate further
/// ret
/// }
/// ```
///
/// # Creating an `OsString`
///
/// **From a Rust string**: `OsString` implements
/// <code>[From]<[String]></code>, so you can use <code>my_string.[into]\()</code> to
/// create an `OsString` from a normal Rust string.
///
/// **From slices:** Just like you can start with an empty Rust
/// [`String`] and then [`String::push_str`] some <code>&[str]</code>
/// sub-string slices into it, you can create an empty `OsString` with
/// the [`OsString::new`] method and then push string slices into it with the
/// [`OsString::push`] method.
///
/// # Extracting a borrowed reference to the whole OS string
///
/// You can use the [`OsString::as_os_str`] method to get an <code>&[OsStr]</code> from
/// an `OsString`; this is effectively a borrowed reference to the
/// whole string.
///
/// # Conversions
///
/// See the [module's toplevel documentation about conversions][conversions] for a discussion on
/// the traits which `OsString` implements for [conversions] from/to native representations.
///
/// [`CStr`]: crate::ffi::CStr
/// [conversions]: super#conversions
/// [into]: Into::into
#[cfg_attr(not(test), rustc_diagnostic_item = "OsString")]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct OsString {
inner: Buf,
}
/// Allows extension traits within `std`.
#[unstable(feature = "sealed", issue = "none")]
impl crate::sealed::Sealed for OsString {}
/// Borrowed reference to an OS string (see [`OsString`]).
///
/// This type represents a borrowed reference to a string in the operating system's preferred
/// representation.
///
/// `&OsStr` is to [`OsString`] as <code>&[str]</code> is to [`String`]: the
/// former in each pair are borrowed references; the latter are owned strings.
///
/// See the [module's toplevel documentation about conversions][conversions] for a discussion on
/// the traits which `OsStr` implements for [conversions] from/to native representations.
///
/// [conversions]: super#conversions
#[cfg_attr(not(test), rustc_diagnostic_item = "OsStr")]
#[stable(feature = "rust1", since = "1.0.0")]
// `OsStr::from_inner` current implementation relies
// on `OsStr` being layout-compatible with `Slice`.
// However, `OsStr` layout is considered an implementation detail and must not be relied upon. We
// want `repr(transparent)` but we don't want it to show up in rustdoc, so we hide it under
// `cfg(doc)`. This is an ad-hoc implementation of attribute privacy.
#[cfg_attr(not(doc), repr(transparent))]
pub struct OsStr {
inner: Slice,
}
/// Allows extension traits within `std`.
#[unstable(feature = "sealed", issue = "none")]
impl crate::sealed::Sealed for OsStr {}
impl OsString {
/// Constructs a new empty `OsString`.
///
/// # Examples
///
/// ```
/// use std::ffi::OsString;
///
/// let os_string = OsString::new();
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[must_use]
#[inline]
pub fn new() -> OsString {
OsString { inner: Buf::from_string(String::new()) }
}
/// Converts bytes to an `OsString` without checking that the bytes contains
/// valid [`OsStr`]-encoded data.
///
/// The byte encoding is an unspecified, platform-specific, self-synchronizing superset of UTF-8.
/// By being a self-synchronizing superset of UTF-8, this encoding is also a superset of 7-bit
/// ASCII.
///
/// See the [module's toplevel documentation about conversions][conversions] for safe,
/// cross-platform [conversions] from/to native representations.
///
/// # Safety
///
/// As the encoding is unspecified, callers must pass in bytes that originated as a mixture of
/// validated UTF-8 and bytes from [`OsStr::as_encoded_bytes`] from within the same Rust version
/// built for the same target platform. For example, reconstructing an `OsString` from bytes sent
/// over the network or stored in a file will likely violate these safety rules.
///
/// Due to the encoding being self-synchronizing, the bytes from [`OsStr::as_encoded_bytes`] can be
/// split either immediately before or immediately after any valid non-empty UTF-8 substring.
///
/// # Example
///
/// ```
/// use std::ffi::OsStr;
///
/// let os_str = OsStr::new("Mary had a little lamb");
/// let bytes = os_str.as_encoded_bytes();
/// let words = bytes.split(|b| *b == b' ');
/// let words: Vec<&OsStr> = words.map(|word| {
/// // SAFETY:
/// // - Each `word` only contains content that originated from `OsStr::as_encoded_bytes`
/// // - Only split with ASCII whitespace which is a non-empty UTF-8 substring
/// unsafe { OsStr::from_encoded_bytes_unchecked(word) }
/// }).collect();
/// ```
///
/// [conversions]: super#conversions
#[inline]
#[stable(feature = "os_str_bytes", since = "1.74.0")]
pub unsafe fn from_encoded_bytes_unchecked(bytes: Vec<u8>) -> Self {
OsString { inner: Buf::from_encoded_bytes_unchecked(bytes) }
}
/// Converts to an [`OsStr`] slice.
///
/// # Examples
///
/// ```
/// use std::ffi::{OsString, OsStr};
///
/// let os_string = OsString::from("foo");
/// let os_str = OsStr::new("foo");
/// assert_eq!(os_string.as_os_str(), os_str);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[must_use]
#[inline]
pub fn as_os_str(&self) -> &OsStr {
self
}
/// Converts the `OsString` into a byte slice. To convert the byte slice back into an
/// `OsString`, use the [`OsStr::from_encoded_bytes_unchecked`] function.
///
/// The byte encoding is an unspecified, platform-specific, self-synchronizing superset of UTF-8.
/// By being a self-synchronizing superset of UTF-8, this encoding is also a superset of 7-bit
/// ASCII.
///
/// Note: As the encoding is unspecified, any sub-slice of bytes that is not valid UTF-8 should
/// be treated as opaque and only comparable within the same Rust version built for the same
/// target platform. For example, sending the bytes over the network or storing it in a file
/// will likely result in incompatible data. See [`OsString`] for more encoding details
/// and [`std::ffi`] for platform-specific, specified conversions.
///
/// [`std::ffi`]: crate::ffi
#[inline]
#[stable(feature = "os_str_bytes", since = "1.74.0")]
pub fn into_encoded_bytes(self) -> Vec<u8> {
self.inner.into_encoded_bytes()
}
/// Converts the `OsString` into a [`String`] if it contains valid Unicode data.
///
/// On failure, ownership of the original `OsString` is returned.
///
/// # Examples
///
/// ```
/// use std::ffi::OsString;
///
/// let os_string = OsString::from("foo");
/// let string = os_string.into_string();
/// assert_eq!(string, Ok(String::from("foo")));
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn into_string(self) -> Result<String, OsString> {
self.inner.into_string().map_err(|buf| OsString { inner: buf })
}
/// Extends the string with the given <code>&[OsStr]</code> slice.
///
/// # Examples
///
/// ```
/// use std::ffi::OsString;
///
/// let mut os_string = OsString::from("foo");
/// os_string.push("bar");
/// assert_eq!(&os_string, "foobar");
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
#[rustc_confusables("append", "put")]
pub fn push<T: AsRef<OsStr>>(&mut self, s: T) {
self.inner.push_slice(&s.as_ref().inner)
}
/// Creates a new `OsString` with at least the given capacity.
///
/// The string will be able to hold at least `capacity` length units of other
/// OS strings without reallocating. This method is allowed to allocate for
/// more units than `capacity`. If `capacity` is 0, the string will not
/// allocate.
///
/// See the main `OsString` documentation information about encoding and capacity units.
///
/// # Examples
///
/// ```
/// use std::ffi::OsString;
///
/// let mut os_string = OsString::with_capacity(10);
/// let capacity = os_string.capacity();
///
/// // This push is done without reallocating
/// os_string.push("foo");
///
/// assert_eq!(capacity, os_string.capacity());
/// ```
#[stable(feature = "osstring_simple_functions", since = "1.9.0")]
#[must_use]
#[inline]
pub fn with_capacity(capacity: usize) -> OsString {
OsString { inner: Buf::with_capacity(capacity) }
}
/// Truncates the `OsString` to zero length.
///
/// # Examples
///
/// ```
/// use std::ffi::OsString;
///
/// let mut os_string = OsString::from("foo");
/// assert_eq!(&os_string, "foo");
///
/// os_string.clear();
/// assert_eq!(&os_string, "");
/// ```
#[stable(feature = "osstring_simple_functions", since = "1.9.0")]
#[inline]
pub fn clear(&mut self) {
self.inner.clear()
}
/// Returns the capacity this `OsString` can hold without reallocating.
///
/// See the main `OsString` documentation information about encoding and capacity units.
///
/// # Examples
///
/// ```
/// use std::ffi::OsString;
///
/// let os_string = OsString::with_capacity(10);
/// assert!(os_string.capacity() >= 10);
/// ```
#[stable(feature = "osstring_simple_functions", since = "1.9.0")]
#[must_use]
#[inline]
pub fn capacity(&self) -> usize {
self.inner.capacity()
}
/// Reserves capacity for at least `additional` more capacity to be inserted
/// in the given `OsString`. Does nothing if the capacity is
/// already sufficient.
///
/// The collection may reserve more space to speculatively avoid frequent reallocations.
///
/// See the main `OsString` documentation information about encoding and capacity units.
///
/// # Examples
///
/// ```
/// use std::ffi::OsString;
///
/// let mut s = OsString::new();
/// s.reserve(10);
/// assert!(s.capacity() >= 10);
/// ```
#[stable(feature = "osstring_simple_functions", since = "1.9.0")]
#[inline]
pub fn reserve(&mut self, additional: usize) {
self.inner.reserve(additional)
}
/// Tries to reserve capacity for at least `additional` more length units
/// in the given `OsString`. The string may reserve more space to speculatively avoid
/// frequent reallocations. After calling `try_reserve`, capacity will be
/// greater than or equal to `self.len() + additional` if it returns `Ok(())`.
/// Does nothing if capacity is already sufficient. This method preserves
/// the contents even if an error occurs.
///
/// See the main `OsString` documentation information about encoding and capacity units.
///
/// # Errors
///
/// If the capacity overflows, or the allocator reports a failure, then an error
/// is returned.
///
/// # Examples
///
/// ```
/// use std::ffi::{OsStr, OsString};
/// use std::collections::TryReserveError;
///
/// fn process_data(data: &str) -> Result<OsString, TryReserveError> {
/// let mut s = OsString::new();
///
/// // Pre-reserve the memory, exiting if we can't
/// s.try_reserve(OsStr::new(data).len())?;
///
/// // Now we know this can't OOM in the middle of our complex work
/// s.push(data);
///
/// Ok(s)
/// }
/// # process_data("123").expect("why is the test harness OOMing on 3 bytes?");
/// ```
#[stable(feature = "try_reserve_2", since = "1.63.0")]
#[inline]
pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
self.inner.try_reserve(additional)
}
/// Reserves the minimum capacity for at least `additional` more capacity to
/// be inserted in the given `OsString`. Does nothing if the capacity is
/// already sufficient.
///
/// Note that the allocator may give the collection more space than it
/// requests. Therefore, capacity can not be relied upon to be precisely
/// minimal. Prefer [`reserve`] if future insertions are expected.
///
/// [`reserve`]: OsString::reserve
///
/// See the main `OsString` documentation information about encoding and capacity units.
///
/// # Examples
///
/// ```
/// use std::ffi::OsString;
///
/// let mut s = OsString::new();
/// s.reserve_exact(10);
/// assert!(s.capacity() >= 10);
/// ```
#[stable(feature = "osstring_simple_functions", since = "1.9.0")]
#[inline]
pub fn reserve_exact(&mut self, additional: usize) {
self.inner.reserve_exact(additional)
}
/// Tries to reserve the minimum capacity for at least `additional`
/// more length units in the given `OsString`. After calling
/// `try_reserve_exact`, capacity will be greater than or equal to
/// `self.len() + additional` if it returns `Ok(())`.
/// Does nothing if the capacity is already sufficient.
///
/// Note that the allocator may give the `OsString` more space than it
/// requests. Therefore, capacity can not be relied upon to be precisely
/// minimal. Prefer [`try_reserve`] if future insertions are expected.
///
/// [`try_reserve`]: OsString::try_reserve
///
/// See the main `OsString` documentation information about encoding and capacity units.
///
/// # Errors
///
/// If the capacity overflows, or the allocator reports a failure, then an error
/// is returned.
///
/// # Examples
///
/// ```
/// use std::ffi::{OsStr, OsString};
/// use std::collections::TryReserveError;
///
/// fn process_data(data: &str) -> Result<OsString, TryReserveError> {
/// let mut s = OsString::new();
///
/// // Pre-reserve the memory, exiting if we can't
/// s.try_reserve_exact(OsStr::new(data).len())?;
///
/// // Now we know this can't OOM in the middle of our complex work
/// s.push(data);
///
/// Ok(s)
/// }
/// # process_data("123").expect("why is the test harness OOMing on 3 bytes?");
/// ```
#[stable(feature = "try_reserve_2", since = "1.63.0")]
#[inline]
pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
self.inner.try_reserve_exact(additional)
}
/// Shrinks the capacity of the `OsString` to match its length.
///
/// See the main `OsString` documentation information about encoding and capacity units.
///
/// # Examples
///
/// ```
/// use std::ffi::OsString;
///
/// let mut s = OsString::from("foo");
///
/// s.reserve(100);
/// assert!(s.capacity() >= 100);
///
/// s.shrink_to_fit();
/// assert_eq!(3, s.capacity());
/// ```
#[stable(feature = "osstring_shrink_to_fit", since = "1.19.0")]
#[inline]
pub fn shrink_to_fit(&mut self) {
self.inner.shrink_to_fit()
}
/// Shrinks the capacity of the `OsString` with a lower bound.
///
/// The capacity will remain at least as large as both the length
/// and the supplied value.
///
/// If the current capacity is less than the lower limit, this is a no-op.
///
/// See the main `OsString` documentation information about encoding and capacity units.
///
/// # Examples
///
/// ```
/// use std::ffi::OsString;
///
/// let mut s = OsString::from("foo");
///
/// s.reserve(100);
/// assert!(s.capacity() >= 100);
///
/// s.shrink_to(10);
/// assert!(s.capacity() >= 10);
/// s.shrink_to(0);
/// assert!(s.capacity() >= 3);
/// ```
#[inline]
#[stable(feature = "shrink_to", since = "1.56.0")]
pub fn shrink_to(&mut self, min_capacity: usize) {
self.inner.shrink_to(min_capacity)
}
/// Converts this `OsString` into a boxed [`OsStr`].
///
/// # Examples
///
/// ```
/// use std::ffi::{OsString, OsStr};
///
/// let s = OsString::from("hello");
///
/// let b: Box<OsStr> = s.into_boxed_os_str();
/// ```
#[must_use = "`self` will be dropped if the result is not used"]
#[stable(feature = "into_boxed_os_str", since = "1.20.0")]
pub fn into_boxed_os_str(self) -> Box<OsStr> {
let rw = Box::into_raw(self.inner.into_box()) as *mut OsStr;
unsafe { Box::from_raw(rw) }
}
/// Consumes and leaks the `OsString`, returning a mutable reference to the contents,
/// `&'a mut OsStr`.
///
/// The caller has free choice over the returned lifetime, including 'static.
/// Indeed, this function is ideally used for data that lives for the remainder of
/// the program’s life, as dropping the returned reference will cause a memory leak.
///
/// It does not reallocate or shrink the `OsString`, so the leaked allocation may include
/// unused capacity that is not part of the returned slice. If you want to discard excess
/// capacity, call [`into_boxed_os_str`], and then [`Box::leak`] instead.
/// However, keep in mind that trimming the capacity may result in a reallocation and copy.
///
/// [`into_boxed_os_str`]: Self::into_boxed_os_str
#[unstable(feature = "os_string_pathbuf_leak", issue = "125965")]
#[inline]
pub fn leak<'a>(self) -> &'a mut OsStr {
OsStr::from_inner_mut(self.inner.leak())
}
/// Part of a hack to make PathBuf::push/pop more efficient.
#[inline]
pub(crate) fn as_mut_vec_for_path_buf(&mut self) -> &mut Vec<u8> {
self.inner.as_mut_vec_for_path_buf()
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl From<String> for OsString {
/// Converts a [`String`] into an [`OsString`].
///
/// This conversion does not allocate or copy memory.
#[inline]
fn from(s: String) -> OsString {
OsString { inner: Buf::from_string(s) }
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized + AsRef<OsStr>> From<&T> for OsString {
/// Copies any value implementing <code>[AsRef]<[OsStr]></code>
/// into a newly allocated [`OsString`].
fn from(s: &T) -> OsString {
s.as_ref().to_os_string()
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl ops::Index<ops::RangeFull> for OsString {
type Output = OsStr;
#[inline]
fn index(&self, _index: ops::RangeFull) -> &OsStr {
OsStr::from_inner(self.inner.as_slice())
}
}
#[stable(feature = "mut_osstr", since = "1.44.0")]
impl ops::IndexMut<ops::RangeFull> for OsString {
#[inline]
fn index_mut(&mut self, _index: ops::RangeFull) -> &mut OsStr {
OsStr::from_inner_mut(self.inner.as_mut_slice())
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl ops::Deref for OsString {
type Target = OsStr;
#[inline]
fn deref(&self) -> &OsStr {
&self[..]
}
}
#[stable(feature = "mut_osstr", since = "1.44.0")]
impl ops::DerefMut for OsString {
#[inline]
fn deref_mut(&mut self) -> &mut OsStr {
&mut self[..]
}
}
#[stable(feature = "osstring_default", since = "1.9.0")]
impl Default for OsString {
/// Constructs an empty `OsString`.
#[inline]
fn default() -> OsString {
OsString::new()
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Clone for OsString {
#[inline]
fn clone(&self) -> Self {
OsString { inner: self.inner.clone() }
}
/// Clones the contents of `source` into `self`.
///
/// This method is preferred over simply assigning `source.clone()` to `self`,
/// as it avoids reallocation if possible.
#[inline]
fn clone_from(&mut self, source: &Self) {
self.inner.clone_from(&source.inner)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Debug for OsString {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&**self, formatter)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl PartialEq for OsString {
#[inline]
fn eq(&self, other: &OsString) -> bool {
&**self == &**other
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl PartialEq<str> for OsString {
#[inline]
fn eq(&self, other: &str) -> bool {
&**self == other
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl PartialEq<OsString> for str {
#[inline]
fn eq(&self, other: &OsString) -> bool {
&**other == self
}
}
#[stable(feature = "os_str_str_ref_eq", since = "1.29.0")]
impl PartialEq<&str> for OsString {
#[inline]
fn eq(&self, other: &&str) -> bool {
**self == **other
}
}
#[stable(feature = "os_str_str_ref_eq", since = "1.29.0")]
impl<'a> PartialEq<OsString> for &'a str {
#[inline]
fn eq(&self, other: &OsString) -> bool {
**other == **self
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Eq for OsString {}
#[stable(feature = "rust1", since = "1.0.0")]
impl PartialOrd for OsString {
#[inline]
fn partial_cmp(&self, other: &OsString) -> Option<cmp::Ordering> {
(&**self).partial_cmp(&**other)
}
#[inline]
fn lt(&self, other: &OsString) -> bool {
&**self < &**other
}
#[inline]
fn le(&self, other: &OsString) -> bool {
&**self <= &**other
}
#[inline]
fn gt(&self, other: &OsString) -> bool {
&**self > &**other
}
#[inline]
fn ge(&self, other: &OsString) -> bool {
&**self >= &**other
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl PartialOrd<str> for OsString {
#[inline]
fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
(&**self).partial_cmp(other)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Ord for OsString {
#[inline]
fn cmp(&self, other: &OsString) -> cmp::Ordering {
(&**self).cmp(&**other)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Hash for OsString {
#[inline]
fn hash<H: Hasher>(&self, state: &mut H) {
(&**self).hash(state)
}
}
#[stable(feature = "os_string_fmt_write", since = "1.64.0")]
impl fmt::Write for OsString {
fn write_str(&mut self, s: &str) -> fmt::Result {
self.push(s);
Ok(())
}
}
impl OsStr {
/// Coerces into an `OsStr` slice.
///
/// # Examples
///
/// ```
/// use std::ffi::OsStr;
///
/// let os_str = OsStr::new("foo");
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &OsStr {
s.as_ref()
}
/// Converts a slice of bytes to an OS string slice without checking that the string contains
/// valid `OsStr`-encoded data.
///
/// The byte encoding is an unspecified, platform-specific, self-synchronizing superset of UTF-8.
/// By being a self-synchronizing superset of UTF-8, this encoding is also a superset of 7-bit
/// ASCII.
///
/// See the [module's toplevel documentation about conversions][conversions] for safe,
/// cross-platform [conversions] from/to native representations.
///
/// # Safety
///
/// As the encoding is unspecified, callers must pass in bytes that originated as a mixture of
/// validated UTF-8 and bytes from [`OsStr::as_encoded_bytes`] from within the same Rust version
/// built for the same target platform. For example, reconstructing an `OsStr` from bytes sent
/// over the network or stored in a file will likely violate these safety rules.
///
/// Due to the encoding being self-synchronizing, the bytes from [`OsStr::as_encoded_bytes`] can be
/// split either immediately before or immediately after any valid non-empty UTF-8 substring.
///
/// # Example
///
/// ```
/// use std::ffi::OsStr;
///
/// let os_str = OsStr::new("Mary had a little lamb");
/// let bytes = os_str.as_encoded_bytes();
/// let words = bytes.split(|b| *b == b' ');
/// let words: Vec<&OsStr> = words.map(|word| {
/// // SAFETY:
/// // - Each `word` only contains content that originated from `OsStr::as_encoded_bytes`
/// // - Only split with ASCII whitespace which is a non-empty UTF-8 substring
/// unsafe { OsStr::from_encoded_bytes_unchecked(word) }
/// }).collect();
/// ```
///
/// [conversions]: super#conversions
#[inline]
#[stable(feature = "os_str_bytes", since = "1.74.0")]
pub unsafe fn from_encoded_bytes_unchecked(bytes: &[u8]) -> &Self {
Self::from_inner(Slice::from_encoded_bytes_unchecked(bytes))
}
#[inline]
fn from_inner(inner: &Slice) -> &OsStr {
// SAFETY: OsStr is just a wrapper of Slice,
// therefore converting &Slice to &OsStr is safe.
unsafe { &*(inner as *const Slice as *const OsStr) }
}
#[inline]
fn from_inner_mut(inner: &mut Slice) -> &mut OsStr {
// SAFETY: OsStr is just a wrapper of Slice,
// therefore converting &mut Slice to &mut OsStr is safe.
// Any method that mutates OsStr must be careful not to
// break platform-specific encoding, in particular Wtf8 on Windows.
unsafe { &mut *(inner as *mut Slice as *mut OsStr) }
}
/// Yields a <code>&[str]</code> slice if the `OsStr` is valid Unicode.
///
/// This conversion may entail doing a check for UTF-8 validity.
///
/// # Examples
///
/// ```
/// use std::ffi::OsStr;
///
/// let os_str = OsStr::new("foo");
/// assert_eq!(os_str.to_str(), Some("foo"));
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline]
pub fn to_str(&self) -> Option<&str> {
self.inner.to_str().ok()
}
/// Converts an `OsStr` to a <code>[Cow]<[str]></code>.
///
/// Any non-Unicode sequences are replaced with
/// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD].
///
/// [U+FFFD]: crate::char::REPLACEMENT_CHARACTER
///
/// # Examples
///
/// Calling `to_string_lossy` on an `OsStr` with invalid unicode:
///
/// ```
/// // Note, due to differences in how Unix and Windows represent strings,
/// // we are forced to complicate this example, setting up example `OsStr`s
/// // with different source data and via different platform extensions.
/// // Understand that in reality you could end up with such example invalid
/// // sequences simply through collecting user command line arguments, for
/// // example.
///
/// #[cfg(unix)] {
/// use std::ffi::OsStr;
/// use std::os::unix::ffi::OsStrExt;
///
/// // Here, the values 0x66 and 0x6f correspond to 'f' and 'o'
/// // respectively. The value 0x80 is a lone continuation byte, invalid
/// // in a UTF-8 sequence.
/// let source = [0x66, 0x6f, 0x80, 0x6f];
/// let os_str = OsStr::from_bytes(&source[..]);
///
/// assert_eq!(os_str.to_string_lossy(), "fo�o");
/// }
/// #[cfg(windows)] {
/// use std::ffi::OsString;
/// use std::os::windows::prelude::*;
///
/// // Here the values 0x0066 and 0x006f correspond to 'f' and 'o'
/// // respectively. The value 0xD800 is a lone surrogate half, invalid
/// // in a UTF-16 sequence.
/// let source = [0x0066, 0x006f, 0xD800, 0x006f];
/// let os_string = OsString::from_wide(&source[..]);
/// let os_str = os_string.as_os_str();
///
/// assert_eq!(os_str.to_string_lossy(), "fo�o");
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline]
pub fn to_string_lossy(&self) -> Cow<'_, str> {
self.inner.to_string_lossy()
}
/// Copies the slice into an owned [`OsString`].
///
/// # Examples
///
/// ```
/// use std::ffi::{OsStr, OsString};
///
/// let os_str = OsStr::new("foo");
/// let os_string = os_str.to_os_string();
/// assert_eq!(os_string, OsString::from("foo"));
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline]
pub fn to_os_string(&self) -> OsString {
OsString { inner: self.inner.to_owned() }
}
/// Checks whether the `OsStr` is empty.
///
/// # Examples
///
/// ```
/// use std::ffi::OsStr;
///
/// let os_str = OsStr::new("");
/// assert!(os_str.is_empty());
///
/// let os_str = OsStr::new("foo");
/// assert!(!os_str.is_empty());
/// ```
#[stable(feature = "osstring_simple_functions", since = "1.9.0")]
#[must_use]
#[inline]
pub fn is_empty(&self) -> bool {
self.inner.inner.is_empty()
}
/// Returns the length of this `OsStr`.
///
/// Note that this does **not** return the number of bytes in the string in
/// OS string form.
///
/// The length returned is that of the underlying storage used by `OsStr`.
/// As discussed in the [`OsString`] introduction, [`OsString`] and `OsStr`
/// store strings in a form best suited for cheap inter-conversion between
/// native-platform and Rust string forms, which may differ significantly
/// from both of them, including in storage size and encoding.
///
/// This number is simply useful for passing to other methods, like
/// [`OsString::with_capacity`] to avoid reallocations.
///
/// See the main `OsString` documentation information about encoding and capacity units.
///
/// # Examples
///
/// ```
/// use std::ffi::OsStr;
///
/// let os_str = OsStr::new("");
/// assert_eq!(os_str.len(), 0);
///
/// let os_str = OsStr::new("foo");
/// assert_eq!(os_str.len(), 3);
/// ```
#[stable(feature = "osstring_simple_functions", since = "1.9.0")]
#[must_use]
#[inline]
pub fn len(&self) -> usize {
self.inner.inner.len()
}
/// Converts a <code>[Box]<[OsStr]></code> into an [`OsString`] without copying or allocating.
#[stable(feature = "into_boxed_os_str", since = "1.20.0")]
#[must_use = "`self` will be dropped if the result is not used"]
pub fn into_os_string(self: Box<OsStr>) -> OsString {
let boxed = unsafe { Box::from_raw(Box::into_raw(self) as *mut Slice) };
OsString { inner: Buf::from_box(boxed) }
}
/// Converts an OS string slice to a byte slice. To convert the byte slice back into an OS
/// string slice, use the [`OsStr::from_encoded_bytes_unchecked`] function.
///
/// The byte encoding is an unspecified, platform-specific, self-synchronizing superset of UTF-8.
/// By being a self-synchronizing superset of UTF-8, this encoding is also a superset of 7-bit
/// ASCII.
///
/// Note: As the encoding is unspecified, any sub-slice of bytes that is not valid UTF-8 should
/// be treated as opaque and only comparable within the same Rust version built for the same
/// target platform. For example, sending the slice over the network or storing it in a file
/// will likely result in incompatible byte slices. See [`OsString`] for more encoding details
/// and [`std::ffi`] for platform-specific, specified conversions.
///
/// [`std::ffi`]: crate::ffi
#[inline]
#[stable(feature = "os_str_bytes", since = "1.74.0")]
pub fn as_encoded_bytes(&self) -> &[u8] {
self.inner.as_encoded_bytes()
}
/// Takes a substring based on a range that corresponds to the return value of
/// [`OsStr::as_encoded_bytes`].