├── .github ├── dependabot.yml └── workflows │ └── rust.yml ├── .gitignore ├── Cargo.toml ├── LICENSE ├── README.md └── src └── lib.rs /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: "cargo" # See documentation for possible values 9 | directory: "/" # Location of package manifests 10 | schedule: 11 | interval: "monthly" 12 | -------------------------------------------------------------------------------- /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | on: [push, pull_request] 2 | 3 | name: Rust 4 | 5 | jobs: 6 | check: 7 | name: Cargo Check 8 | runs-on: ubuntu-latest 9 | steps: 10 | - uses: actions/checkout@v2 11 | - uses: actions-rs/toolchain@v1 12 | with: 13 | profile: minimal 14 | toolchain: stable 15 | override: true 16 | - uses: actions-rs/cargo@v1 17 | with: 18 | command: check 19 | args: --all-features 20 | 21 | test: 22 | name: Test Suite 23 | runs-on: ubuntu-latest 24 | steps: 25 | - uses: actions/checkout@v2 26 | - uses: actions-rs/toolchain@v1 27 | with: 28 | profile: minimal 29 | toolchain: stable 30 | override: true 31 | - uses: actions-rs/cargo@v1 32 | with: 33 | command: test 34 | args: --all-targets --all-features 35 | 36 | doc: 37 | name: Documentation 38 | runs-on: ubuntu-latest 39 | steps: 40 | - uses: actions/checkout@v2 41 | - uses: actions-rs/toolchain@v1 42 | with: 43 | profile: minimal 44 | toolchain: stable 45 | override: true 46 | - uses: actions-rs/cargo@v1 47 | with: 48 | command: test 49 | args: --doc --all-features 50 | 51 | fmt: 52 | name: Format 53 | runs-on: ubuntu-latest 54 | steps: 55 | - uses: actions/checkout@v2 56 | - uses: actions-rs/toolchain@v1 57 | with: 58 | profile: minimal 59 | toolchain: stable 60 | override: true 61 | - run: rustup component add rustfmt 62 | - uses: actions-rs/cargo@v1 63 | with: 64 | command: fmt 65 | args: --all -- --check 66 | 67 | clippy: 68 | name: Clippy Lints 69 | runs-on: ubuntu-latest 70 | steps: 71 | - uses: actions/checkout@v2 72 | - uses: actions-rs/toolchain@v1 73 | with: 74 | profile: minimal 75 | toolchain: stable 76 | override: true 77 | - run: rustup component add clippy 78 | - uses: actions-rs/cargo@v1 79 | with: 80 | command: clippy 81 | args: --all-targets --all-features -- --warn warnings --warn clippy::all --warn clippy::pedantic --warn clippy::cargo --warn clippy::nursery --allow clippy::missing_const_for_fn 82 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | /target 3 | **/*.rs.bk 4 | Cargo.lock 5 | 6 | ### JetBrains 7 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm 8 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 9 | 10 | # User-specific stuff 11 | .idea/**/workspace.xml 12 | .idea/**/tasks.xml 13 | .idea/dictionaries 14 | 15 | # Sensitive or high-churn files 16 | .idea/**/dataSources/ 17 | .idea/**/dataSources.ids 18 | .idea/**/dataSources.local.xml 19 | .idea/**/sqlDataSources.xml 20 | .idea/**/dynamic.xml 21 | .idea/**/uiDesigner.xml 22 | 23 | # Gradle 24 | .idea/**/gradle.xml 25 | .idea/**/libraries 26 | 27 | # CMake 28 | cmake-build-debug/ 29 | cmake-build-release/ 30 | 31 | # Mongo Explorer plugin 32 | .idea/**/mongoSettings.xml 33 | 34 | # File-based project format 35 | *.iws 36 | 37 | # IntelliJ 38 | out/ 39 | 40 | # mpeltonen/sbt-idea plugin 41 | .idea_modules/ 42 | 43 | # JIRA plugin 44 | atlassian-ide-plugin.xml 45 | 46 | # Cursive Clojure plugin 47 | .idea/replstate.xml 48 | 49 | # Crashlytics plugin (for Android Studio and IntelliJ) 50 | com_crashlytics_export_strings.xml 51 | crashlytics.properties 52 | crashlytics-build.properties 53 | fabric.properties 54 | 55 | ### VisualStudioCode 56 | .vscode/* 57 | !.vscode/settings.json 58 | !.vscode/tasks.json 59 | !.vscode/launch.json 60 | !.vscode/extensions.json 61 | 62 | ### Rust 63 | # Generated by Cargo 64 | # will have compiled files and executables 65 | /target/ 66 | 67 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 68 | # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html 69 | Cargo.lock 70 | 71 | # These are backup files generated by rustfmt 72 | **/*.rs.bk 73 | 74 | ### Python 75 | # Byte-compiled / optimized / DLL files 76 | __pycache__/ 77 | *.py[cod] 78 | *$py.class 79 | 80 | # C extensions 81 | *.so 82 | 83 | # Distribution / packaging 84 | .Python 85 | build/ 86 | develop-eggs/ 87 | dist/ 88 | downloads/ 89 | eggs/ 90 | .eggs/ 91 | lib/ 92 | lib64/ 93 | parts/ 94 | sdist/ 95 | var/ 96 | wheels/ 97 | *.egg-info/ 98 | .installed.cfg 99 | *.egg 100 | MANIFEST 101 | 102 | # PyInstaller 103 | # Usually these files are written by a python script from a template 104 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 105 | *.manifest 106 | *.spec 107 | 108 | # Installer logs 109 | pip-log.txt 110 | pip-delete-this-directory.txt 111 | 112 | # Unit test / coverage reports 113 | htmlcov/ 114 | .tox/ 115 | .coverage 116 | .coverage.* 117 | .cache 118 | nosetests.xml 119 | coverage.xml 120 | *.cover 121 | .hypothesis/ 122 | .pytest_cache/ 123 | 124 | # Translations 125 | *.mo 126 | *.pot 127 | 128 | # Django stuff: 129 | *.log 130 | local_settings.py 131 | db.sqlite3 132 | 133 | # Flask stuff: 134 | instance/ 135 | .webassets-cache 136 | 137 | # Scrapy stuff: 138 | .scrapy 139 | 140 | # Sphinx documentation 141 | docs/_build/ 142 | 143 | # PyBuilder 144 | target/ 145 | 146 | # Jupyter Notebook 147 | .ipynb_checkpoints 148 | 149 | # pyenv 150 | .python-version 151 | 152 | # celery beat schedule file 153 | celerybeat-schedule 154 | 155 | # SageMath parsed files 156 | *.sage.py 157 | 158 | # Environments 159 | .env 160 | .venv 161 | env/ 162 | venv/ 163 | ENV/ 164 | env.bak/ 165 | venv.bak/ 166 | 167 | # Spyder project settings 168 | .spyderproject 169 | .spyproject 170 | 171 | # Rope project settings 172 | .ropeproject 173 | 174 | # mkdocs documentation 175 | /site 176 | 177 | # mypy 178 | .mypy_cache/ 179 | 180 | ### Node 181 | # Logs 182 | logs 183 | *.log 184 | npm-debug.log* 185 | yarn-debug.log* 186 | yarn-error.log* 187 | 188 | # Runtime data 189 | pids 190 | *.pid 191 | *.seed 192 | *.pid.lock 193 | 194 | # Directory for instrumented libs generated by jscoverage/JSCover 195 | lib-cov 196 | 197 | # Coverage directory used by tools like istanbul 198 | coverage 199 | 200 | # nyc test coverage 201 | .nyc_output 202 | 203 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 204 | .grunt 205 | 206 | # Bower dependency directory (https://bower.io/) 207 | bower_components 208 | 209 | # node-waf configuration 210 | .lock-wscript 211 | 212 | # Compiled binary addons (https://nodejs.org/api/addons.html) 213 | build/Release 214 | 215 | # Dependency directories 216 | node_modules/ 217 | jspm_packages/ 218 | 219 | # TypeScript v1 declaration files 220 | typings/ 221 | 222 | # Optional npm cache directory 223 | .npm 224 | 225 | # Optional eslint cache 226 | .eslintcache 227 | 228 | # Optional REPL history 229 | .node_repl_history 230 | 231 | # Output of 'npm pack' 232 | *.tgz 233 | 234 | # Yarn Integrity file 235 | .yarn-integrity 236 | 237 | # dotenv environment variables file 238 | .env 239 | 240 | # next.js build output 241 | .next 242 | 243 | ### Ruby 244 | *.gem 245 | *.rbc 246 | /.config 247 | /coverage/ 248 | /InstalledFiles 249 | /pkg/ 250 | /spec/reports/ 251 | /spec/examples.txt 252 | /test/tmp/ 253 | /test/version_tmp/ 254 | /tmp/ 255 | 256 | # Used by dotenv library to load environment variables. 257 | # .env 258 | 259 | ## Specific to RubyMotion: 260 | .dat* 261 | .repl_history 262 | build/ 263 | *.bridgesupport 264 | build-iPhoneOS/ 265 | build-iPhoneSimulator/ 266 | 267 | ## Specific to RubyMotion (use of CocoaPods): 268 | # 269 | # We recommend against adding the Pods directory to your .gitignore. However 270 | # you should judge for yourself, the pros and cons are mentioned at: 271 | # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control 272 | # 273 | # vendor/Pods/ 274 | 275 | ## Documentation cache and generated files: 276 | /.yardoc/ 277 | /_yardoc/ 278 | /doc/ 279 | /rdoc/ 280 | 281 | ## Environment normalization: 282 | /.bundle/ 283 | /vendor/bundle 284 | /lib/bundler/man/ 285 | 286 | # for a library or gem, you might want to ignore these files since the code is 287 | # intended to run in multiple environments; otherwise, check them in: 288 | # Gemfile.lock 289 | # .ruby-version 290 | # .ruby-gemset 291 | 292 | # unless supporting rvm < 1.11.0 or doing something fancy, ignore this: 293 | .rvmrc 294 | /.idea/ 295 | *.iml 296 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "nuid" 3 | version = "0.5.0" 4 | authors = ["Ivan Porto Carrero "] 5 | license = "Apache-2.0" 6 | repository = "https://github.com/casualjim/rs-nuid.git" 7 | readme = "README.md" 8 | keywords = ["nuid", "guid", "uuid"] 9 | description = "A highly performant unique identifier generator." 10 | categories = ["data-structures", "date-and-time", "value-formatting", "encoding", "parsing"] 11 | edition = "2021" 12 | rust-version = "1.63" 13 | 14 | [dependencies] 15 | rand = "0.8" 16 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # NUID 2 | 3 | [![License Apache 2](https://img.shields.io/badge/License-Apache2-blue.svg)](https://www.apache.org/licenses/LICENSE-2.0) 4 | 5 | A highly performant unique identifier generator. 6 | 7 | ## Installation 8 | 9 | In Cargo.toml: 10 | 11 | ```toml 12 | [dependencies] 13 | nuid = "0.5" 14 | ``` 15 | 16 | ## Basic Usage 17 | 18 | ```rust 19 | // Utilize the global locked instance 20 | nuid := nuid::next(); 21 | 22 | // Create an instance, these are not locked. 23 | n := nuid::NUID::new(); 24 | nuid = n.next(); 25 | 26 | // Generate a new crypto/rand seeded prefix. 27 | // Generally not needed, happens automatically. 28 | n.randomize_prefix(); 29 | ``` 30 | 31 | ## Performance 32 | 33 | NUID needs to be very fast to generate and be truly unique, all while being entropy pool friendly. 34 | NUID uses 12 bytes of crypto generated data (entropy draining), and 10 bytes of pseudo-random 35 | sequential data that increments with a pseudo-random increment. 36 | 37 | Total length of a NUID string is 22 bytes of base 62 ascii text, so 62^22 or 38 | 2707803647802660400290261537185326956544 possibilities. 39 | 40 | NUID can generate identifiers as fast as 60ns, or ~16 million per second. There is an associated 41 | benchmark you can use to test performance on your own hardware. 42 | 43 | ## License 44 | 45 | Unless otherwise noted, the NATS source files are distributed 46 | under the Apache Version 2.0 license found in the LICENSE file. 47 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Ivan Porto Carrero 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | // 15 | 16 | use std::fmt::{self, Display}; 17 | use std::ops::Deref; 18 | use std::str; 19 | use std::sync::Mutex; 20 | 21 | use rand::distributions::Alphanumeric; 22 | use rand::rngs::OsRng; 23 | use rand::thread_rng; 24 | use rand::Rng; 25 | 26 | const BASE: usize = 62; 27 | const ALPHABET: [u8; BASE] = *b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; 28 | 29 | const PRE_LEN: usize = 12; 30 | const MAX_SEQ: u64 = 839_299_365_868_340_224; // (BASE ^ remaining bytes 22 - 12) == 62^10 31 | const MIN_INC: u64 = 33; 32 | const MAX_INC: u64 = 333; 33 | 34 | /// The number of bytes/characters of a NUID. 35 | pub const TOTAL_LEN: usize = 22; 36 | 37 | static GLOBAL_NUID: Mutex = Mutex::new(NUID::new()); 38 | 39 | /// Generate the next `NUID` string from the global locked `NUID` instance. 40 | #[allow(clippy::missing_panics_doc)] 41 | #[must_use] 42 | pub fn next() -> NUIDStr { 43 | GLOBAL_NUID.lock().unwrap().next() 44 | } 45 | 46 | /// NUID needs to be very fast to generate and truly unique, all while being entropy pool friendly. 47 | /// We will use 12 bytes of crypto generated data (entropy draining), and 10 bytes of sequential data 48 | /// that is started at a pseudo random number and increments with a pseudo-random increment. 49 | /// Total is 22 bytes of base 62 ascii text :) 50 | pub struct NUID { 51 | pre: [u8; PRE_LEN], 52 | seq: u64, 53 | inc: u64, 54 | } 55 | 56 | /// An `NUID` string. 57 | /// 58 | /// Use [`NUIDStr::as_str`], [`NUIDStr::into_bytes`], the [`Deref`] implementation or 59 | /// [`ToString`] to access the string. 60 | pub struct NUIDStr( 61 | // INVARIANT: this buffer must always contain a valid utf-8 string 62 | [u8; TOTAL_LEN], 63 | ); 64 | 65 | impl Default for NUID { 66 | fn default() -> Self { 67 | Self::new() 68 | } 69 | } 70 | 71 | impl NUID { 72 | /// generate a new `NUID` and properly initialize the prefix, sequential start, and sequential increment. 73 | #[must_use] 74 | pub const fn new() -> Self { 75 | Self { 76 | pre: [0; PRE_LEN], 77 | // the first call to `next` will cause the prefix and sequential to be regenerated 78 | seq: MAX_SEQ, 79 | inc: 0, 80 | } 81 | } 82 | 83 | pub fn randomize_prefix(&mut self) { 84 | let rng = OsRng; 85 | for (i, n) in rng.sample_iter(&Alphanumeric).take(PRE_LEN).enumerate() { 86 | self.pre[i] = ALPHABET[n as usize % BASE]; 87 | } 88 | } 89 | 90 | /// Generate the next `NUID` string. 91 | #[allow(clippy::should_implement_trait)] 92 | #[must_use] 93 | pub fn next(&mut self) -> NUIDStr { 94 | let mut buffer = [0u8; TOTAL_LEN]; 95 | 96 | self.seq += self.inc; 97 | if self.seq >= MAX_SEQ { 98 | self.randomize_prefix(); 99 | self.reset_sequential(); 100 | } 101 | #[allow(clippy::cast_possible_truncation)] 102 | let seq = self.seq as usize; 103 | 104 | for (i, n) in self.pre.iter().enumerate() { 105 | buffer[i] = *n; 106 | } 107 | 108 | let mut l = seq; 109 | for i in (PRE_LEN..TOTAL_LEN).rev() { 110 | buffer[i] = ALPHABET[l % BASE]; 111 | l /= BASE; 112 | } 113 | 114 | // `buffer` has been filled with base62 data, which is always valid utf-8 115 | NUIDStr(buffer) 116 | } 117 | 118 | fn reset_sequential(&mut self) { 119 | let mut rng = thread_rng(); 120 | self.seq = rng.gen_range(0..MAX_SEQ); 121 | self.inc = rng.gen_range(MIN_INC..MAX_INC); 122 | } 123 | } 124 | 125 | impl NUIDStr { 126 | /// Get a reference to the inner string 127 | #[must_use] 128 | pub fn as_str(&self) -> &str { 129 | // SAFETY: the invariant guarantees the buffer to always contain utf-8 characters 130 | unsafe { str::from_utf8_unchecked(&self.0) } 131 | } 132 | 133 | /// Extract the inner buffer 134 | #[must_use] 135 | pub fn into_bytes(self) -> [u8; TOTAL_LEN] { 136 | self.0 137 | } 138 | } 139 | 140 | impl Display for NUIDStr { 141 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 142 | f.write_str(self.as_str()) 143 | } 144 | } 145 | 146 | impl Deref for NUIDStr { 147 | type Target = str; 148 | 149 | /// Get a reference to the inner string 150 | fn deref(&self) -> &Self::Target { 151 | self.as_str() 152 | } 153 | } 154 | 155 | #[cfg(test)] 156 | mod tests { 157 | use super::*; 158 | use std::collections::HashSet; 159 | 160 | #[test] 161 | fn alphabet_size() { 162 | assert_eq!(ALPHABET.len(), BASE); 163 | } 164 | 165 | #[test] 166 | fn global_nuid_init() { 167 | assert_eq!(GLOBAL_NUID.lock().unwrap().pre.len(), PRE_LEN); 168 | assert_ne!(GLOBAL_NUID.lock().unwrap().seq, 0); 169 | } 170 | 171 | #[test] 172 | fn nuid_rollover() { 173 | let mut n = NUID::new(); 174 | n.seq = MAX_SEQ; 175 | let old = n.pre.to_vec(); 176 | let _ = n.next(); 177 | assert_ne!(n.pre.to_vec(), old); 178 | 179 | let mut n = NUID::new(); 180 | n.seq = 1; 181 | let old = n.pre.to_vec(); 182 | let _ = n.next(); 183 | assert_eq!(n.pre.to_vec(), old); 184 | } 185 | 186 | #[test] 187 | fn nuid_len() { 188 | let id = next(); 189 | assert_eq!(id.len(), TOTAL_LEN); 190 | } 191 | 192 | #[test] 193 | fn proper_prefix() { 194 | let mut min: u8 = 255; 195 | let mut max: u8 = 0; 196 | 197 | for nn in &ALPHABET { 198 | let n = *nn; 199 | if n < min { 200 | min = n; 201 | } 202 | if n > max { 203 | max = n; 204 | } 205 | } 206 | 207 | for _ in 0..100_000 { 208 | let nuid = NUID::new(); 209 | for j in 0..PRE_LEN { 210 | assert!(nuid.pre[j] >= min || nuid.pre[j] <= max); 211 | } 212 | } 213 | } 214 | 215 | #[test] 216 | fn unique() { 217 | let mut set = HashSet::new(); 218 | for _ in 0..10_000_000 { 219 | assert!(set.insert(next().to_string())); 220 | } 221 | } 222 | } 223 | --------------------------------------------------------------------------------