smol_str-0.3.5/.cargo_vcs_info.json0000644000000001520000000000100127010ustar { "git": { "sha1": "52bb972c34c3a3423f1ed2228e7ee030c2d91eb7" }, "path_in_vcs": "lib/smol_str" }smol_str-0.3.5/CHANGELOG.md000064400000000000000000000023341046102023000133060ustar 00000000000000# Changelog ## Unreleased - Optimise `SmolStr::clone` 4-5x speedup inline, 0.5x heap (slow down). ## 0.3.4 - 2025-10-23 - Added `rust-version` field to `Cargo.toml` ## 0.3.3 - 2025-10-23 - Optimise `StrExt::to_ascii_lowercase_smolstr`, `StrExt::to_ascii_uppercase_smolstr` ~2x speedup inline, ~4-22x for heap. - Optimise `StrExt::to_lowercase_smolstr`, `StrExt::to_uppercase_smolstr` ~2x speedup inline, ~5-50x for heap. - Optimise `StrExt::replace_smolstr`, `StrExt::replacen_smolstr` for single ascii replace, ~3x speedup inline & heap. ## 0.3.2 - 2024-10-23 - Fix `SmolStrBuilder::push` incorrectly padding null bytes when spilling onto the heap on a multibyte character push ## 0.3.1 - 2024-09-04 - Fix `SmolStrBuilder` leaking implementation details ## 0.3.0 - 2024-09-04 - Remove deprecated `SmolStr::new_inline_from_ascii` function - Remove `SmolStr::to_string` in favor of `ToString::to_string` - Add `impl AsRef<[u8]> for SmolStr` impl - Add `impl AsRef for SmolStr` impl - Add `impl AsRef for SmolStr` impl - Add `SmolStrBuilder` ## 0.2.2 - 2024-05-14 - Add `StrExt` trait providing `to_lowercase_smolstr`, `replace_smolstr` and similar - Add `PartialEq` optimization for `ptr_eq`-able representations smol_str-0.3.5/Cargo.lock0000644000000466630000000000100106750ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 4 [[package]] name = "aho-corasick" version = "1.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" dependencies = [ "memchr", ] [[package]] name = "anes" version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299" [[package]] name = "anstyle" version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "862ed96ca487e809f1c8e5a8447f6ee2cf102f846893800b20cebdf541fc6bbd" [[package]] name = "arbitrary" version = "1.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1" [[package]] name = "autocfg" version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" [[package]] name = "bit-set" version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" dependencies = [ "bit-vec", ] [[package]] name = "bit-vec" version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" [[package]] name = "bitflags" version = "2.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2261d10cca569e4643e526d8dc2e62e433cc8aba21ab764233731f8d369bf394" [[package]] name = "borsh" version = "1.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ad8646f98db542e39fc66e68a20b2144f6a732636df7c2354e74645faaa433ce" dependencies = [ "cfg_aliases", ] [[package]] name = "bumpalo" version = "3.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "46c5e41b57b8bba42a04676d81cb89e9ee8e859a1a66f80a5a72e1cb76b34d43" [[package]] name = "cast" version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" [[package]] name = "cfg-if" version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2fd1289c04a9ea8cb22300a459a72a385d7c73d3259e2ed7dcb2af674838cfa9" [[package]] name = "cfg_aliases" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" [[package]] name = "ciborium" version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e" dependencies = [ "ciborium-io", "ciborium-ll", "serde", ] [[package]] name = "ciborium-io" version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757" [[package]] name = "ciborium-ll" version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9" dependencies = [ "ciborium-io", "half", ] [[package]] name = "clap" version = "4.5.48" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e2134bb3ea021b78629caa971416385309e0131b351b25e01dc16fb54e1b5fae" dependencies = [ "clap_builder", ] [[package]] name = "clap_builder" version = "4.5.48" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2ba64afa3c0a6df7fa517765e31314e983f51dda798ffba27b988194fb65dc9" dependencies = [ "anstyle", "clap_lex", ] [[package]] name = "clap_lex" version = "0.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b94f61472cee1439c0b966b47e3aca9ae07e45d070759512cd390ea2bebc6675" [[package]] name = "criterion" version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e1c047a62b0cc3e145fa84415a3191f628e980b194c2755aa12300a4e6cbd928" dependencies = [ "anes", "cast", "ciborium", "clap", "criterion-plot", "itertools", "num-traits", "oorandom", "plotters", "rayon", "regex", "serde", "serde_json", "tinytemplate", "walkdir", ] [[package]] name = "criterion-plot" version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b1bcc0dc7dfae599d84ad0b1a55f80cde8af3725da8313b528da95ef783e338" dependencies = [ "cast", "itertools", ] [[package]] name = "crossbeam-deque" version = "0.8.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9dd111b7b7f7d55b72c0a6ae361660ee5853c9af73f70c3c2ef6858b950e2e51" dependencies = [ "crossbeam-epoch", "crossbeam-utils", ] [[package]] name = "crossbeam-epoch" version = "0.9.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e" dependencies = [ "crossbeam-utils", ] [[package]] name = "crossbeam-utils" version = "0.8.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" [[package]] name = "crunchy" version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" [[package]] name = "either" version = "1.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" [[package]] name = "errno" version = "0.3.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", "windows-sys", ] [[package]] name = "fastrand" version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" [[package]] name = "fnv" version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" [[package]] name = "getrandom" version = "0.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" dependencies = [ "cfg-if", "libc", "r-efi", "wasip2", ] [[package]] name = "half" version = "2.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" dependencies = [ "cfg-if", "crunchy", "zerocopy", ] [[package]] name = "itertools" version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" dependencies = [ "either", ] [[package]] name = "itoa" version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" [[package]] name = "js-sys" version = "0.3.82" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b011eec8cc36da2aab2d5cff675ec18454fad408585853910a202391cf9f8e65" dependencies = [ "once_cell", "wasm-bindgen", ] [[package]] name = "libc" version = "0.2.175" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6a82ae493e598baaea5209805c49bbf2ea7de956d50d7da0da1164f9c6d28543" [[package]] name = "linux-raw-sys" version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039" [[package]] name = "memchr" version = "2.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273" [[package]] name = "num-traits" version = "0.2.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" dependencies = [ "autocfg", ] [[package]] name = "once_cell" version = "1.21.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" [[package]] name = "oorandom" version = "11.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e" [[package]] name = "plotters" version = "0.3.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5aeb6f403d7a4911efb1e33402027fc44f29b5bf6def3effcc22d7bb75f2b747" dependencies = [ "num-traits", "plotters-backend", "plotters-svg", "wasm-bindgen", "web-sys", ] [[package]] name = "plotters-backend" version = "0.3.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df42e13c12958a16b3f7f4386b9ab1f3e7933914ecea48da7139435263a4172a" [[package]] name = "plotters-svg" version = "0.3.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "51bae2ac328883f7acdfea3d66a7c35751187f870bc81f94563733a154d7a670" dependencies = [ "plotters-backend", ] [[package]] name = "ppv-lite86" version = "0.2.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" dependencies = [ "zerocopy", ] [[package]] name = "proc-macro2" version = "1.0.101" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "89ae43fd86e4158d6db51ad8e2b80f313af9cc74f5c0e03ccb87de09998732de" dependencies = [ "unicode-ident", ] [[package]] name = "proptest" version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bee689443a2bd0a16ab0348b52ee43e3b2d1b1f931c8aa5c9f8de4c86fbe8c40" dependencies = [ "bit-set", "bit-vec", "bitflags", "num-traits", "rand", "rand_chacha", "rand_xorshift", "regex-syntax", "rusty-fork", "tempfile", "unarray", ] [[package]] name = "quick-error" version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" [[package]] name = "quote" version = "1.0.40" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d" dependencies = [ "proc-macro2", ] [[package]] name = "r-efi" version = "5.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" [[package]] name = "rand" version = "0.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1" dependencies = [ "rand_chacha", "rand_core", ] [[package]] name = "rand_chacha" version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" dependencies = [ "ppv-lite86", "rand_core", ] [[package]] name = "rand_core" version = "0.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "99d9a13982dcf210057a8a78572b2217b667c3beacbf3a0d8b454f6f82837d38" dependencies = [ "getrandom", ] [[package]] name = "rand_xorshift" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "513962919efc330f829edb2535844d1b912b0fbe2ca165d613e4e8788bb05a5a" dependencies = [ "rand_core", ] [[package]] name = "rayon" version = "1.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "368f01d005bf8fd9b1206fb6fa653e6c4a81ceb1466406b81792d87c5677a58f" dependencies = [ "either", "rayon-core", ] [[package]] name = "rayon-core" version = "1.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" dependencies = [ "crossbeam-deque", "crossbeam-utils", ] [[package]] name = "regex" version = "1.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "843bc0191f75f3e22651ae5f1e72939ab2f72a4bc30fa80a066bd66edefc24d4" dependencies = [ "aho-corasick", "memchr", "regex-automata", "regex-syntax", ] [[package]] name = "regex-automata" version = "0.4.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5276caf25ac86c8d810222b3dbb938e512c55c6831a10f3e6ed1c93b84041f1c" dependencies = [ "aho-corasick", "memchr", "regex-syntax", ] [[package]] name = "regex-syntax" version = "0.8.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7a2d987857b319362043e95f5353c0535c1f58eec5336fdfcf626430af7def58" [[package]] name = "rustix" version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cd15f8a2c5551a84d56efdc1cd049089e409ac19a3072d5037a17fd70719ff3e" dependencies = [ "bitflags", "errno", "libc", "linux-raw-sys", "windows-sys", ] [[package]] name = "rustversion" version = "1.0.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" [[package]] name = "rusty-fork" version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2" dependencies = [ "fnv", "quick-error", "tempfile", "wait-timeout", ] [[package]] name = "ryu" version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f" [[package]] name = "same-file" version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" dependencies = [ "winapi-util", ] [[package]] name = "serde" version = "1.0.226" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0dca6411025b24b60bfa7ec1fe1f8e710ac09782dca409ee8237ba74b51295fd" dependencies = [ "serde_core", "serde_derive", ] [[package]] name = "serde_core" version = "1.0.226" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ba2ba63999edb9dac981fb34b3e5c0d111a69b0924e253ed29d83f7c99e966a4" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" version = "1.0.226" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8db53ae22f34573731bafa1db20f04027b2d25e02d8205921b569171699cdb33" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "serde_json" version = "1.0.145" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "402a6f66d8c709116cf22f558eab210f5a50187f702eb4d7e5ef38d9a7f1c79c" dependencies = [ "itoa", "memchr", "ryu", "serde", "serde_core", ] [[package]] name = "smol_str" version = "0.3.5" dependencies = [ "arbitrary", "borsh", "criterion", "proptest", "rand", "serde", "serde_core", "serde_json", ] [[package]] name = "syn" version = "2.0.106" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ede7c438028d4436d71104916910f5bb611972c5cfd7f89b8300a8186e6fada6" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "tempfile" version = "3.23.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2d31c77bdf42a745371d260a26ca7163f1e0924b64afa0b688e61b5a9fa02f16" dependencies = [ "fastrand", "getrandom", "once_cell", "rustix", "windows-sys", ] [[package]] name = "tinytemplate" version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "be4d6b5f19ff7664e8c98d03e2139cb510db9b0a60b55f8e8709b689d939b6bc" dependencies = [ "serde", "serde_json", ] [[package]] name = "unarray" version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" [[package]] name = "unicode-ident" version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f63a545481291138910575129486daeaf8ac54aee4387fe7906919f7830c7d9d" [[package]] name = "wait-timeout" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11" dependencies = [ "libc", ] [[package]] name = "walkdir" version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" dependencies = [ "same-file", "winapi-util", ] [[package]] name = "wasip2" version = "1.0.1+wasi-0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0562428422c63773dad2c345a1882263bbf4d65cf3f42e90921f787ef5ad58e7" dependencies = [ "wit-bindgen", ] [[package]] name = "wasm-bindgen" version = "0.2.105" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da95793dfc411fbbd93f5be7715b0578ec61fe87cb1a42b12eb625caa5c5ea60" dependencies = [ "cfg-if", "once_cell", "rustversion", "wasm-bindgen-macro", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-macro" version = "0.2.105" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "04264334509e04a7bf8690f2384ef5265f05143a4bff3889ab7a3269adab59c2" dependencies = [ "quote", "wasm-bindgen-macro-support", ] [[package]] name = "wasm-bindgen-macro-support" version = "0.2.105" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "420bc339d9f322e562942d52e115d57e950d12d88983a14c79b86859ee6c7ebc" dependencies = [ "bumpalo", "proc-macro2", "quote", "syn", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" version = "0.2.105" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "76f218a38c84bcb33c25ec7059b07847d465ce0e0a76b995e134a45adcb6af76" dependencies = [ "unicode-ident", ] [[package]] name = "web-sys" version = "0.3.82" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a1f95c0d03a47f4ae1f7a64643a6bb97465d9b740f0fa8f90ea33915c99a9a1" dependencies = [ "js-sys", "wasm-bindgen", ] [[package]] name = "winapi-util" version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ "windows-sys", ] [[package]] name = "windows-link" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "45e46c0661abb7180e7b9c281db115305d49ca1709ab8242adf09666d2173c65" [[package]] name = "windows-sys" version = "0.61.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e201184e40b2ede64bc2ea34968b28e33622acdbbf37104f0e4a33f7abe657aa" dependencies = [ "windows-link", ] [[package]] name = "wit-bindgen" version = "0.46.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59" [[package]] name = "zerocopy" version = "0.8.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0894878a5fa3edfd6da3f88c4805f4c8558e2b996227a3d864f47fe11e38282c" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" version = "0.8.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "88d2b8d9c68ad2b9e4340d7832716a4d21a22a1154777ad56ea55c51a9cf3831" dependencies = [ "proc-macro2", "quote", "syn", ] smol_str-0.3.5/Cargo.toml0000644000000057750000000000100107170ustar # 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 = "2024" rust-version = "1.89" name = "smol_str" version = "0.3.5" authors = [ "Aleksey Kladov ", "Lukas Wirth ", ] build = false autolib = false autobins = false autoexamples = false autotests = false autobenches = false description = "small-string optimized string type with O(1) clone" readme = "README.md" license = "MIT OR Apache-2.0" repository = "https://github.com/rust-lang/rust-analyzer/tree/master/lib/smol_str" resolver = "2" [package.metadata.docs.rs] rustdoc-args = [ "--cfg", "docsrs", ] all-features = true [features] default = ["std"] serde = ["dep:serde_core"] std = [ "serde_core?/std", "borsh?/std", ] [lib] name = "smol_str" path = "src/lib.rs" [[test]] name = "test" path = "tests/test.rs" [[test]] name = "tidy" path = "tests/tidy.rs" [[bench]] name = "bench" path = "benches/bench.rs" harness = false [dependencies.arbitrary] version = "1.3" optional = true [dependencies.borsh] version = "1.4.0" optional = true default-features = false [dependencies.serde_core] version = "1.0.220" optional = true default-features = false [dev-dependencies.criterion] version = "0.7" [dev-dependencies.proptest] version = "1.5" [dev-dependencies.rand] version = "0.9.2" [dev-dependencies.serde] version = "1.0" features = ["derive"] [dev-dependencies.serde_json] version = "1.0" [lints.clippy] assigning_clones = "allow" dbg_macro = "warn" enum_variant_names = "allow" len_without_is_empty = "allow" literal_string_with_formatting_args = "allow" new_ret_no_self = "allow" print_stderr = "warn" print_stdout = "warn" rc_buffer = "warn" result_unit_err = "allow" single_match = "allow" str_to_string = "warn" todo = "warn" too_long_first_doc_paragraph = "allow" too_many_arguments = "allow" type_complexity = "allow" unnecessary_map_or = "allow" useless_asref = "allow" vec_init_then_push = "allow" wrong_self_convention = "allow" [lints.clippy.complexity] level = "warn" priority = -1 [lints.clippy.correctness] level = "deny" priority = -1 [lints.clippy.perf] level = "deny" priority = -1 [lints.clippy.restriction] level = "allow" priority = -1 [lints.clippy.style] level = "warn" priority = -1 [lints.clippy.suspicious] level = "warn" priority = -1 [lints.rust] elided_lifetimes_in_paths = "warn" explicit_outlives_requirements = "warn" unreachable_pub = "warn" unsafe_op_in_unsafe_fn = "warn" unused_extern_crates = "warn" unused_lifetimes = "warn" [lints.rust.unexpected_cfgs] level = "warn" priority = 0 check-cfg = [ "cfg(bootstrap)", "cfg(no_salsa_async_drops)", ] smol_str-0.3.5/Cargo.toml.orig000064400000000000000000000017041046102023000143640ustar 00000000000000[package] name = "smol_str" version = "0.3.5" description = "small-string optimized string type with O(1) clone" license = "MIT OR Apache-2.0" repository = "https://github.com/rust-lang/rust-analyzer/tree/master/lib/smol_str" authors = ["Aleksey Kladov ", "Lukas Wirth "] edition = "2024" rust-version = "1.89" [package.metadata.docs.rs] rustdoc-args = ["--cfg", "docsrs"] all-features = true [dependencies] serde_core = { version = "1.0.220", optional = true, default-features = false } borsh = { version = "1.4.0", optional = true, default-features = false } arbitrary = { version = "1.3", optional = true } [dev-dependencies] proptest = "1.5" serde_json = "1.0" serde = { version = "1.0", features = ["derive"] } criterion = "0.7" rand = "0.9.2" [features] default = ["std"] std = ["serde_core?/std", "borsh?/std"] serde = ["dep:serde_core"] [[bench]] name = "bench" harness = false [lints] workspace = true smol_str-0.3.5/LICENSE-APACHE000064400000000000000000000251371046102023000134270ustar 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. smol_str-0.3.5/LICENSE-MIT000064400000000000000000000017771046102023000131430ustar 00000000000000Permission 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. smol_str-0.3.5/README.md000064400000000000000000000027721046102023000127620ustar 00000000000000# smol_str [![CI](https://github.com/rust-analyzer/smol_str/workflows/CI/badge.svg)](https://github.com/rust-analyzer/smol_str/actions?query=branch%3Amaster+workflow%3ACI) [![Crates.io](https://img.shields.io/crates/v/smol_str.svg)](https://crates.io/crates/smol_str) [![API reference](https://docs.rs/smol_str/badge.svg)](https://docs.rs/smol_str/) A `SmolStr` is a string type that has the following properties: * `size_of::() == 24` (therefore `== size_of::()` on 64 bit platforms) * `Clone` is `O(1)` * Strings are stack-allocated if they are: * Up to 23 bytes long * Longer than 23 bytes, but substrings of `WS` (see `src/lib.rs`). Such strings consist solely of consecutive newlines, followed by consecutive spaces * If a string does not satisfy the aforementioned conditions, it is heap-allocated * Additionally, a `SmolStr` can be explicitly created from a `&'static str` without allocation Unlike `String`, however, `SmolStr` is immutable. The primary use case for `SmolStr` is a good enough default storage for tokens of typical programming languages. Strings consisting of a series of newlines, followed by a series of whitespace are a typical pattern in computer programs because of indentation. Note that a specialized interner might be a better solution for some use cases. ## Benchmarks Run criterion benches with ```sh cargo bench --bench \* -- --quick ``` ## MSRV Policy Minimal Supported Rust Version: latest stable. Bumping MSRV is not considered a semver-breaking change. smol_str-0.3.5/benches/bench.rs000064400000000000000000000070451046102023000145350ustar 00000000000000use criterion::{Criterion, criterion_group, criterion_main}; use rand::distr::{Alphanumeric, SampleString}; use smol_str::{SmolStr, StrExt, ToSmolStr, format_smolstr}; use std::hint::black_box; /// 12: small (inline) /// 50: medium (heap) /// 1000: large (heap) const TEST_LENS: [usize; 3] = [12, 50, 1000]; fn format_bench(c: &mut Criterion) { for len in TEST_LENS { let n = rand::random_range(10000..99999); let str_len = len.checked_sub(n.to_smolstr().len()).unwrap(); let str = Alphanumeric.sample_string(&mut rand::rng(), str_len); c.bench_function(&format!("format_smolstr! len={len}"), |b| { let mut v = <_>::default(); b.iter(|| v = format_smolstr!("{str}-{n}")); assert_eq!(v, format!("{str}-{n}")); }); } } fn from_str_bench(c: &mut Criterion) { for len in TEST_LENS { let str = Alphanumeric.sample_string(&mut rand::rng(), len); c.bench_function(&format!("SmolStr::from len={len}"), |b| { let mut v = <_>::default(); b.iter(|| v = SmolStr::from(black_box(&str))); assert_eq!(v, str); }); } } fn clone_bench(c: &mut Criterion) { for len in TEST_LENS { let str = Alphanumeric.sample_string(&mut rand::rng(), len); let smolstr = SmolStr::new(&str); c.bench_function(&format!("SmolStr::clone len={len}"), |b| { let mut v = <_>::default(); b.iter(|| v = smolstr.clone()); assert_eq!(v, str); }); } } fn eq_bench(c: &mut Criterion) { for len in TEST_LENS { let str = Alphanumeric.sample_string(&mut rand::rng(), len); let smolstr = SmolStr::new(&str); c.bench_function(&format!("SmolStr::eq len={len}"), |b| { let mut v = false; b.iter(|| v = smolstr == black_box(&str)); assert!(v); }); } } fn to_lowercase_bench(c: &mut Criterion) { const END_CHAR: char = 'İ'; for len in TEST_LENS { // mostly ascii seq with some non-ascii at the end let mut str = Alphanumeric.sample_string(&mut rand::rng(), len - END_CHAR.len_utf8()); str.push(END_CHAR); let str = str.as_str(); c.bench_function(&format!("to_lowercase_smolstr len={len}"), |b| { let mut v = <_>::default(); b.iter(|| v = str.to_lowercase_smolstr()); assert_eq!(v, str.to_lowercase()); }); } } fn to_ascii_lowercase_bench(c: &mut Criterion) { for len in TEST_LENS { let str = Alphanumeric.sample_string(&mut rand::rng(), len); let str = str.as_str(); c.bench_function(&format!("to_ascii_lowercase_smolstr len={len}"), |b| { let mut v = <_>::default(); b.iter(|| v = str.to_ascii_lowercase_smolstr()); assert_eq!(v, str.to_ascii_lowercase()); }); } } fn replace_bench(c: &mut Criterion) { for len in TEST_LENS { let s_dash_s = Alphanumeric.sample_string(&mut rand::rng(), len / 2) + "-" + &Alphanumeric.sample_string(&mut rand::rng(), len - 1 - len / 2); let str = s_dash_s.as_str(); c.bench_function(&format!("replace_smolstr len={len}"), |b| { let mut v = <_>::default(); b.iter(|| v = str.replace_smolstr("-", "_")); assert_eq!(v, str.replace("-", "_")); }); } } criterion_group!( benches, format_bench, from_str_bench, clone_bench, eq_bench, to_lowercase_bench, to_ascii_lowercase_bench, replace_bench, ); criterion_main!(benches); smol_str-0.3.5/src/borsh.rs000064400000000000000000000027311046102023000137500ustar 00000000000000use crate::{INLINE_CAP, Repr, SmolStr}; use alloc::string::{String, ToString}; use borsh::{ BorshDeserialize, BorshSerialize, io::{Error, ErrorKind, Read, Write}, }; use core::mem::transmute; impl BorshSerialize for SmolStr { fn serialize(&self, writer: &mut W) -> borsh::io::Result<()> { self.as_str().serialize(writer) } } impl BorshDeserialize for SmolStr { #[inline] fn deserialize_reader(reader: &mut R) -> borsh::io::Result { let len = u32::deserialize_reader(reader)?; if (len as usize) < INLINE_CAP { let mut buf = [0u8; INLINE_CAP]; reader.read_exact(&mut buf[..len as usize])?; _ = core::str::from_utf8(&buf[..len as usize]).map_err(|err| { let msg = err.to_string(); Error::new(ErrorKind::InvalidData, msg) })?; Ok(SmolStr(Repr::Inline { len: unsafe { transmute::(len as u8) }, buf, })) } else { // u8::vec_from_reader always returns Some on success in current implementation let vec = u8::vec_from_reader(len, reader)? .ok_or_else(|| Error::other("u8::vec_from_reader unexpectedly returned None"))?; Ok(SmolStr::from(String::from_utf8(vec).map_err(|err| { let msg = err.to_string(); Error::new(ErrorKind::InvalidData, msg) })?)) } } } smol_str-0.3.5/src/gdb_smolstr_printer.py000064400000000000000000000105261046102023000167220ustar 00000000000000# Pretty printer for smol_str::SmolStr # # Usage (any of these): # (gdb) source /path/to/gdb_smolstr_printer.py # or add to .gdbinit # python # import gdb # gdb.execute("source /path/to/gdb_smolstr_printer.py") # end # # After loading: # (gdb) info pretty-printer # ... # global pretty-printers: # smol_str # SmolStr # # Disable/enable: # (gdb) disable pretty-printer global smol_str SmolStr # (gdb) enable pretty-printer global smol_str SmolStr import gdb import gdb.printing import re SMOL_INLINE_SIZE_RE = re.compile(r".*::_V(\d+)$") def _read_utf8(mem): try: return mem.tobytes().decode("utf-8", errors="replace") except Exception: return repr(mem.tobytes()) def _active_variant(enum_val): """Return (variant_name, variant_value) for a Rust enum value using discriminant logic. Assume layout: fields[0] is unnamed u8 discriminant; fields[1] is the active variant. """ fields = enum_val.type.fields() if len(fields) < 2: return None, None variant_field = fields[1] return variant_field.name, enum_val[variant_field] class SmolStrProvider: def __init__(self, val): self.val = val def to_string(self): try: repr_enum = self.val["__0"] except Exception: return "" variant_name, variant_val = _active_variant(repr_enum) if not variant_name: return "" if variant_name == "Inline": try: inline_len_val = variant_val["len"] m = SMOL_INLINE_SIZE_RE.match(str(inline_len_val)) if not m: return "" length = int(m.group(1)) buf = variant_val["buf"] data = bytes(int(buf[i]) for i in range(length)) return data.decode("utf-8", errors="replace") except Exception as e: return f"" if variant_name == "Static": try: # variant_val["__0"] is &'static str return variant_val["__0"] except Exception as e: return f"" if variant_name == "Heap": try: # variant_val["__0"] is an Arc inner = variant_val["__0"]["ptr"]["pointer"] # inner is a fat pointer to ArcInner data_ptr = inner["data_ptr"] length = int(inner["length"]) # ArcInner layout: # strong: Atomic, weak: Atomic | unsized tail 'data' bytes. sizeof_AtomicUsize = gdb.lookup_type( "core::sync::atomic::AtomicUsize" ).sizeof header_size = sizeof_AtomicUsize * 2 # strong + weak counters data_arr = int(data_ptr) + header_size mem = gdb.selected_inferior().read_memory(data_arr, length) return _read_utf8(mem) except Exception as e: return f"" return f"" def display_hint(self): return "string" class SmolStrSubPrinter(gdb.printing.SubPrettyPrinter): def __init__(self): super(SmolStrSubPrinter, self).__init__("SmolStr") def __call__(self, val): if not self.enabled: return None try: t = val.type.strip_typedefs() if t.code == gdb.TYPE_CODE_STRUCT and t.name == "smol_str::SmolStr": return SmolStrProvider(val) except Exception: pass return None class SmolStrPrettyPrinter(gdb.printing.PrettyPrinter): def __init__(self): super(SmolStrPrettyPrinter, self).__init__("smol_str", []) self.subprinters = [] self._sp = SmolStrSubPrinter() self.subprinters.append(self._sp) def __call__(self, val): # Iterate subprinters (only one now, scalable for future) for sp in self.subprinters: pp = sp(val) if pp is not None: return pp return None printer = SmolStrPrettyPrinter() def register_printers(objfile=None): gdb.printing.register_pretty_printer(objfile, printer, replace=True) register_printers() smol_str-0.3.5/src/lib.rs000064400000000000000000000723021046102023000134020ustar 00000000000000#![cfg_attr(not(feature = "std"), no_std)] #![cfg_attr(docsrs, feature(doc_cfg))] #![debugger_visualizer(gdb_script_file = "gdb_smolstr_printer.py")] extern crate alloc; use alloc::{borrow::Cow, boxed::Box, string::String, sync::Arc}; use core::{ borrow::Borrow, cmp::{self, Ordering}, convert::Infallible, fmt, hash, iter, mem, ops, str::FromStr, }; /// A `SmolStr` is a string type that has the following properties: /// /// * `size_of::() == 24` (therefor `== size_of::()` on 64 bit platforms) /// * `Clone` is `O(1)` /// * Strings are stack-allocated if they are: /// * Up to 23 bytes long /// * Longer than 23 bytes, but substrings of `WS` (see below). Such strings consist /// solely of consecutive newlines, followed by consecutive spaces /// * If a string does not satisfy the aforementioned conditions, it is heap-allocated /// * Additionally, a `SmolStr` can be explicitly created from a `&'static str` without allocation /// /// Unlike `String`, however, `SmolStr` is immutable. The primary use case for /// `SmolStr` is a good enough default storage for tokens of typical programming /// languages. Strings consisting of a series of newlines, followed by a series of /// whitespace are a typical pattern in computer programs because of indentation. /// Note that a specialized interner might be a better solution for some use cases. /// /// `WS`: A string of 32 newlines followed by 128 spaces. pub struct SmolStr(Repr); impl SmolStr { /// Constructs an inline variant of `SmolStr`. /// /// This never allocates. /// /// # Panics /// /// Panics if `text.len() > 23`. #[inline] pub const fn new_inline(text: &str) -> SmolStr { assert!(text.len() <= INLINE_CAP); // avoids bounds checks in loop let text = text.as_bytes(); let mut buf = [0; INLINE_CAP]; let mut i = 0; while i < text.len() { buf[i] = text[i]; i += 1 } SmolStr(Repr::Inline { // SAFETY: We know that `len` is less than or equal to the maximum value of `InlineSize` // as we asserted it. len: unsafe { InlineSize::transmute_from_u8(text.len() as u8) }, buf, }) } /// Constructs a `SmolStr` from a statically allocated string. /// /// This never allocates. #[inline(always)] pub const fn new_static(text: &'static str) -> SmolStr { // NOTE: this never uses the inline storage; if a canonical // representation is needed, we could check for `len() < INLINE_CAP` // and call `new_inline`, but this would mean an extra branch. SmolStr(Repr::Static(text)) } /// Constructs a `SmolStr` from a `str`, heap-allocating if necessary. #[inline(always)] pub fn new(text: impl AsRef) -> SmolStr { SmolStr(Repr::new(text.as_ref())) } /// Returns a `&str` slice of this `SmolStr`. #[inline(always)] pub fn as_str(&self) -> &str { self.0.as_str() } /// Returns the length of `self` in bytes. #[inline(always)] pub fn len(&self) -> usize { self.0.len() } /// Returns `true` if `self` has a length of zero bytes. #[inline(always)] pub fn is_empty(&self) -> bool { self.0.is_empty() } /// Returns `true` if `self` is heap-allocated. #[inline(always)] pub const fn is_heap_allocated(&self) -> bool { matches!(self.0, Repr::Heap(..)) } } impl Clone for SmolStr { #[inline] fn clone(&self) -> Self { // hint for faster inline / slower heap clones #[cold] #[inline(never)] fn cold_clone(v: &SmolStr) -> SmolStr { SmolStr(v.0.clone()) } if self.is_heap_allocated() { return cold_clone(self); } // SAFETY: We verified that the payload of `Repr` is a POD unsafe { core::ptr::read(self as *const SmolStr) } } } impl Default for SmolStr { #[inline(always)] fn default() -> SmolStr { SmolStr(Repr::Inline { len: InlineSize::_V0, buf: [0; INLINE_CAP] }) } } impl ops::Deref for SmolStr { type Target = str; #[inline(always)] fn deref(&self) -> &str { self.as_str() } } // region: PartialEq implementations impl Eq for SmolStr {} impl PartialEq for SmolStr { fn eq(&self, other: &SmolStr) -> bool { self.0.ptr_eq(&other.0) || self.as_str() == other.as_str() } } impl PartialEq for SmolStr { #[inline(always)] fn eq(&self, other: &str) -> bool { self.as_str() == other } } impl PartialEq for str { #[inline(always)] fn eq(&self, other: &SmolStr) -> bool { other == self } } impl<'a> PartialEq<&'a str> for SmolStr { #[inline(always)] fn eq(&self, other: &&'a str) -> bool { self == *other } } impl PartialEq for &str { #[inline(always)] fn eq(&self, other: &SmolStr) -> bool { *self == other } } impl PartialEq for SmolStr { #[inline(always)] fn eq(&self, other: &String) -> bool { self.as_str() == other } } impl PartialEq for String { #[inline(always)] fn eq(&self, other: &SmolStr) -> bool { other == self } } impl<'a> PartialEq<&'a String> for SmolStr { #[inline(always)] fn eq(&self, other: &&'a String) -> bool { self == *other } } impl PartialEq for &String { #[inline(always)] fn eq(&self, other: &SmolStr) -> bool { *self == other } } // endregion: PartialEq implementations impl Ord for SmolStr { fn cmp(&self, other: &SmolStr) -> Ordering { self.as_str().cmp(other.as_str()) } } impl PartialOrd for SmolStr { fn partial_cmp(&self, other: &SmolStr) -> Option { Some(self.cmp(other)) } } impl hash::Hash for SmolStr { fn hash(&self, hasher: &mut H) { self.as_str().hash(hasher); } } impl fmt::Debug for SmolStr { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Debug::fmt(self.as_str(), f) } } impl fmt::Display for SmolStr { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Display::fmt(self.as_str(), f) } } impl iter::FromIterator for SmolStr { fn from_iter>(iter: I) -> SmolStr { from_char_iter(iter.into_iter()) } } #[inline] fn from_char_iter(iter: impl Iterator) -> SmolStr { from_buf_and_chars([0; _], 0, iter) } fn from_buf_and_chars( mut buf: [u8; INLINE_CAP], buf_len: usize, mut iter: impl Iterator, ) -> SmolStr { let min_size = iter.size_hint().0 + buf_len; if min_size > INLINE_CAP { let heap: String = core::str::from_utf8(&buf[..buf_len]).unwrap().chars().chain(iter).collect(); if heap.len() <= INLINE_CAP { // size hint lied return SmolStr::new_inline(&heap); } return SmolStr(Repr::Heap(heap.into_boxed_str().into())); } let mut len = buf_len; while let Some(ch) = iter.next() { let size = ch.len_utf8(); if size + len > INLINE_CAP { let (min_remaining, _) = iter.size_hint(); let mut heap = String::with_capacity(size + len + min_remaining); heap.push_str(core::str::from_utf8(&buf[..len]).unwrap()); heap.push(ch); heap.extend(iter); return SmolStr(Repr::Heap(heap.into_boxed_str().into())); } ch.encode_utf8(&mut buf[len..]); len += size; } SmolStr(Repr::Inline { // SAFETY: We know that `len` is less than or equal to the maximum value of `InlineSize` // as we otherwise return early. len: unsafe { InlineSize::transmute_from_u8(len as u8) }, buf, }) } fn build_from_str_iter(mut iter: impl Iterator) -> SmolStr where T: AsRef, String: iter::Extend, { let mut len = 0; let mut buf = [0u8; INLINE_CAP]; while let Some(slice) = iter.next() { let slice = slice.as_ref(); let size = slice.len(); if size + len > INLINE_CAP { let mut heap = String::with_capacity(size + len); heap.push_str(core::str::from_utf8(&buf[..len]).unwrap()); heap.push_str(slice); heap.extend(iter); return SmolStr(Repr::Heap(heap.into_boxed_str().into())); } buf[len..][..size].copy_from_slice(slice.as_bytes()); len += size; } SmolStr(Repr::Inline { // SAFETY: We know that `len` is less than or equal to the maximum value of `InlineSize` // as we otherwise return early. len: unsafe { InlineSize::transmute_from_u8(len as u8) }, buf, }) } impl iter::FromIterator for SmolStr { fn from_iter>(iter: I) -> SmolStr { build_from_str_iter(iter.into_iter()) } } impl<'a> iter::FromIterator<&'a String> for SmolStr { fn from_iter>(iter: I) -> SmolStr { SmolStr::from_iter(iter.into_iter().map(|x| x.as_str())) } } impl<'a> iter::FromIterator<&'a str> for SmolStr { fn from_iter>(iter: I) -> SmolStr { build_from_str_iter(iter.into_iter()) } } impl AsRef for SmolStr { #[inline(always)] fn as_ref(&self) -> &str { self.as_str() } } impl AsRef<[u8]> for SmolStr { #[inline(always)] fn as_ref(&self) -> &[u8] { self.as_str().as_bytes() } } #[cfg(feature = "std")] #[cfg_attr(docsrs, doc(cfg(feature = "std")))] impl AsRef for SmolStr { #[inline(always)] fn as_ref(&self) -> &std::ffi::OsStr { AsRef::::as_ref(self.as_str()) } } #[cfg(feature = "std")] #[cfg_attr(docsrs, doc(cfg(feature = "std")))] impl AsRef for SmolStr { #[inline(always)] fn as_ref(&self) -> &std::path::Path { AsRef::::as_ref(self.as_str()) } } impl From<&str> for SmolStr { #[inline] fn from(s: &str) -> SmolStr { SmolStr::new(s) } } impl From<&mut str> for SmolStr { #[inline] fn from(s: &mut str) -> SmolStr { SmolStr::new(s) } } impl From<&String> for SmolStr { #[inline] fn from(s: &String) -> SmolStr { SmolStr::new(s) } } impl From for SmolStr { #[inline(always)] fn from(text: String) -> Self { Self::new(text) } } impl From> for SmolStr { #[inline] fn from(s: Box) -> SmolStr { SmolStr::new(s) } } impl From> for SmolStr { #[inline] fn from(s: Arc) -> SmolStr { let repr = Repr::new_on_stack(s.as_ref()).unwrap_or(Repr::Heap(s)); Self(repr) } } impl<'a> From> for SmolStr { #[inline] fn from(s: Cow<'a, str>) -> SmolStr { SmolStr::new(s) } } impl From for Arc { #[inline(always)] fn from(text: SmolStr) -> Self { match text.0 { Repr::Heap(data) => data, _ => text.as_str().into(), } } } impl From for String { #[inline(always)] fn from(text: SmolStr) -> Self { text.as_str().into() } } impl Borrow for SmolStr { #[inline(always)] fn borrow(&self) -> &str { self.as_str() } } impl FromStr for SmolStr { type Err = Infallible; #[inline] fn from_str(s: &str) -> Result { Ok(SmolStr::from(s)) } } const INLINE_CAP: usize = InlineSize::_V23 as usize; const N_NEWLINES: usize = 32; const N_SPACES: usize = 128; const WS: &str = "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n "; const _: () = { assert!(WS.len() == N_NEWLINES + N_SPACES); assert!(WS.as_bytes()[N_NEWLINES - 1] == b'\n'); assert!(WS.as_bytes()[N_NEWLINES] == b' '); }; /// A [`u8`] with a bunch of niches. #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] enum InlineSize { _V0 = 0, _V1, _V2, _V3, _V4, _V5, _V6, _V7, _V8, _V9, _V10, _V11, _V12, _V13, _V14, _V15, _V16, _V17, _V18, _V19, _V20, _V21, _V22, _V23, } impl InlineSize { /// SAFETY: `value` must be less than or equal to [`INLINE_CAP`] #[inline(always)] const unsafe fn transmute_from_u8(value: u8) -> Self { debug_assert!(value <= InlineSize::_V23 as u8); // SAFETY: The caller is responsible to uphold this invariant unsafe { mem::transmute::(value) } } } #[derive(Clone, Debug)] enum Repr { Inline { len: InlineSize, buf: [u8; INLINE_CAP] }, Static(&'static str), Heap(Arc), } impl Repr { /// This function tries to create a new Repr::Inline or Repr::Static /// If it isn't possible, this function returns None fn new_on_stack(text: T) -> Option where T: AsRef, { let text = text.as_ref(); let len = text.len(); if len <= INLINE_CAP { let mut buf = [0; INLINE_CAP]; buf[..len].copy_from_slice(text.as_bytes()); return Some(Repr::Inline { // SAFETY: We know that `len` is less than or equal to the maximum value of `InlineSize` len: unsafe { InlineSize::transmute_from_u8(len as u8) }, buf, }); } if len <= N_NEWLINES + N_SPACES { let bytes = text.as_bytes(); let possible_newline_count = cmp::min(len, N_NEWLINES); let newlines = bytes[..possible_newline_count].iter().take_while(|&&b| b == b'\n').count(); let possible_space_count = len - newlines; if possible_space_count <= N_SPACES && bytes[newlines..].iter().all(|&b| b == b' ') { let spaces = possible_space_count; let substring = &WS[N_NEWLINES - newlines..N_NEWLINES + spaces]; return Some(Repr::Static(substring)); } } None } fn new(text: &str) -> Self { Self::new_on_stack(text).unwrap_or_else(|| Repr::Heap(Arc::from(text))) } #[inline(always)] fn len(&self) -> usize { match self { Repr::Heap(data) => data.len(), Repr::Static(data) => data.len(), Repr::Inline { len, .. } => *len as usize, } } #[inline(always)] fn is_empty(&self) -> bool { match self { Repr::Heap(data) => data.is_empty(), Repr::Static(data) => data.is_empty(), &Repr::Inline { len, .. } => len as u8 == 0, } } #[inline] fn as_str(&self) -> &str { match self { Repr::Heap(data) => data, Repr::Static(data) => data, Repr::Inline { len, buf } => { let len = *len as usize; // SAFETY: len is guaranteed to be <= INLINE_CAP let buf = unsafe { buf.get_unchecked(..len) }; // SAFETY: buf is guaranteed to be valid utf8 for ..len bytes unsafe { ::core::str::from_utf8_unchecked(buf) } } } } fn ptr_eq(&self, other: &Self) -> bool { match (self, other) { (Self::Heap(l0), Self::Heap(r0)) => Arc::ptr_eq(l0, r0), (Self::Static(l0), Self::Static(r0)) => core::ptr::eq(l0, r0), (Self::Inline { len: l_len, buf: l_buf }, Self::Inline { len: r_len, buf: r_buf }) => { l_len == r_len && l_buf == r_buf } _ => false, } } } /// Convert value to [`SmolStr`] using [`fmt::Display`], potentially without allocating. /// /// Almost identical to [`ToString`], but converts to `SmolStr` instead. pub trait ToSmolStr { fn to_smolstr(&self) -> SmolStr; } /// [`str`] methods producing [`SmolStr`]s. pub trait StrExt: private::Sealed { /// Returns the lowercase equivalent of this string slice as a new [`SmolStr`], /// potentially without allocating. /// /// See [`str::to_lowercase`]. #[must_use = "this returns a new SmolStr without modifying the original"] fn to_lowercase_smolstr(&self) -> SmolStr; /// Returns the uppercase equivalent of this string slice as a new [`SmolStr`], /// potentially without allocating. /// /// See [`str::to_uppercase`]. #[must_use = "this returns a new SmolStr without modifying the original"] fn to_uppercase_smolstr(&self) -> SmolStr; /// Returns the ASCII lowercase equivalent of this string slice as a new [`SmolStr`], /// potentially without allocating. /// /// See [`str::to_ascii_lowercase`]. #[must_use = "this returns a new SmolStr without modifying the original"] fn to_ascii_lowercase_smolstr(&self) -> SmolStr; /// Returns the ASCII uppercase equivalent of this string slice as a new [`SmolStr`], /// potentially without allocating. /// /// See [`str::to_ascii_uppercase`]. #[must_use = "this returns a new SmolStr without modifying the original"] fn to_ascii_uppercase_smolstr(&self) -> SmolStr; /// Replaces all matches of a &str with another &str returning a new [`SmolStr`], /// potentially without allocating. /// /// See [`str::replace`]. #[must_use = "this returns a new SmolStr without modifying the original"] fn replace_smolstr(&self, from: &str, to: &str) -> SmolStr; /// Replaces first N matches of a &str with another &str returning a new [`SmolStr`], /// potentially without allocating. /// /// See [`str::replacen`]. #[must_use = "this returns a new SmolStr without modifying the original"] fn replacen_smolstr(&self, from: &str, to: &str, count: usize) -> SmolStr; } impl StrExt for str { #[inline] fn to_lowercase_smolstr(&self) -> SmolStr { let len = self.len(); if len <= INLINE_CAP { let (buf, rest) = inline_convert_while_ascii(self, u8::to_ascii_lowercase); from_buf_and_chars(buf, len - rest.len(), rest.chars().flat_map(|c| c.to_lowercase())) } else { self.to_lowercase().into() } } #[inline] fn to_uppercase_smolstr(&self) -> SmolStr { let len = self.len(); if len <= INLINE_CAP { let (buf, rest) = inline_convert_while_ascii(self, u8::to_ascii_uppercase); from_buf_and_chars(buf, len - rest.len(), rest.chars().flat_map(|c| c.to_uppercase())) } else { self.to_uppercase().into() } } #[inline] fn to_ascii_lowercase_smolstr(&self) -> SmolStr { let len = self.len(); if len <= INLINE_CAP { let mut buf = [0u8; INLINE_CAP]; buf[..len].copy_from_slice(self.as_bytes()); buf[..len].make_ascii_lowercase(); SmolStr(Repr::Inline { // SAFETY: `len` is in bounds len: unsafe { InlineSize::transmute_from_u8(len as u8) }, buf, }) } else { self.to_ascii_lowercase().into() } } #[inline] fn to_ascii_uppercase_smolstr(&self) -> SmolStr { let len = self.len(); if len <= INLINE_CAP { let mut buf = [0u8; INLINE_CAP]; buf[..len].copy_from_slice(self.as_bytes()); buf[..len].make_ascii_uppercase(); SmolStr(Repr::Inline { // SAFETY: `len` is in bounds len: unsafe { InlineSize::transmute_from_u8(len as u8) }, buf, }) } else { self.to_ascii_uppercase().into() } } #[inline] fn replace_smolstr(&self, from: &str, to: &str) -> SmolStr { self.replacen_smolstr(from, to, usize::MAX) } #[inline] fn replacen_smolstr(&self, from: &str, to: &str, mut count: usize) -> SmolStr { // Fast path for replacing a single ASCII character with another inline. if let [from_u8] = from.as_bytes() && let [to_u8] = to.as_bytes() { return if self.len() <= count { // SAFETY: `from_u8` & `to_u8` are ascii unsafe { replacen_1_ascii(self, |b| if b == from_u8 { *to_u8 } else { *b }) } } else { unsafe { replacen_1_ascii(self, |b| { if b == from_u8 && count != 0 { count -= 1; *to_u8 } else { *b } }) } }; } let mut result = SmolStrBuilder::new(); let mut last_end = 0; for (start, part) in self.match_indices(from).take(count) { // SAFETY: `start` is guaranteed to be within the bounds of `self` as per // `match_indices` and last_end is always less than or equal to `start` result.push_str(unsafe { self.get_unchecked(last_end..start) }); result.push_str(to); last_end = start + part.len(); } // SAFETY: `self.len()` is guaranteed to be within the bounds of `self` and last_end is // always less than or equal to `self.len()` result.push_str(unsafe { self.get_unchecked(last_end..self.len()) }); SmolStr::from(result) } } /// SAFETY: `map` fn must only replace ascii with ascii or return unchanged bytes. #[inline] unsafe fn replacen_1_ascii(src: &str, mut map: impl FnMut(&u8) -> u8) -> SmolStr { if src.len() <= INLINE_CAP { let mut buf = [0u8; INLINE_CAP]; for (idx, b) in src.as_bytes().iter().enumerate() { buf[idx] = map(b); } SmolStr(Repr::Inline { // SAFETY: `len` is in bounds len: unsafe { InlineSize::transmute_from_u8(src.len() as u8) }, buf, }) } else { let out = src.as_bytes().iter().map(map).collect(); // SAFETY: We replaced ascii with ascii on valid utf8 strings. unsafe { String::from_utf8_unchecked(out).into() } } } /// Inline version of std fn `convert_while_ascii`. `s` must have len <= 23. #[inline] fn inline_convert_while_ascii(s: &str, convert: fn(&u8) -> u8) -> ([u8; INLINE_CAP], &str) { // Process the input in chunks of 16 bytes to enable auto-vectorization. // Previously the chunk size depended on the size of `usize`, // but on 32-bit platforms with sse or neon is also the better choice. // The only downside on other platforms would be a bit more loop-unrolling. const N: usize = 16; debug_assert!(s.len() <= INLINE_CAP, "only for inline-able strings"); let mut slice = s.as_bytes(); let mut out = [0u8; INLINE_CAP]; let mut out_slice = &mut out[..slice.len()]; let mut is_ascii = [false; N]; while slice.len() >= N { // SAFETY: checked in loop condition let chunk = unsafe { slice.get_unchecked(..N) }; // SAFETY: out_slice has at least same length as input slice and gets sliced with the same offsets let out_chunk = unsafe { out_slice.get_unchecked_mut(..N) }; for j in 0..N { is_ascii[j] = chunk[j] <= 127; } // Auto-vectorization for this check is a bit fragile, sum and comparing against the chunk // size gives the best result, specifically a pmovmsk instruction on x86. // See https://github.com/llvm/llvm-project/issues/96395 for why llvm currently does not // currently recognize other similar idioms. if is_ascii.iter().map(|x| *x as u8).sum::() as usize != N { break; } for j in 0..N { out_chunk[j] = convert(&chunk[j]); } slice = unsafe { slice.get_unchecked(N..) }; out_slice = unsafe { out_slice.get_unchecked_mut(N..) }; } // handle the remainder as individual bytes while !slice.is_empty() { let byte = slice[0]; if byte > 127 { break; } // SAFETY: out_slice has at least same length as input slice unsafe { *out_slice.get_unchecked_mut(0) = convert(&byte); } slice = unsafe { slice.get_unchecked(1..) }; out_slice = unsafe { out_slice.get_unchecked_mut(1..) }; } unsafe { // SAFETY: we know this is a valid char boundary // since we only skipped over leading ascii bytes let rest = core::str::from_utf8_unchecked(slice); (out, rest) } } impl ToSmolStr for T where T: fmt::Display + ?Sized, { fn to_smolstr(&self) -> SmolStr { format_smolstr!("{}", self) } } mod private { /// No downstream impls allowed. pub trait Sealed {} impl Sealed for str {} } /// Formats arguments to a [`SmolStr`], potentially without allocating. /// /// See [`alloc::format!`] or [`format_args!`] for syntax documentation. #[macro_export] macro_rules! format_smolstr { ($($tt:tt)*) => {{ let mut w = $crate::SmolStrBuilder::new(); ::core::fmt::Write::write_fmt(&mut w, format_args!($($tt)*)).expect("a formatting trait implementation returned an error"); w.finish() }}; } /// A builder that can be used to efficiently build a [`SmolStr`]. /// /// This won't allocate if the final string fits into the inline buffer. #[derive(Clone, Default, Debug, PartialEq, Eq)] pub struct SmolStrBuilder(SmolStrBuilderRepr); #[derive(Clone, Debug, PartialEq, Eq)] enum SmolStrBuilderRepr { Inline { len: usize, buf: [u8; INLINE_CAP] }, Heap(String), } impl Default for SmolStrBuilderRepr { #[inline] fn default() -> Self { SmolStrBuilderRepr::Inline { buf: [0; INLINE_CAP], len: 0 } } } impl SmolStrBuilder { /// Creates a new empty [`SmolStrBuilder`]. #[must_use] pub const fn new() -> Self { Self(SmolStrBuilderRepr::Inline { buf: [0; INLINE_CAP], len: 0 }) } /// Builds a [`SmolStr`] from `self`. #[must_use] pub fn finish(&self) -> SmolStr { SmolStr(match &self.0 { &SmolStrBuilderRepr::Inline { len, buf } => { debug_assert!(len <= INLINE_CAP); Repr::Inline { // SAFETY: We know that `value.len` is less than or equal to the maximum value of `InlineSize` len: unsafe { InlineSize::transmute_from_u8(len as u8) }, buf, } } SmolStrBuilderRepr::Heap(heap) => Repr::new(heap), }) } /// Appends the given [`char`] to the end of `self`'s buffer. pub fn push(&mut self, c: char) { match &mut self.0 { SmolStrBuilderRepr::Inline { len, buf } => { let char_len = c.len_utf8(); let new_len = *len + char_len; if new_len <= INLINE_CAP { c.encode_utf8(&mut buf[*len..]); *len += char_len; } else { let mut heap = String::with_capacity(new_len); // copy existing inline bytes over to the heap // SAFETY: inline data is guaranteed to be valid utf8 for `old_len` bytes unsafe { heap.as_mut_vec().extend_from_slice(&buf[..*len]) }; heap.push(c); self.0 = SmolStrBuilderRepr::Heap(heap); } } SmolStrBuilderRepr::Heap(h) => h.push(c), } } /// Appends a given string slice onto the end of `self`'s buffer. pub fn push_str(&mut self, s: &str) { match &mut self.0 { SmolStrBuilderRepr::Inline { len, buf } => { let old_len = *len; *len += s.len(); // if the new length will fit on the stack (even if it fills it entirely) if *len <= INLINE_CAP { buf[old_len..*len].copy_from_slice(s.as_bytes()); return; // skip the heap push below } let mut heap = String::with_capacity(*len); // copy existing inline bytes over to the heap // SAFETY: inline data is guaranteed to be valid utf8 for `old_len` bytes unsafe { heap.as_mut_vec().extend_from_slice(&buf[..old_len]) }; heap.push_str(s); self.0 = SmolStrBuilderRepr::Heap(heap); } SmolStrBuilderRepr::Heap(heap) => heap.push_str(s), } } } impl fmt::Write for SmolStrBuilder { #[inline] fn write_str(&mut self, s: &str) -> fmt::Result { self.push_str(s); Ok(()) } } impl From for SmolStr { fn from(value: SmolStrBuilder) -> Self { value.finish() } } #[cfg(feature = "arbitrary")] #[cfg_attr(docsrs, doc(cfg(feature = "arbitrary")))] impl<'a> arbitrary::Arbitrary<'a> for SmolStr { fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> Result { let s = <&str>::arbitrary(u)?; Ok(SmolStr::new(s)) } } #[cfg(feature = "borsh")] #[cfg_attr(docsrs, doc(cfg(feature = "borsh")))] mod borsh; #[cfg(feature = "serde")] #[cfg_attr(docsrs, doc(cfg(feature = "serde")))] mod serde; #[test] fn from_buf_and_chars_size_hinted_heap() { let str = from_buf_and_chars( *b"abcdefghijklmnopqr00000", 18, "_0x1x2x3x4x5x6x7x8x9x10x11x12x13".chars(), ); assert_eq!(str, "abcdefghijklmnopqr_0x1x2x3x4x5x6x7x8x9x10x11x12x13"); } smol_str-0.3.5/src/serde.rs000064400000000000000000000047471046102023000137460ustar 00000000000000use alloc::{string::String, vec::Vec}; use core::fmt; use serde::de::{Deserializer, Error, Unexpected, Visitor}; use serde_core as serde; use crate::SmolStr; // https://github.com/serde-rs/serde/blob/629802f2abfd1a54a6072992888fea7ca5bc209f/serde/src/private/de.rs#L56-L125 fn smol_str<'de: 'a, 'a, D>(deserializer: D) -> Result where D: Deserializer<'de>, { struct SmolStrVisitor; impl<'a> Visitor<'a> for SmolStrVisitor { type Value = SmolStr; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("a string") } fn visit_str(self, v: &str) -> Result where E: Error, { Ok(SmolStr::from(v)) } fn visit_borrowed_str(self, v: &'a str) -> Result where E: Error, { Ok(SmolStr::from(v)) } fn visit_string(self, v: String) -> Result where E: Error, { Ok(SmolStr::from(v)) } fn visit_bytes(self, v: &[u8]) -> Result where E: Error, { match core::str::from_utf8(v) { Ok(s) => Ok(SmolStr::from(s)), Err(_) => Err(Error::invalid_value(Unexpected::Bytes(v), &self)), } } fn visit_borrowed_bytes(self, v: &'a [u8]) -> Result where E: Error, { match core::str::from_utf8(v) { Ok(s) => Ok(SmolStr::from(s)), Err(_) => Err(Error::invalid_value(Unexpected::Bytes(v), &self)), } } fn visit_byte_buf(self, v: Vec) -> Result where E: Error, { match String::from_utf8(v) { Ok(s) => Ok(SmolStr::from(s)), Err(e) => Err(Error::invalid_value(Unexpected::Bytes(&e.into_bytes()), &self)), } } } deserializer.deserialize_str(SmolStrVisitor) } impl serde::Serialize for SmolStr { fn serialize(&self, serializer: S) -> Result where S: serde::Serializer, { self.as_str().serialize(serializer) } } impl<'de> serde::Deserialize<'de> for SmolStr { fn deserialize(deserializer: D) -> Result where D: serde::Deserializer<'de>, { smol_str(deserializer) } } smol_str-0.3.5/tests/test.rs000064400000000000000000000326741046102023000141760ustar 00000000000000#![allow(clippy::disallowed_types)] use std::sync::Arc; #[cfg(not(miri))] use proptest::{prop_assert, prop_assert_eq, proptest}; use smol_str::{SmolStr, SmolStrBuilder}; #[test] #[cfg(target_pointer_width = "64")] fn smol_str_is_smol() { assert_eq!(::std::mem::size_of::(), ::std::mem::size_of::(),); } #[test] fn assert_traits() { fn f() {} f::(); } #[test] fn conversions() { let s: SmolStr = "Hello, World!".into(); let s: String = s.into(); assert_eq!(s, "Hello, World!"); let s: SmolStr = Arc::::from("Hello, World!").into(); let s: Arc = s.into(); assert_eq!(s.as_ref(), "Hello, World!"); } #[test] fn const_fn_ctor() { const EMPTY: SmolStr = SmolStr::new_inline(""); const A: SmolStr = SmolStr::new_inline("A"); const HELLO: SmolStr = SmolStr::new_inline("HELLO"); const LONG: SmolStr = SmolStr::new_inline("ABCDEFGHIZKLMNOPQRSTUVW"); assert_eq!(EMPTY, SmolStr::from("")); assert_eq!(A, SmolStr::from("A")); assert_eq!(HELLO, SmolStr::from("HELLO")); assert_eq!(LONG, SmolStr::from("ABCDEFGHIZKLMNOPQRSTUVW")); } #[cfg(not(miri))] fn check_props(std_str: &str, smol: SmolStr) -> Result<(), proptest::test_runner::TestCaseError> { prop_assert_eq!(smol.as_str(), std_str); prop_assert_eq!(smol.len(), std_str.len()); prop_assert_eq!(smol.is_empty(), std_str.is_empty()); if smol.len() <= 23 { prop_assert!(!smol.is_heap_allocated()); } Ok(()) } #[cfg(not(miri))] proptest! { #[test] fn roundtrip(s: String) { check_props(s.as_str(), SmolStr::new(s.clone()))?; } #[test] fn roundtrip_spaces(s in r"( )*") { check_props(s.as_str(), SmolStr::new(s.clone()))?; } #[test] fn roundtrip_newlines(s in r"\n*") { check_props(s.as_str(), SmolStr::new(s.clone()))?; } #[test] fn roundtrip_ws(s in r"( |\n)*") { check_props(s.as_str(), SmolStr::new(s.clone()))?; } #[test] fn from_string_iter(slices in proptest::collection::vec(".*", 1..100)) { let string: String = slices.iter().map(|x| x.as_str()).collect(); let smol: SmolStr = slices.into_iter().collect(); check_props(string.as_str(), smol)?; } #[test] fn from_str_iter(slices in proptest::collection::vec(".*", 1..100)) { let string: String = slices.iter().map(|x| x.as_str()).collect(); let smol: SmolStr = slices.iter().collect(); check_props(string.as_str(), smol)?; } } #[cfg(feature = "serde")] mod serde_tests { use super::*; use serde::{Deserialize, Serialize}; use std::collections::HashMap; #[derive(Serialize, Deserialize)] struct SmolStrStruct { pub(crate) s: SmolStr, pub(crate) vec: Vec, pub(crate) map: HashMap, } #[test] fn test_serde() { let s = SmolStr::new("Hello, World"); let s = serde_json::to_string(&s).unwrap(); assert_eq!(s, "\"Hello, World\""); let s: SmolStr = serde_json::from_str(&s).unwrap(); assert_eq!(s, "Hello, World"); } #[test] fn test_serde_reader() { let s = SmolStr::new("Hello, World"); let s = serde_json::to_string(&s).unwrap(); assert_eq!(s, "\"Hello, World\""); let s: SmolStr = serde_json::from_reader(std::io::Cursor::new(s)).unwrap(); assert_eq!(s, "Hello, World"); } #[test] fn test_serde_struct() { let mut map = HashMap::new(); map.insert(SmolStr::new("a"), SmolStr::new("ohno")); let struct_ = SmolStrStruct { s: SmolStr::new("Hello, World"), vec: vec![SmolStr::new("Hello, World"), SmolStr::new("Hello, World")], map, }; let s = serde_json::to_string(&struct_).unwrap(); let _new_struct: SmolStrStruct = serde_json::from_str(&s).unwrap(); } #[test] fn test_serde_struct_reader() { let mut map = HashMap::new(); map.insert(SmolStr::new("a"), SmolStr::new("ohno")); let struct_ = SmolStrStruct { s: SmolStr::new("Hello, World"), vec: vec![SmolStr::new("Hello, World"), SmolStr::new("Hello, World")], map, }; let s = serde_json::to_string(&struct_).unwrap(); let _new_struct: SmolStrStruct = serde_json::from_reader(std::io::Cursor::new(s)).unwrap(); } #[test] fn test_serde_hashmap() { let mut map = HashMap::new(); map.insert(SmolStr::new("a"), SmolStr::new("ohno")); let s = serde_json::to_string(&map).unwrap(); let _s: HashMap = serde_json::from_str(&s).unwrap(); } #[test] fn test_serde_hashmap_reader() { let mut map = HashMap::new(); map.insert(SmolStr::new("a"), SmolStr::new("ohno")); let s = serde_json::to_string(&map).unwrap(); let _s: HashMap = serde_json::from_reader(std::io::Cursor::new(s)).unwrap(); } #[test] fn test_serde_vec() { let vec = vec![SmolStr::new(""), SmolStr::new("b")]; let s = serde_json::to_string(&vec).unwrap(); let _s: Vec = serde_json::from_str(&s).unwrap(); } #[test] fn test_serde_vec_reader() { let vec = vec![SmolStr::new(""), SmolStr::new("b")]; let s = serde_json::to_string(&vec).unwrap(); let _s: Vec = serde_json::from_reader(std::io::Cursor::new(s)).unwrap(); } } #[test] fn test_search_in_hashmap() { let mut m = ::std::collections::HashMap::::new(); m.insert("aaa".into(), 17); assert_eq!(17, *m.get("aaa").unwrap()); } #[test] fn test_from_char_iterator() { let examples = [ // Simple keyword-like strings ("if", false), ("for", false), ("impl", false), // Strings containing two-byte characters ("パーティーへ行かないか", true), ("パーティーへ行か", true), ("パーティーへ行_", false), ("和製漢語", false), ("部落格", false), ("사회과학원 어학연구소", true), // String containing diverse characters ("表ポあA鷗ŒéB逍Üߪąñ丂㐀𠀀", true), ]; for (raw, is_heap) in &examples { let s: SmolStr = raw.chars().collect(); assert_eq!(s.as_str(), *raw); assert_eq!(s.is_heap_allocated(), *is_heap); } // String which has too many characters to even consider inlining: Chars::size_hint uses // (`len` + 3) / 4. With `len` = 89, this results in 23, so `from_iter` will immediately // heap allocate let raw = "a".repeat(23 * 4 + 1); let s: SmolStr = raw.chars().collect(); assert_eq!(s.as_str(), raw); assert!(s.is_heap_allocated()); } #[test] fn test_bad_size_hint_char_iter() { struct BadSizeHint(I); impl> Iterator for BadSizeHint { type Item = T; fn next(&mut self) -> Option { self.0.next() } fn size_hint(&self) -> (usize, Option) { (1024, None) } } let data = "testing"; let collected: SmolStr = BadSizeHint(data.chars()).collect(); let new = SmolStr::new(data); assert!(!collected.is_heap_allocated()); assert!(!new.is_heap_allocated()); assert_eq!(new, collected); } #[test] fn test_to_smolstr() { use smol_str::ToSmolStr; for i in 0..26 { let a = &"abcdefghijklmnopqrstuvwxyz"[i..]; assert_eq!(a, a.to_smolstr()); assert_eq!(a, smol_str::format_smolstr!("{}", a)); } } #[test] fn test_builder_push_str() { //empty let builder = SmolStrBuilder::new(); assert_eq!("", builder.finish()); // inline push let mut builder = SmolStrBuilder::new(); builder.push_str("a"); builder.push_str("b"); let s = builder.finish(); assert!(!s.is_heap_allocated()); assert_eq!("ab", s); // inline max push let mut builder = SmolStrBuilder::new(); builder.push_str(&"a".repeat(23)); let s = builder.finish(); assert!(!s.is_heap_allocated()); assert_eq!("a".repeat(23), s); // heap push immediate let mut builder = SmolStrBuilder::new(); builder.push_str(&"a".repeat(24)); let s = builder.finish(); assert!(s.is_heap_allocated()); assert_eq!("a".repeat(24), s); // heap push succession let mut builder = SmolStrBuilder::new(); builder.push_str(&"a".repeat(23)); builder.push_str(&"a".repeat(23)); let s = builder.finish(); assert!(s.is_heap_allocated()); assert_eq!("a".repeat(46), s); // heap push on multibyte char let mut builder = SmolStrBuilder::new(); builder.push_str("ohnonononononononono!"); builder.push('🤯'); let s = builder.finish(); assert!(s.is_heap_allocated()); assert_eq!("ohnonononononononono!🤯", s); } #[test] fn test_builder_push() { //empty let builder = SmolStrBuilder::new(); assert_eq!("", builder.finish()); // inline push let mut builder = SmolStrBuilder::new(); builder.push('a'); builder.push('b'); let s = builder.finish(); assert!(!s.is_heap_allocated()); assert_eq!("ab", s); // inline max push let mut builder = SmolStrBuilder::new(); for _ in 0..23 { builder.push('a'); } let s = builder.finish(); assert!(!s.is_heap_allocated()); assert_eq!("a".repeat(23), s); // heap push let mut builder = SmolStrBuilder::new(); for _ in 0..24 { builder.push('a'); } let s = builder.finish(); assert!(s.is_heap_allocated()); assert_eq!("a".repeat(24), s); } #[cfg(test)] mod test_str_ext { use smol_str::StrExt; #[test] fn large() { let lowercase = "aaaaaaAAAAAaaaaaaaaaaaaaaaaaaaaaAAAAaaaaaaaaaaaaaa".to_lowercase_smolstr(); assert_eq!(lowercase, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); assert!(lowercase.is_heap_allocated()); } #[test] fn to_lowercase() { let lowercase = "aßΔC".to_lowercase_smolstr(); assert_eq!(lowercase, "aßδc"); assert!(!lowercase.is_heap_allocated()); } #[test] fn to_uppercase() { let uppercase = "aßΔC".to_uppercase_smolstr(); assert_eq!(uppercase, "ASSΔC"); assert!(!uppercase.is_heap_allocated()); } #[test] fn to_ascii_lowercase() { let uppercase = "aßΔC".to_ascii_lowercase_smolstr(); assert_eq!(uppercase, "aßΔc"); assert!(!uppercase.is_heap_allocated()); } #[test] fn to_ascii_uppercase() { let uppercase = "aßΔC".to_ascii_uppercase_smolstr(); assert_eq!(uppercase, "AßΔC"); assert!(!uppercase.is_heap_allocated()); } #[test] fn replace() { let result = "foo_bar_baz".replace_smolstr("ba", "do"); assert_eq!(result, "foo_dor_doz"); assert!(!result.is_heap_allocated()); } #[test] fn replacen() { let result = "foo_bar_baz".replacen_smolstr("ba", "do", 1); assert_eq!(result, "foo_dor_baz"); assert!(!result.is_heap_allocated()); } #[test] fn replacen_1_ascii() { let result = "foo_bar_baz".replacen_smolstr("o", "u", 1); assert_eq!(result, "fuo_bar_baz"); assert!(!result.is_heap_allocated()); } } #[cfg(feature = "borsh")] mod borsh_tests { use borsh::BorshDeserialize; use smol_str::{SmolStr, ToSmolStr}; use std::io::Cursor; #[test] fn borsh_serialize_stack() { let smolstr_on_stack = "aßΔCaßδc".to_smolstr(); let mut buffer = Vec::new(); borsh::BorshSerialize::serialize(&smolstr_on_stack, &mut buffer).unwrap(); let mut cursor = Cursor::new(buffer); let decoded: SmolStr = borsh::BorshDeserialize::deserialize_reader(&mut cursor).unwrap(); assert_eq!(smolstr_on_stack, decoded); } #[test] fn borsh_serialize_heap() { let smolstr_on_heap = "aßΔCaßδcaßΔCaßδcaßΔCaßδcaßΔCaßδcaßΔCaßδcaßΔCaßδcaßΔCaßδcaßΔCaßδcaßΔCaßδcaßΔCaßδcaßΔCaßδc".to_smolstr(); let mut buffer = Vec::new(); borsh::BorshSerialize::serialize(&smolstr_on_heap, &mut buffer).unwrap(); let mut cursor = Cursor::new(buffer); let decoded: SmolStr = borsh::BorshDeserialize::deserialize_reader(&mut cursor).unwrap(); assert_eq!(smolstr_on_heap, decoded); } #[test] fn borsh_non_utf8_stack() { let invalid_utf8: Vec = vec![0xF0, 0x9F, 0x8F]; // Incomplete UTF-8 sequence let wrong_utf8 = SmolStr::from(unsafe { String::from_utf8_unchecked(invalid_utf8) }); let mut buffer = Vec::new(); borsh::BorshSerialize::serialize(&wrong_utf8, &mut buffer).unwrap(); let mut cursor = Cursor::new(buffer); let result = SmolStr::deserialize_reader(&mut cursor); assert!(result.is_err()); } #[test] fn borsh_non_utf8_heap() { let invalid_utf8: Vec = vec![ 0xC1, 0x8A, 0x5F, 0xE2, 0x3A, 0x9E, 0x3B, 0xAA, 0x01, 0x08, 0x6F, 0x2F, 0xC0, 0x32, 0xAB, 0xE1, 0x9A, 0x2F, 0x4A, 0x3F, 0x25, 0x0D, 0x8A, 0x2A, 0x19, 0x11, 0xF0, 0x7F, 0x0E, 0x80, ]; let wrong_utf8 = SmolStr::from(unsafe { String::from_utf8_unchecked(invalid_utf8) }); let mut buffer = Vec::new(); borsh::BorshSerialize::serialize(&wrong_utf8, &mut buffer).unwrap(); let mut cursor = Cursor::new(buffer); let result = SmolStr::deserialize_reader(&mut cursor); assert!(result.is_err()); } } smol_str-0.3.5/tests/tidy.rs000064400000000000000000000025411046102023000141560ustar 00000000000000#![allow(clippy::disallowed_methods, clippy::print_stdout)] #![cfg(not(miri))] use std::{ env, path::{Path, PathBuf}, process::{Command, Stdio}, }; fn project_root() -> PathBuf { PathBuf::from( env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| env!("CARGO_MANIFEST_DIR").to_owned()), ) } fn run(cmd: &str, dir: impl AsRef) -> Result<(), ()> { let mut args: Vec<_> = cmd.split_whitespace().collect(); let bin = args.remove(0); println!("> {}", cmd); let output = Command::new(bin) .args(args) .current_dir(dir) .stdin(Stdio::null()) .stdout(Stdio::piped()) .stderr(Stdio::inherit()) .output() .map_err(drop)?; if output.status.success() { Ok(()) } else { let stdout = String::from_utf8(output.stdout).map_err(drop)?; print!("{}", stdout); Err(()) } } #[test] fn check_code_formatting() { let dir = project_root(); if run("rustfmt +stable --version", &dir).is_err() { panic!( "failed to run rustfmt from toolchain 'stable'; \ please run `rustup component add rustfmt --toolchain stable` to install it.", ); } if run("cargo +stable fmt -- --check", &dir).is_err() { panic!("code is not properly formatted; please format the code by running `cargo fmt`") } }