├── .editorconfig ├── .github └── workflows │ └── rust.yml ├── .gitignore ├── CHANGELOG.md ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── no_step_on_snek.png └── src ├── kebab.rs ├── lib.rs ├── lower_camel.rs ├── shouty_kebab.rs ├── shouty_snake.rs ├── snake.rs ├── title.rs ├── train.rs └── upper_camel.rs /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | charset = utf-8 5 | 6 | end_of_line = lf 7 | insert_final_newline = true 8 | trim_trailing_whitespace = true 9 | 10 | indent_style = space 11 | indent_size = 4 12 | 13 | [*.md] 14 | trim_trailing_whitespace = true 15 | 16 | [*.yml] 17 | indent_size = 2 18 | -------------------------------------------------------------------------------- /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | name: Rust 2 | 3 | on: 4 | push: 5 | branches: [master] 6 | pull_request: 7 | branches: [master] 8 | 9 | jobs: 10 | build: 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | - uses: actions/checkout@v2 15 | # Use MSRV for the build job 16 | - uses: actions-rs/toolchain@v1 17 | with: 18 | toolchain: 1.56 19 | default: true 20 | profile: minimal 21 | - name: Build 22 | uses: actions-rs/cargo@v1 23 | with: 24 | command: build 25 | # Use stable for other jobs 26 | - uses: actions-rs/toolchain@v1 27 | with: 28 | toolchain: stable 29 | default: true 30 | profile: minimal 31 | components: rustfmt, clippy 32 | - name: Run tests 33 | uses: actions-rs/cargo@v1 34 | with: 35 | command: test 36 | - name: Check formatting 37 | uses: actions-rs/cargo@v1 38 | with: 39 | command: fmt 40 | args: -- --check 41 | - name: Catch common mistakes 42 | uses: actions-rs/cargo@v1 43 | with: 44 | command: clippy 45 | args: --all-targets -- -D warnings 46 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # unreleased 2 | 3 | # 0.5.0 4 | 5 | - Add `no_std` support. 6 | - Remove non-additive `unicode` feature. The library now uses `char::is_alphanumeric` 7 | instead of the `unicode-segmentation` library to determine word boundaries in all cases. 8 | 9 | # 0.4.1 10 | 11 | Improvements: 12 | 13 | - Add Train-Case support 14 | 15 | # 0.4.0 16 | 17 | Breaking changes: 18 | 19 | * Make unicode support optional (off by default). Enable the `unicode` crate 20 | feature if you need unicode support. 21 | * Rename all traits from `SomeCase` to `ToSomeCase`, matching `std`s convention 22 | of beginning trait names with a verb (`ToOwned`, `AsRef`, …) 23 | * Rename `ToMixedCase` to `ToLowerCamelCase` 24 | * Rename `ToCamelCase` to `ToUpperCamelCase` 25 | * Add `ToPascalCase` as an alias to `ToUpperCamelCase` 26 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "heck" 3 | version = "0.5.0" 4 | edition = "2021" 5 | rust-version = "1.56" 6 | license = "MIT OR Apache-2.0" 7 | description = "heck is a case conversion library." 8 | repository = "https://github.com/withoutboats/heck" 9 | keywords = ["string", "case", "camel", "snake", "unicode"] 10 | categories = ["no-std"] 11 | include = ["src/**/*", "LICENSE-*", "README.md", "CHANGELOG.md"] 12 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2015 The Rust Project Developers 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # **heck** is a case conversion library 2 | 3 | !["I specifically requested the opposite of this."](./no_step_on_snek.png) 4 | 5 | This library exists to provide case conversion between common cases like 6 | CamelCase and snake_case. It is intended to be unicode aware, internally 7 | consistent, and reasonably well performing. 8 | 9 | ## Definition of a word boundary 10 | 11 | Word boundaries are defined by non-alphanumeric characters, as well as 12 | within those words in this manner: 13 | 14 | 1. If an uppercase character is followed by lowercase letters, a word 15 | boundary is considered to be just prior to that uppercase character. 16 | 2. If multiple uppercase characters are consecutive, they are considered to 17 | be within a single word, except that the last will be part of the next word 18 | if it is followed by lowercase characters (see rule 1). 19 | 20 | That is, "HelloWorld" is segmented `Hello|World` whereas "XMLHttpRequest" is 21 | segmented `XML|Http|Request`. 22 | 23 | Characters not within words (such as spaces, punctuations, and underscores) 24 | are not included in the output string except as they are a part of the case 25 | being converted to. Multiple adjacent word boundaries (such as a series of 26 | underscores) are folded into one. ("hello__world" in snake case is therefore 27 | "hello_world", not the exact same string). Leading or trailing word boundary 28 | indicators are dropped, except insofar as CamelCase capitalizes the first word. 29 | 30 | ## Cases contained in this library: 31 | 32 | 1. UpperCamelCase 33 | 2. lowerCamelCase 34 | 3. snake_case 35 | 4. kebab-case 36 | 5. SHOUTY_SNAKE_CASE 37 | 6. Title Case 38 | 7. SHOUTY-KEBAB-CASE 39 | 8. Train-Case 40 | 41 | ## MSRV 42 | 43 | The minimum supported Rust version for this crate is 1.56.0. This may change in 44 | minor or patch releases, but we probably won't ever require a very recent 45 | version. If you would like to have a stronger guarantee than that, please open 46 | an issue. 47 | 48 | ## License 49 | 50 | heck is distributed under the terms of both the MIT license and the 51 | Apache License (Version 2.0). 52 | 53 | See LICENSE-APACHE and LICENSE-MIT for details. 54 | -------------------------------------------------------------------------------- /no_step_on_snek.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/withoutboats/heck/070693322aee7c5c7fbee7c9964bf8d7d3a29c96/no_step_on_snek.png -------------------------------------------------------------------------------- /src/kebab.rs: -------------------------------------------------------------------------------- 1 | use core::fmt; 2 | 3 | use alloc::{borrow::ToOwned, string::ToString}; 4 | 5 | use crate::{lowercase, transform}; 6 | 7 | /// This trait defines a kebab case conversion. 8 | /// 9 | /// In kebab-case, word boundaries are indicated by hyphens. 10 | /// 11 | /// ## Example: 12 | /// 13 | /// ```rust 14 | /// use heck::ToKebabCase; 15 | /// 16 | /// let sentence = "We are going to inherit the earth."; 17 | /// assert_eq!(sentence.to_kebab_case(), "we-are-going-to-inherit-the-earth"); 18 | /// ``` 19 | pub trait ToKebabCase: ToOwned { 20 | /// Convert this type to kebab case. 21 | fn to_kebab_case(&self) -> Self::Owned; 22 | } 23 | 24 | impl ToKebabCase for str { 25 | fn to_kebab_case(&self) -> Self::Owned { 26 | AsKebabCase(self).to_string() 27 | } 28 | } 29 | 30 | /// This wrapper performs a kebab case conversion in [`fmt::Display`]. 31 | /// 32 | /// ## Example: 33 | /// 34 | /// ``` 35 | /// use heck::AsKebabCase; 36 | /// 37 | /// let sentence = "We are going to inherit the earth."; 38 | /// assert_eq!(format!("{}", AsKebabCase(sentence)), "we-are-going-to-inherit-the-earth"); 39 | /// ``` 40 | pub struct AsKebabCase>(pub T); 41 | 42 | impl> fmt::Display for AsKebabCase { 43 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 44 | transform(self.0.as_ref(), lowercase, |f| write!(f, "-"), f) 45 | } 46 | } 47 | 48 | #[cfg(test)] 49 | mod tests { 50 | use super::ToKebabCase; 51 | 52 | macro_rules! t { 53 | ($t:ident : $s1:expr => $s2:expr) => { 54 | #[test] 55 | fn $t() { 56 | assert_eq!($s1.to_kebab_case(), $s2) 57 | } 58 | }; 59 | } 60 | 61 | t!(test1: "CamelCase" => "camel-case"); 62 | t!(test2: "This is Human case." => "this-is-human-case"); 63 | t!(test3: "MixedUP CamelCase, with some Spaces" => "mixed-up-camel-case-with-some-spaces"); 64 | t!(test4: "mixed_up_ snake_case with some _spaces" => "mixed-up-snake-case-with-some-spaces"); 65 | t!(test5: "kebab-case" => "kebab-case"); 66 | t!(test6: "SHOUTY_SNAKE_CASE" => "shouty-snake-case"); 67 | t!(test7: "snake_case" => "snake-case"); 68 | t!(test8: "this-contains_ ALLKinds OfWord_Boundaries" => "this-contains-all-kinds-of-word-boundaries"); 69 | t!(test9: "XΣXΣ baffle" => "xσxς-baffle"); 70 | t!(test10: "XMLHttpRequest" => "xml-http-request"); 71 | t!(test11: "لِنَذْهَبْ إِلَى السِّيْنَمَا" => "لِنَذْهَبْ-إِلَى-السِّيْنَمَا"); 72 | // Japanese and Chinese do not have word separation. 73 | t!(test12: "ファイルを読み込み" => "ファイルを読み込み"); 74 | t!(test13: "祝你一天过得愉快" => "祝你一天过得愉快"); 75 | } 76 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! **heck** is a case conversion library. 2 | //! 3 | //! This library exists to provide case conversion between common cases like 4 | //! CamelCase and snake_case. It is intended to be unicode aware, internally 5 | //! consistent, and reasonably well performing. 6 | //! 7 | //! ## Definition of a word boundary 8 | //! 9 | //! Word boundaries are defined by non-alphanumeric characters, as well as 10 | //! within those words in this manner: 11 | //! 12 | //! 1. If an uppercase character is followed by lowercase letters, a word 13 | //! boundary is considered to be just prior to that uppercase character. 14 | //! 2. If multiple uppercase characters are consecutive, they are considered to 15 | //! be within a single word, except that the last will be part of the next word 16 | //! if it is followed by lowercase characters (see rule 1). 17 | //! 18 | //! That is, "HelloWorld" is segmented `Hello|World` whereas "XMLHttpRequest" is 19 | //! segmented `XML|Http|Request`. 20 | //! 21 | //! Characters not within words (such as spaces, punctuations, and underscores) 22 | //! are not included in the output string except as they are a part of the case 23 | //! being converted to. Multiple adjacent word boundaries (such as a series of 24 | //! underscores) are folded into one. ("hello__world" in snake case is therefore 25 | //! "hello_world", not the exact same string). Leading or trailing word boundary 26 | //! indicators are dropped, except insofar as CamelCase capitalizes the first 27 | //! word. 28 | //! 29 | //! ### Cases contained in this library: 30 | //! 31 | //! 1. UpperCamelCase 32 | //! 2. lowerCamelCase 33 | //! 3. snake_case 34 | //! 4. kebab-case 35 | //! 5. SHOUTY_SNAKE_CASE 36 | //! 6. Title Case 37 | //! 7. SHOUTY-KEBAB-CASE 38 | //! 8. Train-Case 39 | #![deny(missing_docs)] 40 | #![forbid(unsafe_code)] 41 | #![no_std] 42 | 43 | extern crate alloc; 44 | 45 | mod kebab; 46 | mod lower_camel; 47 | mod shouty_kebab; 48 | mod shouty_snake; 49 | mod snake; 50 | mod title; 51 | mod train; 52 | mod upper_camel; 53 | 54 | pub use kebab::{AsKebabCase, ToKebabCase}; 55 | pub use lower_camel::{AsLowerCamelCase, ToLowerCamelCase}; 56 | pub use shouty_kebab::{AsShoutyKebabCase, ToShoutyKebabCase}; 57 | pub use shouty_snake::{ 58 | AsShoutySnakeCase, AsShoutySnakeCase as AsShoutySnekCase, ToShoutySnakeCase, ToShoutySnekCase, 59 | }; 60 | pub use snake::{AsSnakeCase, AsSnakeCase as AsSnekCase, ToSnakeCase, ToSnekCase}; 61 | pub use title::{AsTitleCase, ToTitleCase}; 62 | pub use train::{AsTrainCase, ToTrainCase}; 63 | pub use upper_camel::{ 64 | AsUpperCamelCase, AsUpperCamelCase as AsPascalCase, ToPascalCase, ToUpperCamelCase, 65 | }; 66 | 67 | use core::fmt; 68 | 69 | fn transform( 70 | s: &str, 71 | mut with_word: F, 72 | mut boundary: G, 73 | f: &mut fmt::Formatter, 74 | ) -> fmt::Result 75 | where 76 | F: FnMut(&str, &mut fmt::Formatter) -> fmt::Result, 77 | G: FnMut(&mut fmt::Formatter) -> fmt::Result, 78 | { 79 | /// Tracks the current 'mode' of the transformation algorithm as it scans 80 | /// the input string. 81 | /// 82 | /// The mode is a tri-state which tracks the case of the last cased 83 | /// character of the current word. If there is no cased character 84 | /// (either lowercase or uppercase) since the previous word boundary, 85 | /// than the mode is `Boundary`. If the last cased character is lowercase, 86 | /// then the mode is `Lowercase`. Othertherwise, the mode is 87 | /// `Uppercase`. 88 | #[derive(Clone, Copy, PartialEq)] 89 | enum WordMode { 90 | /// There have been no lowercase or uppercase characters in the current 91 | /// word. 92 | Boundary, 93 | /// The previous cased character in the current word is lowercase. 94 | Lowercase, 95 | /// The previous cased character in the current word is uppercase. 96 | Uppercase, 97 | } 98 | 99 | let mut first_word = true; 100 | 101 | for word in s.split(|c: char| !c.is_alphanumeric()) { 102 | let mut char_indices = word.char_indices().peekable(); 103 | let mut init = 0; 104 | let mut mode = WordMode::Boundary; 105 | 106 | while let Some((i, c)) = char_indices.next() { 107 | if let Some(&(next_i, next)) = char_indices.peek() { 108 | // The mode including the current character, assuming the 109 | // current character does not result in a word boundary. 110 | let next_mode = if c.is_lowercase() { 111 | WordMode::Lowercase 112 | } else if c.is_uppercase() { 113 | WordMode::Uppercase 114 | } else { 115 | mode 116 | }; 117 | 118 | // Word boundary after if current is not uppercase and next 119 | // is uppercase 120 | if next_mode == WordMode::Lowercase && next.is_uppercase() { 121 | if !first_word { 122 | boundary(f)?; 123 | } 124 | with_word(&word[init..next_i], f)?; 125 | first_word = false; 126 | init = next_i; 127 | mode = WordMode::Boundary; 128 | 129 | // Otherwise if current and previous are uppercase and next 130 | // is lowercase, word boundary before 131 | } else if mode == WordMode::Uppercase && c.is_uppercase() && next.is_lowercase() { 132 | if !first_word { 133 | boundary(f)?; 134 | } else { 135 | first_word = false; 136 | } 137 | with_word(&word[init..i], f)?; 138 | init = i; 139 | mode = WordMode::Boundary; 140 | 141 | // Otherwise no word boundary, just update the mode 142 | } else { 143 | mode = next_mode; 144 | } 145 | } else { 146 | // Collect trailing characters as a word 147 | if !first_word { 148 | boundary(f)?; 149 | } else { 150 | first_word = false; 151 | } 152 | with_word(&word[init..], f)?; 153 | break; 154 | } 155 | } 156 | } 157 | 158 | Ok(()) 159 | } 160 | 161 | fn lowercase(s: &str, f: &mut fmt::Formatter) -> fmt::Result { 162 | let mut chars = s.chars().peekable(); 163 | while let Some(c) = chars.next() { 164 | if c == 'Σ' && chars.peek().is_none() { 165 | write!(f, "ς")?; 166 | } else { 167 | write!(f, "{}", c.to_lowercase())?; 168 | } 169 | } 170 | 171 | Ok(()) 172 | } 173 | 174 | fn uppercase(s: &str, f: &mut fmt::Formatter) -> fmt::Result { 175 | for c in s.chars() { 176 | write!(f, "{}", c.to_uppercase())?; 177 | } 178 | 179 | Ok(()) 180 | } 181 | 182 | fn capitalize(s: &str, f: &mut fmt::Formatter) -> fmt::Result { 183 | let mut char_indices = s.char_indices(); 184 | if let Some((_, c)) = char_indices.next() { 185 | write!(f, "{}", c.to_uppercase())?; 186 | if let Some((i, _)) = char_indices.next() { 187 | lowercase(&s[i..], f)?; 188 | } 189 | } 190 | 191 | Ok(()) 192 | } 193 | -------------------------------------------------------------------------------- /src/lower_camel.rs: -------------------------------------------------------------------------------- 1 | use core::fmt; 2 | 3 | use alloc::{ 4 | borrow::ToOwned, 5 | string::{String, ToString}, 6 | }; 7 | 8 | use crate::{capitalize, lowercase, transform}; 9 | 10 | /// This trait defines a lower camel case conversion. 11 | /// 12 | /// In lowerCamelCase, word boundaries are indicated by capital letters, 13 | /// excepting the first word. 14 | /// 15 | /// ## Example: 16 | /// 17 | /// ```rust 18 | /// use heck::ToLowerCamelCase; 19 | /// 20 | /// let sentence = "It is we who built these palaces and cities."; 21 | /// assert_eq!(sentence.to_lower_camel_case(), "itIsWeWhoBuiltThesePalacesAndCities"); 22 | /// ``` 23 | pub trait ToLowerCamelCase: ToOwned { 24 | /// Convert this type to lower camel case. 25 | fn to_lower_camel_case(&self) -> Self::Owned; 26 | } 27 | 28 | impl ToLowerCamelCase for str { 29 | fn to_lower_camel_case(&self) -> String { 30 | AsLowerCamelCase(self).to_string() 31 | } 32 | } 33 | 34 | /// This wrapper performs a lower camel case conversion in [`fmt::Display`]. 35 | /// 36 | /// ## Example: 37 | /// 38 | /// ``` 39 | /// use heck::AsLowerCamelCase; 40 | /// 41 | /// let sentence = "It is we who built these palaces and cities."; 42 | /// assert_eq!(format!("{}", AsLowerCamelCase(sentence)), "itIsWeWhoBuiltThesePalacesAndCities"); 43 | /// ``` 44 | pub struct AsLowerCamelCase>(pub T); 45 | 46 | impl> fmt::Display for AsLowerCamelCase { 47 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 48 | let mut first = true; 49 | transform( 50 | self.0.as_ref(), 51 | |s, f| { 52 | if first { 53 | first = false; 54 | lowercase(s, f) 55 | } else { 56 | capitalize(s, f) 57 | } 58 | }, 59 | |_| Ok(()), 60 | f, 61 | ) 62 | } 63 | } 64 | 65 | #[cfg(test)] 66 | mod tests { 67 | use super::ToLowerCamelCase; 68 | 69 | macro_rules! t { 70 | ($t:ident : $s1:expr => $s2:expr) => { 71 | #[test] 72 | fn $t() { 73 | assert_eq!($s1.to_lower_camel_case(), $s2) 74 | } 75 | }; 76 | } 77 | 78 | t!(test1: "CamelCase" => "camelCase"); 79 | t!(test2: "This is Human case." => "thisIsHumanCase"); 80 | t!(test3: "MixedUP CamelCase, with some Spaces" => "mixedUpCamelCaseWithSomeSpaces"); 81 | t!(test4: "mixed_up_ snake_case, with some _spaces" => "mixedUpSnakeCaseWithSomeSpaces"); 82 | t!(test5: "kebab-case" => "kebabCase"); 83 | t!(test6: "SHOUTY_SNAKE_CASE" => "shoutySnakeCase"); 84 | t!(test7: "snake_case" => "snakeCase"); 85 | t!(test8: "this-contains_ ALLKinds OfWord_Boundaries" => "thisContainsAllKindsOfWordBoundaries"); 86 | t!(test9: "XΣXΣ baffle" => "xσxςBaffle"); 87 | t!(test10: "XMLHttpRequest" => "xmlHttpRequest"); 88 | } 89 | -------------------------------------------------------------------------------- /src/shouty_kebab.rs: -------------------------------------------------------------------------------- 1 | use core::fmt; 2 | 3 | use alloc::{borrow::ToOwned, string::ToString}; 4 | 5 | use crate::{transform, uppercase}; 6 | 7 | /// This trait defines a shouty kebab case conversion. 8 | /// 9 | /// In SHOUTY-KEBAB-CASE, word boundaries are indicated by hyphens and all 10 | /// words are in uppercase. 11 | /// 12 | /// ## Example: 13 | /// 14 | /// ```rust 15 | /// use heck::ToShoutyKebabCase; 16 | /// 17 | /// let sentence = "We are going to inherit the earth."; 18 | /// assert_eq!(sentence.to_shouty_kebab_case(), "WE-ARE-GOING-TO-INHERIT-THE-EARTH"); 19 | /// ``` 20 | pub trait ToShoutyKebabCase: ToOwned { 21 | /// Convert this type to shouty kebab case. 22 | fn to_shouty_kebab_case(&self) -> Self::Owned; 23 | } 24 | 25 | impl ToShoutyKebabCase for str { 26 | fn to_shouty_kebab_case(&self) -> Self::Owned { 27 | AsShoutyKebabCase(self).to_string() 28 | } 29 | } 30 | 31 | /// This wrapper performs a kebab case conversion in [`fmt::Display`]. 32 | /// 33 | /// ## Example: 34 | /// 35 | /// ``` 36 | /// use heck::AsShoutyKebabCase; 37 | /// 38 | /// let sentence = "We are going to inherit the earth."; 39 | /// assert_eq!(format!("{}", AsShoutyKebabCase(sentence)), "WE-ARE-GOING-TO-INHERIT-THE-EARTH"); 40 | /// ``` 41 | pub struct AsShoutyKebabCase>(pub T); 42 | 43 | impl> fmt::Display for AsShoutyKebabCase { 44 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 45 | transform(self.0.as_ref(), uppercase, |f| write!(f, "-"), f) 46 | } 47 | } 48 | 49 | #[cfg(test)] 50 | mod tests { 51 | use super::ToShoutyKebabCase; 52 | 53 | macro_rules! t { 54 | ($t:ident : $s1:expr => $s2:expr) => { 55 | #[test] 56 | fn $t() { 57 | assert_eq!($s1.to_shouty_kebab_case(), $s2) 58 | } 59 | }; 60 | } 61 | 62 | t!(test1: "CamelCase" => "CAMEL-CASE"); 63 | t!(test2: "This is Human case." => "THIS-IS-HUMAN-CASE"); 64 | t!(test3: "MixedUP CamelCase, with some Spaces" => "MIXED-UP-CAMEL-CASE-WITH-SOME-SPACES"); 65 | t!(test4: "mixed_up_ snake_case with some _spaces" => "MIXED-UP-SNAKE-CASE-WITH-SOME-SPACES"); 66 | t!(test5: "kebab-case" => "KEBAB-CASE"); 67 | t!(test6: "SHOUTY_SNAKE_CASE" => "SHOUTY-SNAKE-CASE"); 68 | t!(test7: "snake_case" => "SNAKE-CASE"); 69 | t!(test8: "this-contains_ ALLKinds OfWord_Boundaries" => "THIS-CONTAINS-ALL-KINDS-OF-WORD-BOUNDARIES"); 70 | t!(test9: "XΣXΣ baffle" => "XΣXΣ-BAFFLE"); 71 | t!(test10: "XMLHttpRequest" => "XML-HTTP-REQUEST"); 72 | t!(test11: "SHOUTY-KEBAB-CASE" => "SHOUTY-KEBAB-CASE"); 73 | } 74 | -------------------------------------------------------------------------------- /src/shouty_snake.rs: -------------------------------------------------------------------------------- 1 | use core::fmt; 2 | 3 | use alloc::{borrow::ToOwned, string::ToString}; 4 | 5 | use crate::{transform, uppercase}; 6 | 7 | /// This trait defines a shouty snake case conversion. 8 | /// 9 | /// In SHOUTY_SNAKE_CASE, word boundaries are indicated by underscores and all 10 | /// words are in uppercase. 11 | /// 12 | /// ## Example: 13 | /// 14 | /// ```rust 15 | /// use heck::ToShoutySnakeCase; 16 | /// 17 | /// let sentence = "That world is growing in this minute."; 18 | /// assert_eq!(sentence.to_shouty_snake_case(), "THAT_WORLD_IS_GROWING_IN_THIS_MINUTE"); 19 | /// ``` 20 | pub trait ToShoutySnakeCase: ToOwned { 21 | /// Convert this type to shouty snake case. 22 | fn to_shouty_snake_case(&self) -> Self::Owned; 23 | } 24 | 25 | /// Oh heck, `ToShoutySnekCase` is an alias for [`ToShoutySnakeCase`]. See 26 | /// ToShoutySnakeCase for more documentation. 27 | pub trait ToShoutySnekCase: ToOwned { 28 | /// CONVERT THIS TYPE TO SNEK CASE. 29 | #[allow(non_snake_case)] 30 | fn TO_SHOUTY_SNEK_CASE(&self) -> Self::Owned; 31 | } 32 | 33 | impl ToShoutySnekCase for T { 34 | fn TO_SHOUTY_SNEK_CASE(&self) -> Self::Owned { 35 | self.to_shouty_snake_case() 36 | } 37 | } 38 | 39 | impl ToShoutySnakeCase for str { 40 | fn to_shouty_snake_case(&self) -> Self::Owned { 41 | AsShoutySnakeCase(self).to_string() 42 | } 43 | } 44 | 45 | /// This wrapper performs a shouty snake case conversion in [`fmt::Display`]. 46 | /// 47 | /// ## Example: 48 | /// 49 | /// ``` 50 | /// use heck::AsShoutySnakeCase; 51 | /// 52 | /// let sentence = "That world is growing in this minute."; 53 | /// assert_eq!(format!("{}", AsShoutySnakeCase(sentence)), "THAT_WORLD_IS_GROWING_IN_THIS_MINUTE"); 54 | /// ``` 55 | pub struct AsShoutySnakeCase>(pub T); 56 | 57 | impl> fmt::Display for AsShoutySnakeCase { 58 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 59 | transform(self.0.as_ref(), uppercase, |f| write!(f, "_"), f) 60 | } 61 | } 62 | 63 | #[cfg(test)] 64 | mod tests { 65 | use super::ToShoutySnakeCase; 66 | 67 | macro_rules! t { 68 | ($t:ident : $s1:expr => $s2:expr) => { 69 | #[test] 70 | fn $t() { 71 | assert_eq!($s1.to_shouty_snake_case(), $s2) 72 | } 73 | }; 74 | } 75 | 76 | t!(test1: "CamelCase" => "CAMEL_CASE"); 77 | t!(test2: "This is Human case." => "THIS_IS_HUMAN_CASE"); 78 | t!(test3: "MixedUP CamelCase, with some Spaces" => "MIXED_UP_CAMEL_CASE_WITH_SOME_SPACES"); 79 | t!(test4: "mixed_up_snake_case with some _spaces" => "MIXED_UP_SNAKE_CASE_WITH_SOME_SPACES"); 80 | t!(test5: "kebab-case" => "KEBAB_CASE"); 81 | t!(test6: "SHOUTY_SNAKE_CASE" => "SHOUTY_SNAKE_CASE"); 82 | t!(test7: "snake_case" => "SNAKE_CASE"); 83 | t!(test8: "this-contains_ ALLKinds OfWord_Boundaries" => "THIS_CONTAINS_ALL_KINDS_OF_WORD_BOUNDARIES"); 84 | t!(test9: "XΣXΣ baffle" => "XΣXΣ_BAFFLE"); 85 | t!(test10: "XMLHttpRequest" => "XML_HTTP_REQUEST"); 86 | } 87 | -------------------------------------------------------------------------------- /src/snake.rs: -------------------------------------------------------------------------------- 1 | use alloc::{ 2 | borrow::ToOwned, 3 | fmt, 4 | string::{String, ToString}, 5 | }; 6 | 7 | use crate::{lowercase, transform}; 8 | 9 | /// This trait defines a snake case conversion. 10 | /// 11 | /// In snake_case, word boundaries are indicated by underscores. 12 | /// 13 | /// ## Example: 14 | /// 15 | /// ```rust 16 | /// use heck::ToSnakeCase; 17 | /// 18 | /// let sentence = "We carry a new world here, in our hearts."; 19 | /// assert_eq!(sentence.to_snake_case(), "we_carry_a_new_world_here_in_our_hearts"); 20 | /// ``` 21 | pub trait ToSnakeCase: ToOwned { 22 | /// Convert this type to snake case. 23 | fn to_snake_case(&self) -> Self::Owned; 24 | } 25 | 26 | /// Oh heck, `SnekCase` is an alias for [`ToSnakeCase`]. See ToSnakeCase for 27 | /// more documentation. 28 | pub trait ToSnekCase: ToOwned { 29 | /// Convert this type to snek case. 30 | fn to_snek_case(&self) -> Self::Owned; 31 | } 32 | 33 | impl ToSnekCase for T { 34 | fn to_snek_case(&self) -> Self::Owned { 35 | self.to_snake_case() 36 | } 37 | } 38 | 39 | impl ToSnakeCase for str { 40 | fn to_snake_case(&self) -> String { 41 | AsSnakeCase(self).to_string() 42 | } 43 | } 44 | 45 | /// This wrapper performs a snake case conversion in [`fmt::Display`]. 46 | /// 47 | /// ## Example: 48 | /// 49 | /// ``` 50 | /// use heck::AsSnakeCase; 51 | /// 52 | /// let sentence = "We carry a new world here, in our hearts."; 53 | /// assert_eq!(format!("{}", AsSnakeCase(sentence)), "we_carry_a_new_world_here_in_our_hearts"); 54 | /// ``` 55 | pub struct AsSnakeCase>(pub T); 56 | 57 | impl> fmt::Display for AsSnakeCase { 58 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 59 | transform(self.0.as_ref(), lowercase, |f| write!(f, "_"), f) 60 | } 61 | } 62 | 63 | #[cfg(test)] 64 | mod tests { 65 | use super::ToSnakeCase; 66 | 67 | macro_rules! t { 68 | ($t:ident : $s1:expr => $s2:expr) => { 69 | #[test] 70 | fn $t() { 71 | assert_eq!($s1.to_snake_case(), $s2) 72 | } 73 | }; 74 | } 75 | 76 | t!(test1: "CamelCase" => "camel_case"); 77 | t!(test2: "This is Human case." => "this_is_human_case"); 78 | t!(test3: "MixedUP CamelCase, with some Spaces" => "mixed_up_camel_case_with_some_spaces"); 79 | t!(test4: "mixed_up_ snake_case with some _spaces" => "mixed_up_snake_case_with_some_spaces"); 80 | t!(test5: "kebab-case" => "kebab_case"); 81 | t!(test6: "SHOUTY_SNAKE_CASE" => "shouty_snake_case"); 82 | t!(test7: "snake_case" => "snake_case"); 83 | t!(test8: "this-contains_ ALLKinds OfWord_Boundaries" => "this_contains_all_kinds_of_word_boundaries"); 84 | t!(test9: "XΣXΣ baffle" => "xσxς_baffle"); 85 | t!(test10: "XMLHttpRequest" => "xml_http_request"); 86 | t!(test11: "FIELD_NAME11" => "field_name11"); 87 | t!(test12: "99BOTTLES" => "99bottles"); 88 | t!(test13: "FieldNamE11" => "field_nam_e11"); 89 | t!(test14: "abc123def456" => "abc123def456"); 90 | t!(test16: "abc123DEF456" => "abc123_def456"); 91 | t!(test17: "abc123Def456" => "abc123_def456"); 92 | t!(test18: "abc123DEf456" => "abc123_d_ef456"); 93 | t!(test19: "ABC123def456" => "abc123def456"); 94 | t!(test20: "ABC123DEF456" => "abc123def456"); 95 | t!(test21: "ABC123Def456" => "abc123_def456"); 96 | t!(test22: "ABC123DEf456" => "abc123d_ef456"); 97 | t!(test23: "ABC123dEEf456FOO" => "abc123d_e_ef456_foo"); 98 | t!(test24: "abcDEF" => "abc_def"); 99 | t!(test25: "ABcDE" => "a_bc_de"); 100 | } 101 | -------------------------------------------------------------------------------- /src/title.rs: -------------------------------------------------------------------------------- 1 | use core::fmt; 2 | 3 | use alloc::{ 4 | borrow::ToOwned, 5 | string::{String, ToString}, 6 | }; 7 | 8 | use crate::{capitalize, transform}; 9 | 10 | /// This trait defines a title case conversion. 11 | /// 12 | /// In Title Case, word boundaries are indicated by spaces, and every word is 13 | /// capitalized. 14 | /// 15 | /// ## Example: 16 | /// 17 | /// ```rust 18 | /// use heck::ToTitleCase; 19 | /// 20 | /// let sentence = "We have always lived in slums and holes in the wall."; 21 | /// assert_eq!(sentence.to_title_case(), "We Have Always Lived In Slums And Holes In The Wall"); 22 | /// ``` 23 | pub trait ToTitleCase: ToOwned { 24 | /// Convert this type to title case. 25 | fn to_title_case(&self) -> Self::Owned; 26 | } 27 | 28 | impl ToTitleCase for str { 29 | fn to_title_case(&self) -> String { 30 | AsTitleCase(self).to_string() 31 | } 32 | } 33 | 34 | /// This wrapper performs a title case conversion in [`fmt::Display`]. 35 | /// 36 | /// ## Example: 37 | /// 38 | /// ``` 39 | /// use heck::AsTitleCase; 40 | /// 41 | /// let sentence = "We have always lived in slums and holes in the wall."; 42 | /// assert_eq!(format!("{}", AsTitleCase(sentence)), "We Have Always Lived In Slums And Holes In The Wall"); 43 | /// ``` 44 | pub struct AsTitleCase>(pub T); 45 | 46 | impl> fmt::Display for AsTitleCase { 47 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 48 | transform(self.0.as_ref(), capitalize, |f| write!(f, " "), f) 49 | } 50 | } 51 | 52 | #[cfg(test)] 53 | mod tests { 54 | use super::ToTitleCase; 55 | 56 | macro_rules! t { 57 | ($t:ident : $s1:expr => $s2:expr) => { 58 | #[test] 59 | fn $t() { 60 | assert_eq!($s1.to_title_case(), $s2) 61 | } 62 | }; 63 | } 64 | 65 | t!(test1: "CamelCase" => "Camel Case"); 66 | t!(test2: "This is Human case." => "This Is Human Case"); 67 | t!(test3: "MixedUP CamelCase, with some Spaces" => "Mixed Up Camel Case With Some Spaces"); 68 | t!(test4: "mixed_up_ snake_case, with some _spaces" => "Mixed Up Snake Case With Some Spaces"); 69 | t!(test5: "kebab-case" => "Kebab Case"); 70 | t!(test6: "SHOUTY_SNAKE_CASE" => "Shouty Snake Case"); 71 | t!(test7: "snake_case" => "Snake Case"); 72 | t!(test8: "this-contains_ ALLKinds OfWord_Boundaries" => "This Contains All Kinds Of Word Boundaries"); 73 | t!(test9: "XΣXΣ baffle" => "Xσxς Baffle"); 74 | t!(test10: "XMLHttpRequest" => "Xml Http Request"); 75 | } 76 | -------------------------------------------------------------------------------- /src/train.rs: -------------------------------------------------------------------------------- 1 | use core::fmt; 2 | 3 | use alloc::{borrow::ToOwned, string::ToString}; 4 | 5 | use crate::{capitalize, transform}; 6 | 7 | /// This trait defines a train case conversion. 8 | /// 9 | /// In Train-Case, word boundaries are indicated by hyphens and words start 10 | /// with Capital Letters. 11 | /// 12 | /// ## Example: 13 | /// 14 | /// ```rust 15 | /// use heck::ToTrainCase; 16 | /// 17 | /// let sentence = "We are going to inherit the earth."; 18 | /// assert_eq!(sentence.to_train_case(), "We-Are-Going-To-Inherit-The-Earth"); 19 | /// ``` 20 | pub trait ToTrainCase: ToOwned { 21 | /// Convert this type to Train-Case. 22 | fn to_train_case(&self) -> Self::Owned; 23 | } 24 | 25 | impl ToTrainCase for str { 26 | fn to_train_case(&self) -> Self::Owned { 27 | AsTrainCase(self).to_string() 28 | } 29 | } 30 | 31 | /// This wrapper performs a train case conversion in [`fmt::Display`]. 32 | /// 33 | /// ## Example: 34 | /// 35 | /// ``` 36 | /// use heck::AsTrainCase; 37 | /// 38 | /// let sentence = "We are going to inherit the earth."; 39 | /// assert_eq!(format!("{}", AsTrainCase(sentence)), "We-Are-Going-To-Inherit-The-Earth"); 40 | /// ``` 41 | pub struct AsTrainCase>(pub T); 42 | 43 | impl> fmt::Display for AsTrainCase { 44 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 45 | transform(self.0.as_ref(), capitalize, |f| write!(f, "-"), f) 46 | } 47 | } 48 | 49 | #[cfg(test)] 50 | mod tests { 51 | use super::ToTrainCase; 52 | 53 | macro_rules! t { 54 | ($t:ident : $s1:expr => $s2:expr) => { 55 | #[test] 56 | fn $t() { 57 | assert_eq!($s1.to_train_case(), $s2) 58 | } 59 | }; 60 | } 61 | 62 | t!(test1: "CamelCase" => "Camel-Case"); 63 | t!(test2: "This is Human case." => "This-Is-Human-Case"); 64 | t!(test3: "MixedUP CamelCase, with some Spaces" => "Mixed-Up-Camel-Case-With-Some-Spaces"); 65 | t!(test4: "mixed_up_ snake_case with some _spaces" => "Mixed-Up-Snake-Case-With-Some-Spaces"); 66 | t!(test5: "kebab-case" => "Kebab-Case"); 67 | t!(test6: "SHOUTY_SNAKE_CASE" => "Shouty-Snake-Case"); 68 | t!(test7: "snake_case" => "Snake-Case"); 69 | t!(test8: "this-contains_ ALLKinds OfWord_Boundaries" => "This-Contains-All-Kinds-Of-Word-Boundaries"); 70 | #[cfg(feature = "unicode")] 71 | t!(test9: "XΣXΣ baffle" => "Xσxς-Baffle"); 72 | t!(test10: "XMLHttpRequest" => "Xml-Http-Request"); 73 | t!(test11: "FIELD_NAME11" => "Field-Name11"); 74 | t!(test12: "99BOTTLES" => "99bottles"); 75 | t!(test13: "FieldNamE11" => "Field-Nam-E11"); 76 | t!(test14: "abc123def456" => "Abc123def456"); 77 | t!(test16: "abc123DEF456" => "Abc123-Def456"); 78 | t!(test17: "abc123Def456" => "Abc123-Def456"); 79 | t!(test18: "abc123DEf456" => "Abc123-D-Ef456"); 80 | t!(test19: "ABC123def456" => "Abc123def456"); 81 | t!(test20: "ABC123DEF456" => "Abc123def456"); 82 | t!(test21: "ABC123Def456" => "Abc123-Def456"); 83 | t!(test22: "ABC123DEf456" => "Abc123d-Ef456"); 84 | t!(test23: "ABC123dEEf456FOO" => "Abc123d-E-Ef456-Foo"); 85 | t!(test24: "abcDEF" => "Abc-Def"); 86 | t!(test25: "ABcDE" => "A-Bc-De"); 87 | } 88 | -------------------------------------------------------------------------------- /src/upper_camel.rs: -------------------------------------------------------------------------------- 1 | use core::fmt; 2 | 3 | use alloc::{ 4 | borrow::ToOwned, 5 | string::{String, ToString}, 6 | }; 7 | 8 | use crate::{capitalize, transform}; 9 | 10 | /// This trait defines an upper camel case conversion. 11 | /// 12 | /// In UpperCamelCase, word boundaries are indicated by capital letters, 13 | /// including the first word. 14 | /// 15 | /// ## Example: 16 | /// 17 | /// ```rust 18 | /// use heck::ToUpperCamelCase; 19 | /// 20 | /// let sentence = "We are not in the least afraid of ruins."; 21 | /// assert_eq!(sentence.to_upper_camel_case(), "WeAreNotInTheLeastAfraidOfRuins"); 22 | /// ``` 23 | pub trait ToUpperCamelCase: ToOwned { 24 | /// Convert this type to upper camel case. 25 | fn to_upper_camel_case(&self) -> Self::Owned; 26 | } 27 | 28 | impl ToUpperCamelCase for str { 29 | fn to_upper_camel_case(&self) -> String { 30 | AsUpperCamelCase(self).to_string() 31 | } 32 | } 33 | 34 | /// `ToPascalCase` is an alias for [`ToUpperCamelCase`]. See ToUpperCamelCase for more 35 | /// documentation. 36 | pub trait ToPascalCase: ToOwned { 37 | /// Convert this type to upper camel case. 38 | fn to_pascal_case(&self) -> Self::Owned; 39 | } 40 | 41 | impl ToPascalCase for T { 42 | fn to_pascal_case(&self) -> Self::Owned { 43 | self.to_upper_camel_case() 44 | } 45 | } 46 | 47 | /// This wrapper performs a upper camel case conversion in [`fmt::Display`]. 48 | /// 49 | /// ## Example: 50 | /// 51 | /// ``` 52 | /// use heck::AsUpperCamelCase; 53 | /// 54 | /// let sentence = "We are not in the least afraid of ruins."; 55 | /// assert_eq!(format!("{}", AsUpperCamelCase(sentence)), "WeAreNotInTheLeastAfraidOfRuins"); 56 | /// ``` 57 | pub struct AsUpperCamelCase>(pub T); 58 | 59 | impl> fmt::Display for AsUpperCamelCase { 60 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 61 | transform(self.0.as_ref(), capitalize, |_| Ok(()), f) 62 | } 63 | } 64 | 65 | #[cfg(test)] 66 | mod tests { 67 | use super::ToUpperCamelCase; 68 | 69 | macro_rules! t { 70 | ($t:ident : $s1:expr => $s2:expr) => { 71 | #[test] 72 | fn $t() { 73 | assert_eq!($s1.to_upper_camel_case(), $s2) 74 | } 75 | }; 76 | } 77 | 78 | t!(test1: "CamelCase" => "CamelCase"); 79 | t!(test2: "This is Human case." => "ThisIsHumanCase"); 80 | t!(test3: "MixedUP_CamelCase, with some Spaces" => "MixedUpCamelCaseWithSomeSpaces"); 81 | t!(test4: "mixed_up_ snake_case, with some _spaces" => "MixedUpSnakeCaseWithSomeSpaces"); 82 | t!(test5: "kebab-case" => "KebabCase"); 83 | t!(test6: "SHOUTY_SNAKE_CASE" => "ShoutySnakeCase"); 84 | t!(test7: "snake_case" => "SnakeCase"); 85 | t!(test8: "this-contains_ ALLKinds OfWord_Boundaries" => "ThisContainsAllKindsOfWordBoundaries"); 86 | t!(test9: "XΣXΣ baffle" => "XσxςBaffle"); 87 | t!(test10: "XMLHttpRequest" => "XmlHttpRequest"); 88 | } 89 | --------------------------------------------------------------------------------