uuid58 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/LICENSE +21 -0
- data/README.md +175 -0
- data/lib/uuid58/version.rb +5 -0
- data/lib/uuid58.rb +237 -0
- metadata +47 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: c9fefacc984af2fd9877230142d176db69532f767cef06b046344a2e682cf776
|
|
4
|
+
data.tar.gz: d5e00b37a2a49b98edb11b5fba03c1fd4a3cb60909b816a6d8803f71ebf0a738
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: 5e0db5dd62dbc631987ae4f4497c3639c5bf2a1eaefcc5d44f5cbf173bd6c394751a7f449f31b9914c420680a07db61a38c76205de8095b07f64e3fb42114aa1
|
|
7
|
+
data.tar.gz: 638888d5d19fc1ee414290c4c720620514f2b3706eeb64080e88dd6997850373faad8eea3d72b6238af07638b7b9218a6f932bba435c94509d178c0d3c6f6848
|
data/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Nakano as a Service
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
data/README.md
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
# uuid58 for Ruby
|
|
2
|
+
|
|
3
|
+
[](https://github.com/nakanoasaservice/uuid58/actions/workflows/ci-ruby.yml)
|
|
4
|
+
[](https://github.com/nakanoasaservice/uuid58/blob/main/LICENSE)
|
|
5
|
+
|
|
6
|
+
Shorten UUIDs to 22-character Base58 strings, and back, in Ruby. Give Rails
|
|
7
|
+
records with UUID primary keys short, URL-safe IDs in a few lines.
|
|
8
|
+
|
|
9
|
+
```text
|
|
10
|
+
f4b247fd-1f87-45d4-aa06-1c6fc0a8dfaf ⇄ XDY9dmBbcMBXqcRvYw8xJ2
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
- **Fixed 22 characters**, using the Bitcoin Base58 alphabet: URL-safe, with
|
|
14
|
+
no `0`, `O`, `I`, or `l`.
|
|
15
|
+
- **Sortable**: sorting uuid58 strings bytewise sorts the UUIDs numerically,
|
|
16
|
+
so UUIDv7 IDs stay time-ordered.
|
|
17
|
+
- **Stable spec, well tested**: implements
|
|
18
|
+
[uuid58 spec 1.1.0](https://github.com/nakanoasaservice/uuid58/blob/main/spec/SPEC.md)
|
|
19
|
+
and passes its 200+ shared
|
|
20
|
+
[test vectors](https://github.com/nakanoasaservice/uuid58/blob/main/spec/vectors.json),
|
|
21
|
+
so output matches every other language.
|
|
22
|
+
- **No dependencies**, Ruby 3.2+.
|
|
23
|
+
|
|
24
|
+
[Try it in your browser](https://nakanoasaservice.github.io/uuid58/) ·
|
|
25
|
+
[Specification](https://github.com/nakanoasaservice/uuid58/blob/main/spec/SPEC.md) ·
|
|
26
|
+
[Other languages](https://github.com/nakanoasaservice/uuid58#install)
|
|
27
|
+
|
|
28
|
+
## Install
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
bundle add uuid58
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
or `gem install uuid58`. The gem is not released on RubyGems yet; these
|
|
35
|
+
commands work once the first version is published.
|
|
36
|
+
|
|
37
|
+
## Usage
|
|
38
|
+
|
|
39
|
+
```ruby
|
|
40
|
+
require "uuid58"
|
|
41
|
+
|
|
42
|
+
s = "XDY9dmBbcMBXqcRvYw8xJ2"
|
|
43
|
+
|
|
44
|
+
# All of these return s:
|
|
45
|
+
Uuid58.encode("f4b247fd-1f87-45d4-aa06-1c6fc0a8dfaf")
|
|
46
|
+
Uuid58.encode("F4B247FD1F8745D4AA061C6FC0A8DFAF") # plain hex, any case
|
|
47
|
+
Uuid58.encode(["f4b247fd1f8745d4aa061c6fc0a8dfaf"].pack("H32")) # 16 binary bytes
|
|
48
|
+
Uuid58.encode(0xF4B247FD1F8745D4AA061C6FC0A8DFAF)
|
|
49
|
+
|
|
50
|
+
Uuid58.decode(s) # => "f4b247fd-1f87-45d4-aa06-1c6fc0a8dfaf"
|
|
51
|
+
Uuid58.decode_bytes(s) # => "\xF4\xB2G\xFD\x1F\x87E\xD4..." (Encoding::BINARY)
|
|
52
|
+
Uuid58.decode_int(s) # => 325257319917903217740243107280071483311
|
|
53
|
+
|
|
54
|
+
Uuid58.valid?("XDY9dmBbcMBXqcRvYw8xJ2") # => true
|
|
55
|
+
Uuid58.valid?("zzzzzzzzzzzzzzzzzzzzzz") # => false: exceeds 128 bits
|
|
56
|
+
|
|
57
|
+
Uuid58.generate # a random UUIDv4, encoded, e.g. "Tj5D5H2Bc1LcPjwNNhH4xS"
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
### Rails
|
|
61
|
+
|
|
62
|
+
With UUID primary keys, encode for URLs and decode when looking records up:
|
|
63
|
+
|
|
64
|
+
```ruby
|
|
65
|
+
class Post < ApplicationRecord
|
|
66
|
+
def to_param = Uuid58.encode(id)
|
|
67
|
+
|
|
68
|
+
def self.find_by_param!(param) = find(Uuid58.decode(param))
|
|
69
|
+
end
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
`Uuid58.decode` raises `Uuid58::Error` (an `ArgumentError`) for a malformed
|
|
73
|
+
parameter; rescue it, or check `Uuid58.valid?` first, to return 404 instead
|
|
74
|
+
of 500.
|
|
75
|
+
|
|
76
|
+
### Strings, encodings and bytes
|
|
77
|
+
|
|
78
|
+
`encode` decides how to read a `String` from its encoding:
|
|
79
|
+
|
|
80
|
+
- **`Encoding::BINARY`** (`ASCII-8BIT`) strings are raw bytes and must be
|
|
81
|
+
exactly 16 bytes long. These come from `Array#pack`,
|
|
82
|
+
`SecureRandom.random_bytes`, or `bytea`/`binary(16)` columns.
|
|
83
|
+
- **Any other encoding** is UUID text (see [Accepted UUID strings](#accepted-uuid-strings)).
|
|
84
|
+
|
|
85
|
+
Some sources return text as `BINARY`, such as `Net::HTTP` bodies or
|
|
86
|
+
`File.binread`. Call `Uuid58.encode(str.dup.force_encoding(Encoding::UTF_8))`
|
|
87
|
+
for those, or use `Uuid58.encode_bytes` / `Uuid58.encode_int` to choose
|
|
88
|
+
explicitly.
|
|
89
|
+
|
|
90
|
+
Every check works on bytes, so any byte `0x80` or above is rejected, whatever
|
|
91
|
+
the string's encoding
|
|
92
|
+
([SPEC.md Section 4.1](https://github.com/nakanoasaservice/uuid58/blob/main/spec/SPEC.md#41-measuring-length)). Strings in an encoding that is
|
|
93
|
+
not ASCII-compatible (UTF-16, UTF-32) are transcoded to UTF-8 first.
|
|
94
|
+
|
|
95
|
+
### Errors
|
|
96
|
+
|
|
97
|
+
All invalid-input errors subclass `Uuid58::Error`, which subclasses
|
|
98
|
+
`ArgumentError`. Each has a `kind` symbol naming the spec error kind
|
|
99
|
+
([SPEC.md Section 7](https://github.com/nakanoasaservice/uuid58/blob/main/spec/SPEC.md#7-errors)):
|
|
100
|
+
|
|
101
|
+
| Exception | `kind` | Raised when |
|
|
102
|
+
| ------------------------------- | -------------------- | -------------------------------------------------------------------- |
|
|
103
|
+
| `Uuid58::InvalidLengthError` | `:invalid_length` | a string of the wrong length, or bytes whose length is not 16 |
|
|
104
|
+
| `Uuid58::InvalidCharacterError` | `:invalid_character` | a character not allowed in its position |
|
|
105
|
+
| `Uuid58::OverflowError` | `:overflow` | a value outside `0..2**128 - 1` (decoded string or encoded Integer) |
|
|
106
|
+
|
|
107
|
+
Input that contains a non-ASCII character raises `InvalidLengthError` or
|
|
108
|
+
`InvalidCharacterError`, depending on the byte length.
|
|
109
|
+
|
|
110
|
+
```ruby
|
|
111
|
+
begin
|
|
112
|
+
Uuid58.decode(user_input)
|
|
113
|
+
rescue Uuid58::InvalidCharacterError
|
|
114
|
+
# ...
|
|
115
|
+
rescue Uuid58::Error => e
|
|
116
|
+
e.kind # => :invalid_length or :overflow
|
|
117
|
+
end
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
Passing an unsupported type (for example `nil`, a `Float` or a `Symbol`)
|
|
121
|
+
raises `TypeError`. Error messages are not part of the specification and may
|
|
122
|
+
change.
|
|
123
|
+
|
|
124
|
+
## API
|
|
125
|
+
|
|
126
|
+
| Method | Description |
|
|
127
|
+
| --------------------------------------- | -------------------------------------------------------------------------- |
|
|
128
|
+
| `Uuid58.encode(value) -> String` | Encode a UUID string, a 16-byte `BINARY` string, or an `Integer`. |
|
|
129
|
+
| `Uuid58.encode_bytes(bytes) -> String` | Encode exactly 16 bytes, whatever the string's encoding. |
|
|
130
|
+
| `Uuid58.encode_int(int) -> String` | Encode an `Integer` in `0..2**128 - 1`. |
|
|
131
|
+
| `Uuid58.decode(str) -> String` | Decode to the lowercase hyphenated UUID string. |
|
|
132
|
+
| `Uuid58.decode_bytes(str) -> String` | Decode to 16 big-endian bytes (`Encoding::BINARY`). |
|
|
133
|
+
| `Uuid58.decode_int(str) -> Integer` | Decode to an `Integer` in `0..2**128 - 1`. |
|
|
134
|
+
| `Uuid58.valid?(str)`, `Uuid58.uuid58?` | `true` exactly when `decode(str)` would succeed. Never raises. |
|
|
135
|
+
| `Uuid58.generate -> String` | Generate a random UUIDv4 (`SecureRandom`) and return its encoding. |
|
|
136
|
+
| `ALPHABET`, `MAX_UUID58`, `MAX_INT` | The Base58 alphabet, the largest valid uuid58 string, and `2**128 - 1`. |
|
|
137
|
+
|
|
138
|
+
### Accepted UUID strings
|
|
139
|
+
|
|
140
|
+
`encode` accepts exactly two textual forms, in any letter case
|
|
141
|
+
([SPEC.md Section 5.1](https://github.com/nakanoasaservice/uuid58/blob/main/spec/SPEC.md#51-accepted-forms)):
|
|
142
|
+
|
|
143
|
+
- hyphenated, 36 characters: `f4b247fd-1f87-45d4-aa06-1c6fc0a8dfaf`
|
|
144
|
+
- plain, 32 hex digits: `f4b247fd1f8745d4aa061c6fc0a8dfaf`
|
|
145
|
+
|
|
146
|
+
Everything else is rejected: braces, the `urn:uuid:` prefix, misplaced
|
|
147
|
+
hyphens, and surrounding whitespace or newlines.
|
|
148
|
+
|
|
149
|
+
## Compatibility
|
|
150
|
+
|
|
151
|
+
This gem implements
|
|
152
|
+
[uuid58 spec 1.1.0](https://github.com/nakanoasaservice/uuid58/blob/main/spec/SPEC.md)
|
|
153
|
+
and passes every case in
|
|
154
|
+
[`spec/vectors.json`](https://github.com/nakanoasaservice/uuid58/blob/main/spec/vectors.json)
|
|
155
|
+
in CI. A string encoded here decodes to the same UUID with every other
|
|
156
|
+
[uuid58 implementation](https://github.com/nakanoasaservice/uuid58#install),
|
|
157
|
+
and the reverse.
|
|
158
|
+
|
|
159
|
+
## Development
|
|
160
|
+
|
|
161
|
+
Uses Ruby from [mise](https://mise.jdx.dev/) (pinned via `mise.toml`).
|
|
162
|
+
|
|
163
|
+
```bash
|
|
164
|
+
bundle install
|
|
165
|
+
bundle exec rake test # tests, including spec/vectors.json conformance
|
|
166
|
+
bundle exec rake build # build pkg/uuid58-x.y.z.gem
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
The conformance tests read `../spec/vectors.json`, so run them from a
|
|
170
|
+
checkout of the repository.
|
|
171
|
+
|
|
172
|
+
## License
|
|
173
|
+
|
|
174
|
+
MIT. See
|
|
175
|
+
[LICENSE](https://github.com/nakanoasaservice/uuid58/blob/main/LICENSE).
|
data/lib/uuid58.rb
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "securerandom"
|
|
4
|
+
require_relative "uuid58/version"
|
|
5
|
+
|
|
6
|
+
# Encode UUIDs as 22-character, order-preserving Base58 strings.
|
|
7
|
+
#
|
|
8
|
+
# Implements the uuid58 specification:
|
|
9
|
+
# https://github.com/nakanoasaservice/uuid58/blob/main/spec/SPEC.md
|
|
10
|
+
#
|
|
11
|
+
# Uuid58.encode("f4b247fd-1f87-45d4-aa06-1c6fc0a8dfaf") # => "XDY9dmBbcMBXqcRvYw8xJ2"
|
|
12
|
+
# Uuid58.decode("XDY9dmBbcMBXqcRvYw8xJ2") # => "f4b247fd-1f87-45d4-aa06-1c6fc0a8dfaf"
|
|
13
|
+
#
|
|
14
|
+
# Every check works on the bytes of the string, so any byte 0x80 or above
|
|
15
|
+
# (any non-ASCII character, or ill-formed text) is rejected, whatever the
|
|
16
|
+
# string's encoding claims (SPEC.md Section 4.1).
|
|
17
|
+
module Uuid58
|
|
18
|
+
# The Bitcoin Base58 alphabet, in ascending ASCII order (SPEC.md Section 2).
|
|
19
|
+
ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
|
|
20
|
+
|
|
21
|
+
# The largest valid uuid58 string, the encoding of 2**128 - 1.
|
|
22
|
+
MAX_UUID58 = "YcVfxkQb6JRzqk5kF2tNLv" # cspell:disable-line
|
|
23
|
+
|
|
24
|
+
# The largest 128-bit value.
|
|
25
|
+
MAX_INT = (1 << 128) - 1
|
|
26
|
+
|
|
27
|
+
# Base class for every error raised for invalid input. Inspect #kind, or
|
|
28
|
+
# rescue a subclass, to tell the spec error kinds (SPEC.md Section 7) apart.
|
|
29
|
+
# Error messages are not part of the specification and may change.
|
|
30
|
+
class Error < ArgumentError
|
|
31
|
+
# The spec error kind: :invalid_length, :invalid_character or :overflow.
|
|
32
|
+
def kind
|
|
33
|
+
self.class::KIND
|
|
34
|
+
end
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
# The input has the wrong length (+:invalid_length+).
|
|
38
|
+
class InvalidLengthError < Error
|
|
39
|
+
KIND = :invalid_length
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
# The input contains a character not allowed in its position
|
|
43
|
+
# (+:invalid_character+).
|
|
44
|
+
class InvalidCharacterError < Error
|
|
45
|
+
KIND = :invalid_character
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
# The value is outside 0..2**128 - 1 (+:overflow+).
|
|
49
|
+
class OverflowError < Error
|
|
50
|
+
KIND = :overflow
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
ENCODED_LENGTH = 22
|
|
54
|
+
private_constant :ENCODED_LENGTH
|
|
55
|
+
|
|
56
|
+
# Byte -> digit value, nil for bytes outside the alphabet (incl. >= 0x80).
|
|
57
|
+
DIGIT_VALUES = Array.new(256).tap do |table|
|
|
58
|
+
ALPHABET.each_byte.with_index { |byte, i| table[byte] = i }
|
|
59
|
+
end.freeze
|
|
60
|
+
private_constant :DIGIT_VALUES
|
|
61
|
+
|
|
62
|
+
HEX_DIGIT = Array.new(256, false).tap do |table|
|
|
63
|
+
"0123456789abcdefABCDEF".each_byte { |byte| table[byte] = true }
|
|
64
|
+
end.freeze
|
|
65
|
+
private_constant :HEX_DIGIT
|
|
66
|
+
|
|
67
|
+
HYPHEN = "-".ord
|
|
68
|
+
HYPHEN_POSITIONS = [8, 13, 18, 23].freeze
|
|
69
|
+
private_constant :HYPHEN, :HYPHEN_POSITIONS
|
|
70
|
+
|
|
71
|
+
module_function
|
|
72
|
+
|
|
73
|
+
# Encodes a UUID as a 22-character uuid58 string.
|
|
74
|
+
#
|
|
75
|
+
# +value+ may be:
|
|
76
|
+
# - a UUID string, hyphenated (+f4b247fd-1f87-45d4-aa06-1c6fc0a8dfaf+) or
|
|
77
|
+
# plain (32 hex digits), in any letter case. Nothing else is accepted: no
|
|
78
|
+
# braces, +urn:uuid:+ prefix, whitespace or misplaced hyphens;
|
|
79
|
+
# - a binary string (Encoding::BINARY, e.g. from Array#pack or a +bytea+
|
|
80
|
+
# column) of exactly 16 bytes, big-endian. See #encode_bytes;
|
|
81
|
+
# - an Integer in 0..2**128 - 1.
|
|
82
|
+
#
|
|
83
|
+
# Raises InvalidLengthError, InvalidCharacterError or OverflowError for
|
|
84
|
+
# invalid input, and TypeError for any other type.
|
|
85
|
+
def encode(value)
|
|
86
|
+
case value
|
|
87
|
+
when Integer
|
|
88
|
+
encode_int(value)
|
|
89
|
+
when String
|
|
90
|
+
if value.encoding == Encoding::BINARY
|
|
91
|
+
encode_bytes(value)
|
|
92
|
+
else
|
|
93
|
+
encode_uint128(parse_uuid(value))
|
|
94
|
+
end
|
|
95
|
+
else
|
|
96
|
+
raise TypeError, "Uuid58.encode expects a String or Integer, not #{value.class}"
|
|
97
|
+
end
|
|
98
|
+
end
|
|
99
|
+
|
|
100
|
+
# Encodes 16 raw bytes (big-endian) whatever the string's encoding.
|
|
101
|
+
# Raises InvalidLengthError unless +bytes+ is exactly 16 bytes long.
|
|
102
|
+
def encode_bytes(bytes)
|
|
103
|
+
raise TypeError, "expected a String, not #{bytes.class}" unless bytes.is_a?(String)
|
|
104
|
+
if bytes.bytesize != 16
|
|
105
|
+
raise InvalidLengthError, "Invalid UUID bytes: expected 16 bytes, got #{bytes.bytesize}"
|
|
106
|
+
end
|
|
107
|
+
|
|
108
|
+
encode_uint128(bytes.unpack1("H32").to_i(16))
|
|
109
|
+
end
|
|
110
|
+
|
|
111
|
+
# Encodes an Integer in 0..2**128 - 1. Raises OverflowError otherwise.
|
|
112
|
+
def encode_int(int)
|
|
113
|
+
raise TypeError, "expected an Integer, not #{int.class}" unless int.is_a?(Integer)
|
|
114
|
+
unless int.between?(0, MAX_INT)
|
|
115
|
+
raise OverflowError, "Integer out of range for a 128-bit UUID"
|
|
116
|
+
end
|
|
117
|
+
|
|
118
|
+
encode_uint128(int)
|
|
119
|
+
end
|
|
120
|
+
|
|
121
|
+
# Decodes a uuid58 string to a lowercase, hyphenated UUID string.
|
|
122
|
+
#
|
|
123
|
+
# Raises InvalidLengthError, InvalidCharacterError or OverflowError for
|
|
124
|
+
# invalid input, and TypeError for a non-String.
|
|
125
|
+
def decode(str)
|
|
126
|
+
hex = decode_int(str).to_s(16).rjust(32, "0")
|
|
127
|
+
"#{hex[0, 8]}-#{hex[8, 4]}-#{hex[12, 4]}-#{hex[16, 4]}-#{hex[20, 12]}"
|
|
128
|
+
end
|
|
129
|
+
|
|
130
|
+
# Decodes a uuid58 string to 16 big-endian bytes (Encoding::BINARY).
|
|
131
|
+
# Raises the same errors as #decode.
|
|
132
|
+
def decode_bytes(str)
|
|
133
|
+
[decode_int(str).to_s(16).rjust(32, "0")].pack("H32")
|
|
134
|
+
end
|
|
135
|
+
|
|
136
|
+
# Decodes a uuid58 string to an Integer in 0..2**128 - 1.
|
|
137
|
+
# Raises the same errors as #decode.
|
|
138
|
+
#
|
|
139
|
+
# Checks length, then characters, then range (SPEC.md Section 4).
|
|
140
|
+
def decode_int(str)
|
|
141
|
+
raise TypeError, "expected a String, not #{str.class}" unless str.is_a?(String)
|
|
142
|
+
|
|
143
|
+
str = ascii_compatible(str)
|
|
144
|
+
# Length in bytes: for non-ASCII input this may report :invalid_length
|
|
145
|
+
# instead of :invalid_character, which SPEC.md Section 4.1 allows.
|
|
146
|
+
if str.bytesize != ENCODED_LENGTH
|
|
147
|
+
raise InvalidLengthError,
|
|
148
|
+
"Invalid uuid58 length: expected #{ENCODED_LENGTH} characters, " \
|
|
149
|
+
"got #{str.bytesize} bytes"
|
|
150
|
+
end
|
|
151
|
+
|
|
152
|
+
value = 0
|
|
153
|
+
str.each_byte.with_index do |byte, pos|
|
|
154
|
+
digit = DIGIT_VALUES[byte]
|
|
155
|
+
raise InvalidCharacterError, "Invalid uuid58 character at byte #{pos}" if digit.nil?
|
|
156
|
+
|
|
157
|
+
value = (value * 58) + digit
|
|
158
|
+
end
|
|
159
|
+
raise OverflowError, "uuid58 value exceeds 128 bits" if value > MAX_INT
|
|
160
|
+
|
|
161
|
+
value
|
|
162
|
+
end
|
|
163
|
+
|
|
164
|
+
# Returns true exactly when #decode would succeed on +str+. Never raises;
|
|
165
|
+
# any non-String returns false.
|
|
166
|
+
def valid?(str)
|
|
167
|
+
# Same length and alphabet, so byte order equals numeric order
|
|
168
|
+
# (SPEC.md Section 3.2) and comparing with MAX_UUID58 checks the range.
|
|
169
|
+
return false unless str.is_a?(String)
|
|
170
|
+
|
|
171
|
+
str = ascii_compatible(str)
|
|
172
|
+
str.bytesize == ENCODED_LENGTH &&
|
|
173
|
+
str.each_byte.all? { |byte| DIGIT_VALUES[byte] } &&
|
|
174
|
+
str.b <= MAX_UUID58
|
|
175
|
+
rescue Error
|
|
176
|
+
false
|
|
177
|
+
end
|
|
178
|
+
|
|
179
|
+
# Generates a random (version 4) UUID and returns its uuid58 encoding.
|
|
180
|
+
def generate
|
|
181
|
+
encode_uint128(SecureRandom.uuid.delete("-").to_i(16))
|
|
182
|
+
end
|
|
183
|
+
|
|
184
|
+
class << self
|
|
185
|
+
alias_method :uuid58?, :valid?
|
|
186
|
+
end
|
|
187
|
+
|
|
188
|
+
def encode_uint128(value)
|
|
189
|
+
out = Array.new(ENCODED_LENGTH)
|
|
190
|
+
(ENCODED_LENGTH - 1).downto(0) do |i|
|
|
191
|
+
value, digit = value.divmod(58)
|
|
192
|
+
out[i] = ALPHABET[digit]
|
|
193
|
+
end
|
|
194
|
+
out.join
|
|
195
|
+
end
|
|
196
|
+
|
|
197
|
+
# Parses the hyphenated or plain UUID form strictly (SPEC.md Section 5.1),
|
|
198
|
+
# byte by byte. String#to_i(16) alone is not used for validation: it
|
|
199
|
+
# accepts signs, underscores and trailing garbage.
|
|
200
|
+
def parse_uuid(str)
|
|
201
|
+
str = ascii_compatible(str)
|
|
202
|
+
bytes = str.bytes
|
|
203
|
+
case bytes.size
|
|
204
|
+
when 36
|
|
205
|
+
HYPHEN_POSITIONS.each do |pos|
|
|
206
|
+
raise InvalidCharacterError, "Invalid UUID: expected '-' at byte #{pos}" unless bytes[pos] == HYPHEN
|
|
207
|
+
end
|
|
208
|
+
hyphens = HYPHEN_POSITIONS
|
|
209
|
+
when 32
|
|
210
|
+
hyphens = []
|
|
211
|
+
else
|
|
212
|
+
raise InvalidLengthError,
|
|
213
|
+
"Invalid UUID length: expected 32 or 36 characters, got #{bytes.size} bytes"
|
|
214
|
+
end
|
|
215
|
+
bytes.each_with_index do |byte, pos|
|
|
216
|
+
next if HEX_DIGIT[byte] || hyphens.include?(pos)
|
|
217
|
+
|
|
218
|
+
raise InvalidCharacterError, "Invalid UUID: expected a hexadecimal digit at byte #{pos}"
|
|
219
|
+
end
|
|
220
|
+
hyphens.reverse_each { |pos| bytes.delete_at(pos) }
|
|
221
|
+
|
|
222
|
+
bytes.pack("C*").to_i(16)
|
|
223
|
+
end
|
|
224
|
+
|
|
225
|
+
# Strings in an encoding that is not ASCII-compatible (UTF-16, UTF-32) are
|
|
226
|
+
# transcoded to UTF-8 so their bytes can be checked like any other string.
|
|
227
|
+
# Ill-formed ones (e.g. a lone surrogate) are rejected as non-ASCII.
|
|
228
|
+
def ascii_compatible(str)
|
|
229
|
+
return str if str.encoding.ascii_compatible?
|
|
230
|
+
|
|
231
|
+
str.encode(Encoding::UTF_8)
|
|
232
|
+
rescue EncodingError
|
|
233
|
+
raise InvalidCharacterError, "Invalid character: ill-formed #{str.encoding} string"
|
|
234
|
+
end
|
|
235
|
+
|
|
236
|
+
private_class_method :encode_uint128, :parse_uuid, :ascii_compatible
|
|
237
|
+
end
|
metadata
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
|
2
|
+
name: uuid58
|
|
3
|
+
version: !ruby/object:Gem::Version
|
|
4
|
+
version: 0.1.0
|
|
5
|
+
platform: ruby
|
|
6
|
+
authors:
|
|
7
|
+
- Nakano as a Service
|
|
8
|
+
bindir: bin
|
|
9
|
+
cert_chain: []
|
|
10
|
+
date: 1980-01-02 00:00:00.000000000 Z
|
|
11
|
+
dependencies: []
|
|
12
|
+
description: Shorten UUIDs to 22-character Base58 strings, and back. URL-safe, order-preserving,
|
|
13
|
+
and identical across languages under a stable, well-tested spec.
|
|
14
|
+
executables: []
|
|
15
|
+
extensions: []
|
|
16
|
+
extra_rdoc_files: []
|
|
17
|
+
files:
|
|
18
|
+
- LICENSE
|
|
19
|
+
- README.md
|
|
20
|
+
- lib/uuid58.rb
|
|
21
|
+
- lib/uuid58/version.rb
|
|
22
|
+
homepage: https://nakanoasaservice.github.io/uuid58/
|
|
23
|
+
licenses:
|
|
24
|
+
- MIT
|
|
25
|
+
metadata:
|
|
26
|
+
homepage_uri: https://nakanoasaservice.github.io/uuid58/
|
|
27
|
+
source_code_uri: https://github.com/nakanoasaservice/uuid58/tree/main/ruby
|
|
28
|
+
bug_tracker_uri: https://github.com/nakanoasaservice/uuid58/issues
|
|
29
|
+
rubygems_mfa_required: 'true'
|
|
30
|
+
rdoc_options: []
|
|
31
|
+
require_paths:
|
|
32
|
+
- lib
|
|
33
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
|
34
|
+
requirements:
|
|
35
|
+
- - ">="
|
|
36
|
+
- !ruby/object:Gem::Version
|
|
37
|
+
version: '3.2'
|
|
38
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
|
39
|
+
requirements:
|
|
40
|
+
- - ">="
|
|
41
|
+
- !ruby/object:Gem::Version
|
|
42
|
+
version: '0'
|
|
43
|
+
requirements: []
|
|
44
|
+
rubygems_version: 4.0.20
|
|
45
|
+
specification_version: 4
|
|
46
|
+
summary: Shorten UUIDs to 22-character Base58 strings, and back.
|
|
47
|
+
test_files: []
|