about summary refs log tree commit diff
path: root/library/alloc/src/string.rs
AgeCommit message (Collapse)AuthorLines
2023-03-02Remove manual implementation of String::neKonrad Borowski-4/+0
2023-02-12Auto merge of #105671 - lukas-code:depreciate-char, r=scottmcmbors-4/+4
Use associated items of `char` instead of freestanding items in `core::char` The associated functions and constants on `char` have been stable since 1.52 and the freestanding items have soft-deprecated since 1.62 (https://github.com/rust-lang/rust/pull/95566). This PR ~~marks them as "deprecated in future", similar to the integer and floating point modules (`core::{i32, f32}` etc)~~ replaces all uses of `core::char::*` with `char::*` to prepare for future deprecation of `core::char::*`.
2023-02-07Docs: Fix format of headings in String::reserveDanilo Bargen-2/+2
2023-01-25Set version placeholders to 1.68Mark Rousskov-1/+1
2023-01-14Use associated items of `char` instead of freestanding items in `core::char`Lukas Markeffsky-4/+4
2023-01-10impl: specialize impl of `ToString` on `bool`Ezra Shaw-0/+9
2022-12-30Replace libstd, libcore, liballoc in line comments.jonathanCogan-1/+1
2022-12-28Update bootstrap cfgPietro Albini-1/+1
2022-11-18Rm diagnostic item, use lang itemDeadbeef-2/+1
2022-11-17Minimal implementation of implicit deref patternsDeadbeef-0/+1
2022-10-31Add tracking issue for `string_extend_from_within`Sky-1/+1
2022-10-22Fix typo in docs of `String::leak`.Finn Bear-1/+1
2022-10-19Put fn in the right place.Finn Bear-29/+29
2022-10-19Copy of #102941.Finn Bear-1/+30
2022-09-26remove cfg(bootstrap)Pietro Albini-3/+0
2022-08-23Auto merge of #99917 - yaahc:error-in-core-move, r=thomccbors-0/+20
Move Error trait into core This PR moves the error trait from the standard library into a new unstable `error` module within the core library. The goal of this PR is to help unify error reporting across the std and no_std ecosystems, as well as open the door to integrating the error trait into the panic reporting system when reporting panics whose source is an errors (such as via `expect`). This PR is a rewrite of https://github.com/rust-lang/rust/pull/90328 using new compiler features that have been added to support error in core.
2022-08-22Move error trait into coreJane Losare-Lusby-0/+20
2022-08-22Rollup merge of #100331 - lo48576:try-reserve-preserve-on-failure, r=thomccDylan DPC-1/+2
Guarantee `try_reserve` preserves the contents on error Update doc comments to make the guarantee explicit. However, some implementations does not have the statement though. * `HashMap`, `HashSet`: require guarantees on hashbrown side. * `PathBuf`: simply redirecting to `OsString`. Fixes #99606.
2022-08-20Rollup merge of #99544 - dylni:expose-utf8lossy, r=Mark-SimulacrumMatthias Krüger-8/+8
Expose `Utf8Lossy` as `Utf8Chunks` This PR changes the feature for `Utf8Lossy` from `str_internals` to `utf8_lossy` and improves the API. This is done to eventually expose the API as stable. Proposal: rust-lang/libs-team#54 Tracking Issue: #99543
2022-08-20Expose `Utf8Lossy` as `Utf8Chunks`dylni-8/+8
2022-08-10Guarantee `try_reserve` preserves the contents on errorYOSHIOKA Takuma-1/+2
Update doc comments to make the guarantee explicit. However, some implementations does not have the statement though. * `HashMap`, `HashSet`: require guarantees on hashbrown side. * `PathBuf`: simply redirecting to `OsString`. Fixes #99606.
2022-07-26Rollup merge of #98710 - mojave2:string, r=JohnTitorYuki Okushi-5/+5
correct the output of a `capacity` method example The output of this example in std::alloc is different from which shown in the comment. I have tested it on both Linux and Windows.
2022-06-30correct the output of a `capacity` method examplemojave2-5/+5
2022-06-29alloc: fix `no_global_oom_handling` warningsMiguel Ojeda-2/+2
Rust 1.62.0 introduced a couple new `unused_imports` warnings in `no_global_oom_handling` builds, making a total of 5 warnings: ```txt warning: unused import: `Unsize` --> library/alloc/src/boxed/thin.rs:6:33 | 6 | use core::marker::{PhantomData, Unsize}; | ^^^^^^ | = note: `#[warn(unused_imports)]` on by default warning: unused import: `from_fn` --> library/alloc/src/string.rs:51:18 | 51 | use core::iter::{from_fn, FusedIterator}; | ^^^^^^^ warning: unused import: `core::ops::Deref` --> library/alloc/src/vec/into_iter.rs:12:5 | 12 | use core::ops::Deref; | ^^^^^^^^^^^^^^^^ warning: associated function `shrink` is never used --> library/alloc/src/raw_vec.rs:424:8 | 424 | fn shrink(&mut self, cap: usize) -> Result<(), TryReserveError> { | ^^^^^^ | = note: `#[warn(dead_code)]` on by default warning: associated function `forget_remaining_elements` is never used --> library/alloc/src/vec/into_iter.rs:126:19 | 126 | pub(crate) fn forget_remaining_elements(&mut self) { | ^^^^^^^^^^^^^^^^^^^^^^^^^ ``` This patch cleans them so that projects compiling `alloc` without infallible allocations do not see the warnings. It also enables the use of `-Dwarnings`. The couple `dead_code` ones may be reverted when some fallible allocation support starts using them. Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2022-06-19Fix documentation for with_capacity and reserve families of methodsjmaargh-35/+35
Documentation for the following methods with_capacity with_capacity_in with_capacity_and_hasher reserve reserve_exact try_reserve try_reserve_exact was inconsistent and often not entirely correct where they existed on the following types Vec VecDeque String OsString PathBuf BinaryHeap HashSet HashMap BufWriter LineWriter since the allocator is allowed to allocate more than the requested capacity in all such cases, and will frequently "allocate" much more in the case of zero-sized types (I also checked BufReader, but there the docs appear to be accurate as it appears to actually allocate the exact capacity). Some effort was made to make the documentation more consistent between types as well. Fix with_capacity* methods for Vec Fix *reserve* methods for Vec Fix docs for *reserve* methods of VecDeque Fix docs for String::with_capacity Fix docs for *reserve* methods of String Fix docs for OsString::with_capacity Fix docs for *reserve* methods on OsString Fix docs for with_capacity* methods on HashSet Fix docs for *reserve methods of HashSet Fix docs for with_capacity* methods of HashMap Fix docs for *reserve methods on HashMap Fix expect messages about OOM in doctests Fix docs for BinaryHeap::with_capacity Fix docs for *reserve* methods of BinaryHeap Fix typos Fix docs for with_capacity on BufWriter and LineWriter Fix consistent use of `hasher` between `HashMap` and `HashSet` Fix warning in doc test Add test for capacity of vec with ZST Fix doc test error
2022-05-21Auto merge of #96605 - Urgau:string-retain-codegen, r=thomccbors-8/+17
Improve codegen of String::retain method This pull-request improve the codegen of the `String::retain` method. Using `unwrap_unchecked` helps the optimizer to not generate a panicking path that will never be taken for valid UTF-8 like string. Using `encode_utf8` saves us from an expensive call to `memcpy`, as the optimizer is unable to realize that `ch_len <= 4` and so can generate much better assembly code. https://rust.godbolt.org/z/z73ohenfc
2022-05-01Improve codegen of String::retain method.Loïc BRANSTETT-8/+17
Using unwrap_unchecked helps the optimizer to not generate panicking path, that will never be taken for valid UTF-8 like string. Using encode_utf8 saves us a call to a memcpy, as the optimizer is unable to realize that ch_len <= 4 and so can generate much better assembly code. https://rust.godbolt.org/z/z73ohenfc
2022-04-19Clarify docs for from_raw_partsjmaargh-1/+4
Original safety explanation for from_raw_parts was unclear on safety for consuming a C string. This clarifies when doing so is safe.
2022-04-09Rework String UTF-8 DocumentationMark Lodato-10/+82
**This Commit** Adds some clarity around indexing into Strings and the constraints driving various decisions there. **Why?** The [`String` documentation][0] mentions how `String`s can't be indexed but `Range` has an implementation for `SliceIndex<str>`. This can be confusing. There are also several statements to explain the lack of `String` indexing: - the inability to index into a `String` is an implication of UTF-8 encoding - indexing into a `String` could not be constant-time with UTF-8 encoding - indexing into a `String` does not have an obvious return type This last statement made sense but the first two seemed contradictory to the documentation around [`SliceIndex<str>`][1] which mention: - one can index into a `String` with a `Range` (also called substring slicing but it uses the same syntax and the method name is `index`) - `Range` indexing into a `String` is constant-time To resolve this seeming contradiction the documentation is reworked to more clearly explain what factors drive the decision to disallow indexing into a `String` with a single number. [0]: https://doc.rust-lang.org/stable/std/string/struct.String.html#utf-8 [1]: https://doc.rust-lang.org/stable/std/slice/trait.SliceIndex.html#impl-SliceIndex%3Cstr%3E
2022-03-27Rollup merge of #95368 - ↵Dylan DPC-1/+1
lopopolo:lopopolo/string-try-reserve-exact-doc-typo, r=Dylan-DPC Fix typo in `String::try_reserve_exact` docs Copying the pattern from `Vec::try_reserve_exact` and `String::try_reserve`, it looks like this doc comment is intending to refer to the currently-being-documented function.
2022-03-27Fix typo in `String::try_reserve_exact` docsRyan Lopopolo-1/+1
Copying the pattern from `Vec::try_reserve_exact` and `String::try_reserve`, it looks like this doc comment is intending to refer to the currently-being-documented function.
2022-03-10Use implicit capture syntax in format_argsT-O-R-U-S-1/+1
This updates the standard library's documentation to use the new syntax. The documentation is worthwhile to update as it should be more idiomatic (particularly for features like this, which are nice for users to get acquainted with). The general codebase is likely more hassle than benefit to update: it'll hurt git blame, and generally updates can be done by folks updating the code if (and when) that makes things more readable with the new format. A few places in the compiler and library code are updated (mostly just due to already having been done when this commit was first authored).
2022-02-19Collections: improve the documentation of drain membersStein Somers-5/+12
2021-12-29Fix a minor mistake in `String::try_reserve_exact` examplesSprite-1/+1
2021-12-05doc: suggest try_reserve in try_reserve_exactTennyZhuang-2/+2
Signed-off-by: TennyZhuang <zty0826@gmail.com>
2021-11-25Eliminate an unreachable codepath from String::from_utf8_lossyDavid Tolnay-7/+5
Utf8Lossy's Iterator implementation ensures that only the final chunk has an empty slice for broken. Thus the only way the first chunk could have an empty broken is if it is the final chunk, i.e. there is only one chunk total. And the only way that there could be one chunk total is if the whole input is valid utf8 and non-empty. That condition has already been handled by an early return, so at the point that the first REPLACEMENT is being pushed, it's impossible for first_broken to be empty.
2021-10-31Rollup merge of #89786 - jkugelman:must-use-len-and-is_empty, r=joshtriplettMatthias Krüger-0/+2
Add #[must_use] to len and is_empty Parent issue: #89692 r? `@joshtriplett`
2021-10-31Rollup merge of #89835 - jkugelman:must-use-expensive-computations, ↵Matthias Krüger-0/+2
r=joshtriplett Add #[must_use] to expensive computations The unifying theme for this commit is weak, admittedly. I put together a list of "expensive" functions when I originally proposed this whole effort, but nobody's cared about that criterion. Still, it's a decent way to bite off a not-too-big chunk of work. Given the grab bag nature of this commit, the messages I used vary quite a bit. I'm open to wording changes. For some reason clippy flagged four `BTreeSet` methods but didn't say boo about equivalent ones on `HashSet`. I stared at them for a while but I can't figure out the difference so I added the `HashSet` ones in. ```rust // Flagged by clippy. alloc::collections::btree_set::BTreeSet<T> fn difference<'a>(&'a self, other: &'a BTreeSet<T>) -> Difference<'a, T>; alloc::collections::btree_set::BTreeSet<T> fn symmetric_difference<'a>(&'a self, other: &'a BTreeSet<T>) -> SymmetricDifference<'a, T> alloc::collections::btree_set::BTreeSet<T> fn intersection<'a>(&'a self, other: &'a BTreeSet<T>) -> Intersection<'a, T>; alloc::collections::btree_set::BTreeSet<T> fn union<'a>(&'a self, other: &'a BTreeSet<T>) -> Union<'a, T>; // Ignored by clippy, but not by me. std::collections::HashSet<T, S> fn difference<'a>(&'a self, other: &'a HashSet<T, S>) -> Difference<'a, T, S>; std::collections::HashSet<T, S> fn symmetric_difference<'a>(&'a self, other: &'a HashSet<T, S>) -> SymmetricDifference<'a, T, S> std::collections::HashSet<T, S> fn intersection<'a>(&'a self, other: &'a HashSet<T, S>) -> Intersection<'a, T, S>; std::collections::HashSet<T, S> fn union<'a>(&'a self, other: &'a HashSet<T, S>) -> Union<'a, T, S>; ``` Parent issue: #89692 r? ```@joshtriplett```
2021-10-30Add #[must_use] to len and is_emptyJohn Kugelman-0/+2
2021-10-31Rollup merge of #89899 - jkugelman:must-use-alloc, r=joshtriplettMatthias Krüger-0/+2
Add #[must_use] to remaining alloc functions I've run out of compelling reasons to group functions together across crates so I'm just going to go module-by-module. This is everything remaining from the `alloc` crate. I ignored these because they might be used to purposefully leak memory... or other allocator shenanigans? I dunno. I'll add them if y'all tell me to. ```rust alloc::alloc unsafe fn alloc(layout: Layout) -> *mut u8; alloc::alloc unsafe fn alloc_zeroed(layout: Layout) -> *mut u8; alloc::sync::Arc<T> fn into_raw(this: Self) -> *const T; ``` I don't know why clippy ignored these. I added them myself: ```rust alloc::collections::btree_map::BTreeMap<K, V> fn range<T: ?Sized, R>(&self, range: R) -> Range<'_, K, V>; alloc::collections::btree_set::BTreeSet<T> fn range<K: ?Sized, R>(&self, range: R) -> Range<'_, T>; ``` I added these non-mutating `mut` functions: ```rust alloc::collections::btree_map::BTreeMap<K, V> fn range_mut<T: ?Sized, R>(&mut self, range: R) -> RangeMut<'_, K, V>; alloc::collections::btree_map::BTreeMap<K, V> fn iter_mut(&mut self) -> IterMut<'_, K, V>; alloc::collections::btree_map::BTreeMap<K, V> fn values_mut(&mut self) -> ValuesMut<'_, K, V>; alloc::collections::linked_list::LinkedList<T> fn iter_mut(&mut self) -> IterMut<'_, T>; alloc::collections::linked_list::LinkedList<T> fn cursor_front_mut(&mut self) -> CursorMut<'_, T>; alloc::collections::linked_list::LinkedList<T> fn cursor_back_mut(&mut self) -> CursorMut<'_, T>; alloc::collections::linked_list::LinkedList<T> fn front_mut(&mut self) -> Option<&mut T>; alloc::collections::linked_list::LinkedList<T> fn back_mut(&mut self) -> Option<&mut T>; alloc::collections::linked_list::CursorMut<'a, T> fn current(&mut self) -> Option<&mut T>; alloc::collections::linked_list::CursorMut<'a, T> fn peek_next(&mut self) -> Option<&mut T>; alloc::collections::linked_list::CursorMut<'a, T> fn peek_prev(&mut self) -> Option<&mut T>; alloc::collections::linked_list::CursorMut<'a, T> fn front_mut(&mut self) -> Option<&mut T>; alloc::collections::linked_list::CursorMut<'a, T> fn back_mut(&mut self) -> Option<&mut T>; ``` I moved a few existing `#[must_use]`s from functions onto the iterator types they return: `IntoIterSorted`, `IntoKeys`, `IntoValues`. Parent issue: #89692 r? `@joshtriplett`
2021-10-25Fix copy-paste error in String::as_mut_vec() docsnyanpasu64-4/+5
2021-10-15Add #[must_use] to remaining alloc functionsJohn Kugelman-0/+2
2021-10-12Add #[must_use] to expensive computationsJohn Kugelman-0/+2
The unifying theme for this commit is weak, admittedly. I put together a list of "expensive" functions when I originally proposed this whole effort, but nobody's cared about that criterion. Still, it's a decent way to bite off a not-too-big chunk of work. Given the grab bag nature of this commit, the messages I used vary quite a bit.
2021-10-12Rollup merge of #89778 - jkugelman:must-use-as_type-conversions, r=joshtriplettthe8472-0/+5
Add #[must_use] to as_type conversions Clippy missed these: ```rust alloc::string::String fn as_mut_str(&mut self) -> &mut str; core::mem::NonNull<T> unsafe fn as_uninit_mut<'a>(&mut self) -> &'a MaybeUninit<T>; str unsafe fn as_bytes_mut(&mut self) -> &mut [u8]; str fn as_mut_ptr(&mut self) -> *mut u8; ``` Parent issue: #89692 r? ````@joshtriplett````
2021-10-11Add #[must_use] to as_type conversionsJohn Kugelman-0/+5
2021-10-11Rollup merge of #89753 - jkugelman:must-use-from_value-conversions, ↵Guillaume Gomez-0/+1
r=joshtriplett Add #[must_use] to from_value conversions I added two methods to the list myself. Clippy did not flag them because they take `mut` args, but neither modifies their argument. ```rust core::str const unsafe fn from_utf8_unchecked_mut(v: &mut [u8]) -> &mut str; std::ffi::CString unsafe fn from_raw(ptr: *mut c_char) -> CString; ``` I put a custom note on `from_raw`: ```rust #[must_use = "call `drop(from_raw(ptr))` if you intend to drop the `CString`"] pub unsafe fn from_raw(ptr: *mut c_char) -> CString { ``` Parent issue: #89692 r? ``@joshtriplett``
2021-10-11Rollup merge of #89726 - jkugelman:must-use-alloc-constructors, r=joshtriplettGuillaume Gomez-0/+2
Add #[must_use] to alloc constructors Added `#[must_use]`. to the various forms of `new`, `pin`, and `with_capacity` in the `alloc` crate. No extra explanations given as I couldn't think of anything useful to add. I figure this deserves extra scrutiny compared to the other PRs I've done so far. In particular: * The 4 `pin`/`pin_in` methods I touched. Are there legitimate use cases for pinning and not using the result? Pinning's a difficult concept I'm not very comfortable with. * `Box`'s constructors. Do people ever create boxes just for the side effects... allocating or zeroing out memory? Parent issue: #89692 r? ``@joshtriplett``
2021-10-10Add #[must_use] to conversions that move selfJohn Kugelman-0/+4
2021-10-10Add #[must_use] to from_value conversionsJohn Kugelman-0/+1
2021-10-10Add #[must_use] to alloc constructorsJohn Kugelman-0/+2