smallstr-0.3.0/.cargo_vcs_info.json0000644000000001360000000000100126750ustar { "git": { "sha1": "862b3c60f8639409ffc4defff3abbe98480b3560" }, "path_in_vcs": "" }smallstr-0.3.0/.github/workflows/ci.yml000064400000000000000000000026650072674642500162410ustar 00000000000000name: CI on: pull_request: paths: - '**.rs' - '**.toml' - '.github/workflows/ci.yml' push: branches: [master] paths: - '**.rs' - '**.toml' - '.github/workflows/ci.yml' jobs: Test: strategy: fail-fast: false matrix: rust: [stable, nightly] runs-on: ubuntu-latest steps: - uses: actions/checkout@v1 - uses: hecrj/setup-rust-action@v1 with: rust-version: ${{ matrix.platform.rust }} - name: Build run: cargo build --verbose - name: Test run: cargo test --verbose - name: Build with std run: cargo build --verbose --features std,ffi - name: Test with std run: cargo build --verbose --features std,ffi - name: Build with serde/no_std run: cargo build --verbose --features serde - name: Test with serde/no_std run: cargo test --verbose --features serde - name: Build with serde/std run: cargo build --verbose --features serde,std - name: Test with serde/std run: cargo test --verbose --features serde,std - name: Build with union feature if: matrix.platform.rust == 'nightly' run: cargo build --verbose --features union - name: Test with with union feature if: matrix.platform.rust == 'nightly' run: cargo test --verbose --features union env: RUST_BACKTRACE: 1 RUST_INCREMENTAL: 0 RUSTFLAGS: "-C debuginfo=0" smallstr-0.3.0/.gitignore000064400000000000000000000000220072674642500134770ustar 00000000000000target Cargo.lock smallstr-0.3.0/Cargo.toml0000644000000021710000000000100106740ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" name = "smallstr" version = "0.3.0" authors = ["Murarth "] description = "String-like container based on smallvec" homepage = "https://github.com/murarth/smallstr" documentation = "https://docs.rs/smallstr/" readme = "README.md" keywords = ["small", "str", "string"] categories = ["data-structures"] license = "MIT OR Apache-2.0" repository = "https://github.com/murarth/smallstr" [dependencies.serde] version = "1.0" features = ["alloc"] optional = true default-features = false [dependencies.smallvec] version = "1.1" [dev-dependencies.bincode] version = "1.0" [features] ffi = [] std = ["serde/std"] union = ["smallvec/union"] smallstr-0.3.0/Cargo.toml.orig000064400000000000000000000012420072674642500144030ustar 00000000000000[package] name = "smallstr" version = "0.3.0" authors = ["Murarth "] edition = "2018" description = "String-like container based on smallvec" documentation = "https://docs.rs/smallstr/" homepage = "https://github.com/murarth/smallstr" repository = "https://github.com/murarth/smallstr" categories = ["data-structures"] keywords = ["small", "str", "string"] license = "MIT OR Apache-2.0" readme = "README.md" [features] ffi = [] std = ["serde/std"] union = ["smallvec/union"] [dependencies] serde = { version = "1.0", default-features = false, features = ["alloc"], optional = true } smallvec = { version = "1.1" } [dev-dependencies] bincode = "1.0" smallstr-0.3.0/LICENSE-APACHE000064400000000000000000000251370072674642500134510ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. smallstr-0.3.0/LICENSE-MIT000064400000000000000000000020400072674642500131450ustar 00000000000000Copyright (c) 2018-2020 Murarth Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. smallstr-0.3.0/README.md000064400000000000000000000006220072674642500127740ustar 00000000000000# smallstr `String`-like container based on `SmallVec` [Documentation](https://docs.rs/smallstr/) ## Building To include `smallstr` in your project, add the following to your `Cargo.toml`: ```toml [dependencies] smallstr = "0.3" ``` ## License smallstr is distributed under the terms of both the MIT license and the Apache License (Version 2.0). See LICENSE-APACHE and LICENSE-MIT for details. smallstr-0.3.0/src/lib.rs000064400000000000000000000023540072674642500134240ustar 00000000000000//! Implements `SmallString`, a `String`-like container for small strings //! //! ## `no_std` support //! //! By default, `smallstr` does not depend on `std`. The `std` feature may be enabled //! to add the `std` dependency. The `ffi` feature also implies `std`. //! //! ## `ffi` feature //! //! The `ffi` feature will add the following trait implementations to `SmallString`: //! //! * `PartialEq` //! * `PartialEq<&'_ OsStr>` //! * `PartialEq` //! * `PartialEq>` //! //! This feature also adds `std` as a dependency. //! //! ## `serde` support //! //! When the `serde` feature is enabled, the traits `serde::Deserialize` and //! `serde::Serialize` are implemented for `SmallString`. //! //! This feature is disabled by default. //! //! By default, the `serde` dependency is compiled with `no_std`. //! If the `std` feature is enabled, `std` is added as a dependency in `serde`, as well. //! //! ## `union` feature //! //! This feature will enable the `union` feature in `smallvec`, which reduces the size of //! a `SmallString` instance. This feature requires a nightly compiler. #![cfg_attr(not(any(feature = "ffi", feature = "std")), no_std)] #![deny(missing_docs)] extern crate alloc; pub use string::*; mod string; smallstr-0.3.0/src/string.rs000064400000000000000000000707430072674642500141730ustar 00000000000000use core::{ borrow::{Borrow, BorrowMut}, cmp::Ordering, fmt, hash::{Hash, Hasher}, iter::FromIterator, ops, ptr, slice, str::{self, Chars, Utf8Error}, }; use alloc::{borrow::Cow, boxed::Box, string::String}; #[cfg(feature = "ffi")] use std::ffi::{OsStr, OsString}; #[cfg(feature = "serde")] use core::marker::PhantomData; #[cfg(feature = "serde")] use serde::{ de::{Deserialize, Deserializer, Error, Visitor}, ser::{Serialize, Serializer}, }; use smallvec::{Array, SmallVec}; /// A `String`-like container that can store a small number of bytes inline. /// /// `SmallString` uses a `SmallVec<[u8; N]>` as its internal storage. #[derive(Clone, Default)] pub struct SmallString> { data: SmallVec, } impl> SmallString { /// Construct an empty string. #[inline] pub fn new() -> SmallString { SmallString { data: SmallVec::new(), } } /// Construct an empty string with enough capacity pre-allocated to store /// at least `n` bytes. /// /// Will create a heap allocation only if `n` is larger than the inline capacity. #[inline] pub fn with_capacity(n: usize) -> SmallString { SmallString { data: SmallVec::with_capacity(n), } } /// Construct a `SmallString` by copying data from a `&str`. #[inline] pub fn from_str(s: &str) -> SmallString { SmallString { data: SmallVec::from_slice(s.as_bytes()), } } /// Construct a `SmallString` by using an existing allocation. #[inline] pub fn from_string(s: String) -> SmallString { SmallString { data: SmallVec::from_vec(s.into_bytes()), } } /// Constructs a new `SmallString` on the stack using UTF-8 bytes. /// /// If the provided byte array is not valid UTF-8, an error is returned. #[inline] pub fn from_buf(buf: A) -> Result, FromUtf8Error> { let data = SmallVec::from_buf(buf); match str::from_utf8(&data) { Ok(_) => Ok(SmallString { data }), Err(error) => { let buf = data.into_inner().ok().unwrap(); Err(FromUtf8Error { buf, error }) } } } /// Constructs a new `SmallString` on the stack using the provided byte array /// without checking that the array contains valid UTF-8. /// /// # Safety /// /// This function is unsafe because it does not check that the bytes passed /// to it are valid UTF-8. If this constraint is violated, it may cause /// memory unsafety issues, as the Rust standard library functions assume /// that `&str`s are valid UTF-8. #[inline] pub unsafe fn from_buf_unchecked(buf: A) -> SmallString { SmallString { data: SmallVec::from_buf(buf), } } /// The maximum number of bytes this string can hold inline. #[inline] pub fn inline_size(&self) -> usize { A::size() } /// Returns the length of this string, in bytes. #[inline] pub fn len(&self) -> usize { self.data.len() } /// Returns `true` if this string is empty. #[inline] pub fn is_empty(&self) -> bool { self.data.is_empty() } /// Returns the number of bytes this string can hold without reallocating. #[inline] pub fn capacity(&self) -> usize { self.data.capacity() } /// Returns `true` if the data has spilled into a separate heap-allocated buffer. #[inline] pub fn spilled(&self) -> bool { self.data.spilled() } /// Empties the string and returns an iterator over its former contents. pub fn drain(&mut self) -> Drain { unsafe { let len = self.len(); self.data.set_len(0); let ptr = self.as_ptr(); let slice = slice::from_raw_parts(ptr, len); let s = str::from_utf8_unchecked(slice); Drain { iter: s.chars() } } } /// Appends the given `char` to the end of this string. /// /// # Examples /// /// ``` /// use smallstr::SmallString; /// /// let mut s: SmallString<[u8; 8]> = SmallString::from("foo"); /// /// s.push('x'); /// /// assert_eq!(s, "foox"); /// ``` #[inline] pub fn push(&mut self, ch: char) { match ch.len_utf8() { 1 => self.data.push(ch as u8), _ => self.push_str(ch.encode_utf8(&mut [0; 4])), } } /// Appends the given string slice to the end of this string. /// /// # Examples /// /// ``` /// use smallstr::SmallString; /// /// let mut s: SmallString<[u8; 8]> = SmallString::from("foo"); /// /// s.push_str("bar"); /// /// assert_eq!(s, "foobar"); /// ``` #[inline] pub fn push_str(&mut self, s: &str) { self.data.extend_from_slice(s.as_bytes()); } /// Removes the last character from this string and returns it. /// /// Returns `None` if the string is empty. #[inline] pub fn pop(&mut self) -> Option { match self.chars().next_back() { Some(ch) => unsafe { let new_len = self.len() - ch.len_utf8(); self.data.set_len(new_len); Some(ch) }, None => None, } } /// Reallocates to set the new capacity to `new_cap`. /// /// # Panics /// /// If `new_cap` is less than the current length. #[inline] pub fn grow(&mut self, new_cap: usize) { self.data.grow(new_cap); } /// Ensures that this string's capacity is at least `additional` bytes larger /// than its length. /// /// The capacity may be increased by more than `additional` bytes in order to /// prevent frequent reallocations. #[inline] pub fn reserve(&mut self, additional: usize) { self.data.reserve(additional); } /// Ensures that this string's capacity is `additional` bytes larger than /// its length. #[inline] pub fn reserve_exact(&mut self, additional: usize) { self.data.reserve(additional); } /// Shrink the capacity of the string as much as possible. /// /// When possible, this will move the data from an external heap buffer /// to the string's inline storage. #[inline] pub fn shrink_to_fit(&mut self) { self.data.shrink_to_fit(); } /// Shorten the string, keeping the first `len` bytes. /// /// This does not reallocate. If you want to shrink the string's capacity, /// use `shrink_to_fit` after truncating. /// /// # Panics /// /// If `len` does not lie on a `char` boundary. #[inline] pub fn truncate(&mut self, len: usize) { assert!(self.is_char_boundary(len)); self.data.truncate(len); } /// Extracts a string slice containing the entire string. #[inline] pub fn as_str(&self) -> &str { self } /// Extracts a string slice containing the entire string. #[inline] pub fn as_mut_str(&mut self) -> &mut str { self } /// Removes all contents of the string. #[inline] pub fn clear(&mut self) { self.data.clear(); } /// Removes a `char` from this string at a byte position and returns it. /// /// # Panics /// /// If `idx` does not lie on a `char` boundary. #[inline] pub fn remove(&mut self, idx: usize) -> char { let ch = match self[idx..].chars().next() { Some(ch) => ch, None => panic!("cannot remove a char from the end of a string"), }; let ch_len = ch.len_utf8(); let next = idx + ch_len; let len = self.len(); unsafe { ptr::copy( self.as_ptr().add(next), self.as_mut_ptr().add(idx), len - next, ); self.data.set_len(len - ch_len); } ch } /// Inserts a `char` into this string at the given byte position. /// /// # Panics /// /// If `idx` does not lie on `char` boundaries. #[inline] pub fn insert(&mut self, idx: usize, ch: char) { assert!(self.is_char_boundary(idx)); match ch.len_utf8() { 1 => self.data.insert(idx, ch as u8), _ => self.insert_str(idx, ch.encode_utf8(&mut [0; 4])), } } /// Inserts a `&str` into this string at the given byte position. /// /// # Panics /// /// If `idx` does not lie on `char` boundaries. #[inline] pub fn insert_str(&mut self, idx: usize, s: &str) { assert!(self.is_char_boundary(idx)); let len = self.len(); let amt = s.len(); self.data.reserve(amt); unsafe { ptr::copy( self.as_ptr().add(idx), self.as_mut_ptr().add(idx + amt), len - idx, ); ptr::copy_nonoverlapping(s.as_ptr(), self.as_mut_ptr().add(idx), amt); self.data.set_len(len + amt); } } /// Returns a mutable reference to the contents of the `SmallString`. /// /// # Safety /// /// This function is unsafe because it does not check that the bytes passed /// to it are valid UTF-8. If this constraint is violated, it may cause /// memory unsafety issues, as the Rust standard library functions assume /// that `&str`s are valid UTF-8. #[inline] pub unsafe fn as_mut_vec(&mut self) -> &mut SmallVec { &mut self.data } /// Converts the `SmallString` into a `String`, without reallocating if the /// `SmallString` has already spilled onto the heap. #[inline] pub fn into_string(self) -> String { unsafe { String::from_utf8_unchecked(self.data.into_vec()) } } /// Converts the `SmallString` into a `Box`, without reallocating if the /// `SmallString` has already spilled onto the heap. /// /// Note that this will drop excess capacity. #[inline] pub fn into_boxed_str(self) -> Box { self.into_string().into_boxed_str() } /// Convert the `SmallString` into `A`, if possible. Otherwise, return `Err(self)`. /// /// This method returns `Err(self)` if the `SmallString` is too short /// (and the `A` contains uninitialized elements) or if the `SmallString` is too long /// (and the elements have been spilled to the heap). #[inline] pub fn into_inner(self) -> Result { self.data.into_inner().map_err(|data| SmallString { data }) } /// Retains only the characters specified by the predicate. /// /// In other words, removes all characters `c` such that `f(c)` returns `false`. /// This method operates in place and preserves the order of retained /// characters. /// /// # Examples /// /// ``` /// use smallstr::SmallString; /// /// let mut s: SmallString<[u8; 16]> = SmallString::from("f_o_ob_ar"); /// /// s.retain(|c| c != '_'); /// /// assert_eq!(s, "foobar"); /// ``` #[inline] pub fn retain bool>(&mut self, mut f: F) { struct SetLenOnDrop<'a, A: Array> { s: &'a mut SmallString, idx: usize, del_bytes: usize, } impl<'a, A: Array> Drop for SetLenOnDrop<'a, A> { fn drop(&mut self) { let new_len = self.idx - self.del_bytes; debug_assert!(new_len <= self.s.len()); unsafe { self.s.data.set_len(new_len) }; } } let len = self.len(); let mut guard = SetLenOnDrop { s: self, idx: 0, del_bytes: 0, }; while guard.idx < len { let ch = unsafe { guard .s .get_unchecked(guard.idx..len) .chars() .next() .unwrap() }; let ch_len = ch.len_utf8(); if !f(ch) { guard.del_bytes += ch_len; } else if guard.del_bytes > 0 { unsafe { ptr::copy( guard.s.data.as_ptr().add(guard.idx), guard.s.data.as_mut_ptr().add(guard.idx - guard.del_bytes), ch_len, ); } } // Point idx to the next char guard.idx += ch_len; } drop(guard); } fn as_mut_ptr(&mut self) -> *mut u8 { self.as_ptr() as *mut u8 } } impl> ops::Deref for SmallString { type Target = str; #[inline] fn deref(&self) -> &str { let bytes: &[u8] = &self.data; unsafe { str::from_utf8_unchecked(bytes) } } } impl> ops::DerefMut for SmallString { #[inline] fn deref_mut(&mut self) -> &mut str { let bytes: &mut [u8] = &mut self.data; unsafe { str::from_utf8_unchecked_mut(bytes) } } } impl> AsRef for SmallString { #[inline] fn as_ref(&self) -> &str { self } } impl> AsMut for SmallString { #[inline] fn as_mut(&mut self) -> &mut str { self } } impl> Borrow for SmallString { #[inline] fn borrow(&self) -> &str { self } } impl> BorrowMut for SmallString { #[inline] fn borrow_mut(&mut self) -> &mut str { self } } impl> AsRef<[u8]> for SmallString { #[inline] fn as_ref(&self) -> &[u8] { self.data.as_ref() } } impl> Borrow<[u8]> for SmallString { #[inline] fn borrow(&self) -> &[u8] { self.data.borrow() } } impl> fmt::Write for SmallString { #[inline] fn write_str(&mut self, s: &str) -> fmt::Result { self.push_str(s); Ok(()) } #[inline] fn write_char(&mut self, ch: char) -> fmt::Result { self.push(ch); Ok(()) } } #[cfg(feature = "serde")] impl> Serialize for SmallString { fn serialize(&self, serializer: S) -> Result { serializer.serialize_str(self) } } #[cfg(feature = "serde")] impl<'de, A: Array> Deserialize<'de> for SmallString { fn deserialize>(deserializer: D) -> Result { deserializer.deserialize_str(SmallStringVisitor { phantom: PhantomData, }) } } #[cfg(feature = "serde")] struct SmallStringVisitor { phantom: PhantomData, } #[cfg(feature = "serde")] impl<'de, A: Array> Visitor<'de> for SmallStringVisitor { type Value = SmallString; fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("a string") } fn visit_str(self, v: &str) -> Result { Ok(v.into()) } fn visit_string(self, v: String) -> Result { Ok(v.into()) } } impl> From for SmallString { #[inline] fn from(ch: char) -> SmallString { SmallString::from_str(ch.encode_utf8(&mut [0; 4])) } } impl<'a, A: Array> From<&'a str> for SmallString { #[inline] fn from(s: &str) -> SmallString { SmallString::from_str(s) } } impl> From> for SmallString { #[inline] fn from(s: Box) -> SmallString { SmallString::from_string(s.into()) } } impl> From for SmallString { #[inline] fn from(s: String) -> SmallString { SmallString::from_string(s) } } macro_rules! impl_index_str { ($index_type: ty) => { impl> ops::Index<$index_type> for SmallString { type Output = str; #[inline] fn index(&self, index: $index_type) -> &str { &self.as_str()[index] } } impl> ops::IndexMut<$index_type> for SmallString { #[inline] fn index_mut(&mut self, index: $index_type) -> &mut str { &mut self.as_mut_str()[index] } } }; } impl_index_str!(ops::Range); impl_index_str!(ops::RangeFrom); impl_index_str!(ops::RangeTo); impl_index_str!(ops::RangeFull); impl> FromIterator for SmallString { fn from_iter>(iter: I) -> SmallString { let mut s = SmallString::new(); s.extend(iter); s } } impl<'a, A: Array> FromIterator<&'a char> for SmallString { fn from_iter>(iter: I) -> SmallString { let mut s = SmallString::new(); s.extend(iter.into_iter().cloned()); s } } impl<'a, A: Array> FromIterator> for SmallString { fn from_iter>>(iter: I) -> SmallString { let mut s = SmallString::new(); s.extend(iter); s } } impl<'a, A: Array> FromIterator<&'a str> for SmallString { fn from_iter>(iter: I) -> SmallString { let mut s = SmallString::new(); s.extend(iter); s } } impl> FromIterator for SmallString { fn from_iter>(iter: I) -> SmallString { let mut s = SmallString::new(); s.extend(iter); s } } impl> Extend for SmallString { fn extend>(&mut self, iter: I) { let iter = iter.into_iter(); let (lo, _) = iter.size_hint(); self.reserve(lo); for ch in iter { self.push(ch); } } } impl<'a, A: Array> Extend<&'a char> for SmallString { fn extend>(&mut self, iter: I) { self.extend(iter.into_iter().cloned()); } } impl<'a, A: Array> Extend> for SmallString { fn extend>>(&mut self, iter: I) { for s in iter { self.push_str(&s); } } } impl<'a, A: Array> Extend<&'a str> for SmallString { fn extend>(&mut self, iter: I) { for s in iter { self.push_str(s); } } } impl> Extend for SmallString { fn extend>(&mut self, iter: I) { for s in iter { self.push_str(&s); } } } impl> fmt::Debug for SmallString { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&**self, f) } } impl> fmt::Display for SmallString { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&**self, f) } } macro_rules! eq_str { ( $rhs:ty ) => { impl<'a, A: Array> PartialEq<$rhs> for SmallString { #[inline] fn eq(&self, rhs: &$rhs) -> bool { &self[..] == &rhs[..] } #[inline] fn ne(&self, rhs: &$rhs) -> bool { &self[..] != &rhs[..] } } }; } eq_str!(str); eq_str!(&'a str); eq_str!(String); eq_str!(Cow<'a, str>); #[cfg(feature = "ffi")] impl> PartialEq for SmallString { #[inline] fn eq(&self, rhs: &OsStr) -> bool { &self[..] == rhs } #[inline] fn ne(&self, rhs: &OsStr) -> bool { &self[..] != rhs } } #[cfg(feature = "ffi")] impl<'a, A: Array> PartialEq<&'a OsStr> for SmallString { #[inline] fn eq(&self, rhs: &&OsStr) -> bool { &self[..] == *rhs } #[inline] fn ne(&self, rhs: &&OsStr) -> bool { &self[..] != *rhs } } #[cfg(feature = "ffi")] impl> PartialEq for SmallString { #[inline] fn eq(&self, rhs: &OsString) -> bool { &self[..] == rhs } #[inline] fn ne(&self, rhs: &OsString) -> bool { &self[..] != rhs } } #[cfg(feature = "ffi")] impl<'a, A: Array> PartialEq> for SmallString { #[inline] fn eq(&self, rhs: &Cow) -> bool { self[..] == **rhs } #[inline] fn ne(&self, rhs: &Cow) -> bool { self[..] != **rhs } } impl PartialEq> for SmallString where A: Array, B: Array, { #[inline] fn eq(&self, rhs: &SmallString) -> bool { &self[..] == &rhs[..] } #[inline] fn ne(&self, rhs: &SmallString) -> bool { &self[..] != &rhs[..] } } impl> Eq for SmallString {} impl> PartialOrd for SmallString { #[inline] fn partial_cmp(&self, rhs: &SmallString) -> Option { self[..].partial_cmp(&rhs[..]) } } impl> Ord for SmallString { #[inline] fn cmp(&self, rhs: &SmallString) -> Ordering { self[..].cmp(&rhs[..]) } } impl> Hash for SmallString { #[inline] fn hash(&self, state: &mut H) { self[..].hash(state) } } /// A draining iterator for `SmallString`. /// /// This struct is created by the [`drain`] method on [`SmallString`]. /// /// [`drain`]: struct.SmallString.html#method.drain /// [`SmallString`]: struct.SmallString.html pub struct Drain<'a> { iter: Chars<'a>, } impl<'a> Iterator for Drain<'a> { type Item = char; #[inline] fn next(&mut self) -> Option { self.iter.next() } #[inline] fn size_hint(&self) -> (usize, Option) { self.iter.size_hint() } } impl<'a> DoubleEndedIterator for Drain<'a> { #[inline] fn next_back(&mut self) -> Option { self.iter.next_back() } } /// A possible error value when creating a `SmallString` from a byte array. /// /// This type is the error type for the [`from_buf`] method on [`SmallString`]. /// /// [`from_buf`]: struct.SmallString.html#method.from_buf /// [`SmallString`]: struct.SmallString.html #[derive(Debug)] pub struct FromUtf8Error> { buf: A, error: Utf8Error, } impl> FromUtf8Error { /// Returns the slice of `[u8]` bytes that were attempted to convert to a `SmallString`. #[inline] pub fn as_bytes(&self) -> &[u8] { let ptr = &self.buf as *const _ as *const u8; unsafe { slice::from_raw_parts(ptr, A::size()) } } /// Returns the byte array that was attempted to convert into a `SmallString`. #[inline] pub fn into_buf(self) -> A { self.buf } /// Returns the `Utf8Error` to get more details about the conversion failure. #[inline] pub fn utf8_error(&self) -> Utf8Error { self.error } } impl> fmt::Display for FromUtf8Error { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.error, f) } } #[cfg(test)] mod test { use alloc::{ borrow::{Cow, ToOwned}, string::{String, ToString}, }; use super::SmallString; #[test] fn test_drain() { let mut s: SmallString<[u8; 2]> = SmallString::new(); s.push('a'); assert_eq!(s.drain().collect::(), "a"); assert!(s.is_empty()); // spilling the vec s.push('x'); s.push('y'); s.push('z'); assert_eq!(s.drain().collect::(), "xyz"); assert!(s.is_empty()); } #[test] fn test_drain_rev() { let mut s: SmallString<[u8; 2]> = SmallString::new(); s.push('a'); assert_eq!(s.drain().rev().collect::(), "a"); assert!(s.is_empty()); // spilling the vec s.push('x'); s.push('y'); s.push('z'); assert_eq!(s.drain().rev().collect::(), "zyx"); assert!(s.is_empty()); } #[test] fn test_eq() { let s: SmallString<[u8; 4]> = SmallString::from("foo"); assert_eq!(s, *"foo"); assert_eq!(s, "foo"); assert_eq!(s, "foo".to_owned()); assert_eq!(s, Cow::Borrowed("foo")); } #[cfg(feature = "ffi")] #[test] fn test_eq_os_str() { use std::ffi::OsStr; let s: SmallString<[u8; 4]> = SmallString::from("foo"); let os_s: &OsStr = "foo".as_ref(); assert_eq!(s, os_s); assert_eq!(s, *os_s); assert_eq!(s, os_s.to_owned()); assert_eq!(s, Cow::Borrowed(os_s)); } #[test] fn test_from_buf() { let s: SmallString<[u8; 2]> = SmallString::from_buf([206, 177]).unwrap(); assert_eq!(s, "α"); assert!(SmallString::<[u8; 2]>::from_buf([206, 0]).is_err()); } #[test] fn test_insert() { let mut s: SmallString<[u8; 8]> = SmallString::from("abc"); s.insert(1, 'x'); assert_eq!(s, "axbc"); s.insert(3, 'α'); assert_eq!(s, "axbαc"); s.insert_str(0, "foo"); assert_eq!(s, "fooaxbαc"); } #[test] #[should_panic] fn test_insert_panic() { let mut s: SmallString<[u8; 8]> = SmallString::from("αβγ"); s.insert(1, 'x'); } #[test] fn test_into_string() { let s: SmallString<[u8; 2]> = SmallString::from("foo"); assert_eq!(s.into_string(), "foo"); let s: SmallString<[u8; 8]> = SmallString::from("foo"); assert_eq!(s.into_string(), "foo"); } #[test] fn test_to_string() { let s: SmallString<[u8; 2]> = SmallString::from("foo"); assert_eq!(s.to_string(), "foo"); let s: SmallString<[u8; 8]> = SmallString::from("foo"); assert_eq!(s.to_string(), "foo"); } #[test] fn test_pop() { let mut s: SmallString<[u8; 8]> = SmallString::from("αβγ"); assert_eq!(s.pop(), Some('γ')); assert_eq!(s.pop(), Some('β')); assert_eq!(s.pop(), Some('α')); assert_eq!(s.pop(), None); } #[test] fn test_remove() { let mut s: SmallString<[u8; 8]> = SmallString::from("αβγ"); assert_eq!(s.remove(2), 'β'); assert_eq!(s, "αγ"); assert_eq!(s.remove(0), 'α'); assert_eq!(s, "γ"); assert_eq!(s.remove(0), 'γ'); assert_eq!(s, ""); } #[test] #[should_panic] fn test_remove_panic_0() { let mut s: SmallString<[u8; 8]> = SmallString::from("foo"); // Attempt to remove at the end s.remove(3); } #[test] #[should_panic] fn test_remove_panic_1() { let mut s: SmallString<[u8; 8]> = SmallString::from("αβγ"); // Attempt to remove mid-character s.remove(1); } #[test] fn test_retain() { let mut s: SmallString<[u8; 8]> = SmallString::from("α_β_γ"); s.retain(|_| true); assert_eq!(s, "α_β_γ"); s.retain(|c| c != '_'); assert_eq!(s, "αβγ"); s.retain(|c| c != 'β'); assert_eq!(s, "αγ"); s.retain(|c| c == 'α'); assert_eq!(s, "α"); s.retain(|_| false); assert_eq!(s, ""); } #[test] fn test_truncate() { let mut s: SmallString<[u8; 2]> = SmallString::from("foobar"); s.truncate(6); assert_eq!(s, "foobar"); s.truncate(3); assert_eq!(s, "foo"); } #[test] #[should_panic] fn test_truncate_panic() { let mut s: SmallString<[u8; 2]> = SmallString::from("α"); s.truncate(1); } #[test] fn test_write() { use core::fmt::Write; let mut s: SmallString<[u8; 8]> = SmallString::from("foo"); write!(s, "bar").unwrap(); assert_eq!(s, "foobar"); } #[cfg(feature = "serde")] #[test] fn test_serde() { use bincode::{deserialize, serialize}; let mut small_str: SmallString<[u8; 4]> = SmallString::from("foo"); let encoded = serialize(&small_str).unwrap(); let decoded: SmallString<[u8; 4]> = deserialize(&encoded).unwrap(); assert_eq!(small_str, decoded); // Spill the vec small_str.push_str("bar"); // Check again after spilling. let encoded = serialize(&small_str).unwrap(); let decoded: SmallString<[u8; 4]> = deserialize(&encoded).unwrap(); assert_eq!(small_str, decoded); } }