Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
karthick-vinod authored and tholka-hypto committed Nov 25, 2021
0 parents commit d771304
Show file tree
Hide file tree
Showing 15 changed files with 380 additions and 0 deletions.
11 changes: 11 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/.bundle/
/.yardoc
/_yardoc/
/coverage/
/doc/
/pkg/
/spec/reports/
/tmp/

# rspec failure tracking
.rspec_status
3 changes: 3 additions & 0 deletions .rspec
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
--format documentation
--color
--require spec_helper
24 changes: 24 additions & 0 deletions .rubocop.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
AllCops:
TargetRubyVersion: 2.5
NewCops: enable

Style/StringLiterals:
Enabled: true
EnforcedStyle: single_quotes

Style/StringLiteralsInInterpolation:
Enabled: true
EnforcedStyle: double_quotes

Style/ClassAndModuleChildren:
Enabled: true
EnforcedStyle: compact

Style/RedundantSelf:
Enabled: false

Layout/LineLength:
Max: 120

Metrics/AbcSize:
Max: 20
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
## [Unreleased]

## [0.1.0] - 2021-11-21

- Initial release
12 changes: 12 additions & 0 deletions Gemfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# frozen_string_literal: true

source 'https://rubygems.org'

# Specify your gem's dependencies in lsuuid.gemspec
gemspec

gem 'rake', '~> 13.0'

gem 'rspec', '~> 3.0'

gem 'rubocop', '~> 1.7'
21 changes: 21 additions & 0 deletions LICENSE.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2021 Karthick

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
113 changes: 113 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
# LSUUID (Lexicographically Sortable Universally Unique Identifier)

LSUUID is a lexicographically sortable identifier with format similar to UUIDv4.
UUID has some limitations which are already listed and addressed by [ULID](https://github.com/ulid/spec).

LSUUID provides the following improvements over ulid :-
- The timestamp component in ulid is in milliseconds whereas LSUUID uses nanoseconds so that chance of collision is reduced 1000 times
- Ability to bucket the generated identifiers with a prefix is provided by LSUUID
- LSUUID adheres to the UUIDv4 format there by allowing the storage of the identifier in the UUID datatype of data stores which is more efficient than a string which is required for ulid.

*Note: For use cases where format of the identifier is not a matter of concern, using ULID over LSUUID might be a better choice.*

## Specification
Below is the structure of LSUUID.

**Without Prefix:**
```
Sample LSUUID: 619bd0ef-2a04-5068-d3c4-f6fac6809edb
619bd0ef-2a04-5068- d3c4-f6fac6809edb
|------------------| |-----------------|
Timestamp Randomness
64bits 64bits
```

**With Prefix:**
```
Sample LSUUID: 619bd0ef-2a04-5068-d3c4-f6fac6809edb
619bd0 ef-2a04-5068-d3c4-f6 fac6809edb
|------| |--------------------| |----------|
Prefix Timestamp Randomness
24bits 64bits 40bits
```

### Components:

**Timestamp**
- 64 bit integer
- UNIX-time in nanoseconds

**Randomness**
- 64 bits (40 bits in case a prefix is specified)
- Cryptographically secure source of randomness, if possible

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'lsuuid'
```

And then execute:

$ bundle install

Or install it yourself as:

$ gem install lsuuid

## Usage

### Generate a UUID:
```ruby
irb(main):001:0> LSUUID.generate
=> "619bd0ef-2a04-5068-d3c4-f6fac6809edb"
```
Generates a UUID based on the method call time.
### Timestamp specific UUIDs:
```ruby
irb(main):001:0> t = Time.now
=> 2021-11-22 22:49:02 +0530
irb(main):002:0> LSUUID.generate(time: t)
=> "619bd106-0c6b-ba28-7811-f5787dab02d4"
```
### Modes:
#### **ceil**
```ruby
irb(main):001:0> LSUUID.generate(time: t, mode: :ceil)
=> "619bd106-0c6b-ba28-ffff-ffffffffffff"
irb(main):002:0> LSUUID.generate(time: t, mode: :ceil, prefix: 0)
=> "00000061-9bd1-060c-6bba-28ffffffffff"
```

#### **floor**
```ruby
irb(main):001:0> LSUUID.generate(time: t, mode: :floor)
=> "619bd106-0c6b-ba28-0000-000000000000"
irb(main):002:0> LSUUID.generate(time: t, mode: :ceil, prefix: 0)
=> "00000061-9bd1-060c-6bba-280000000000"
```

### Prefix
```ruby
irb(main):001:0> LSUUID.generate(prefix: 0, time: t)
=> "00000061-9bd1-060c-6bba-28428c7e196d"
irb(main):002:0> LSUUID.generate(prefix: 1000, time: t)
=> "0003e861-9bd1-060c-6bba-28d9cb973352"
irb(main):003:0> LSUUID.generate(prefix: 16_777_215, time: t)
=> "ffffff61-9bd1-060c-6bba-2826264c51e0"
```
**Note:** Prefix can be an integer between 0 and 16,777,215

## Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/hwslabs/lsuuid.

## License

The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
12 changes: 12 additions & 0 deletions Rakefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# frozen_string_literal: true

require 'bundler/gem_tasks'
require 'rspec/core/rake_task'

RSpec::Core::RakeTask.new(:spec)

require 'rubocop/rake_task'

RuboCop::RakeTask.new

task default: %i[spec rubocop]
15 changes: 15 additions & 0 deletions bin/console
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#!/usr/bin/env ruby
# frozen_string_literal: true

require 'bundler/setup'
require 'lsuuid'

# You can add fixtures and/or initialization code here to make experimenting
# with your gem easier. You can also use a different console, if you like.

# (If you use this, don't forget to add pry to your Gemfile!)
# require 'pry'
# Pry.start

require 'irb'
IRB.start(__FILE__)
8 changes: 8 additions & 0 deletions bin/setup
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'
set -vx

bundle install

# Do any other automated setup that you need to do here
52 changes: 52 additions & 0 deletions lib/lsuuid.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# frozen_string_literal: true

require_relative 'lsuuid/version'

if RUBY_VERSION >= '2.5'
require 'securerandom'
else
require 'sysrandom/securerandom'
end

module LSUUID # :nodoc:
PREFIX_LEN = 6
PAD_CHAR = '0'
FLOOR_CHAR = '0'
CEIL_CHAR = 'f'
DEFAULT_RAND_LEN = 16

class << self
# We allow 6 chars (24 bits) of UUID to be customizable as per requirement.
def generate(prefix: nil, time: Time.now, mode: :random)
prefix_hex = validate_prefix_and_get_hex(prefix)
result = prefix_hex +
time.to_i.to_s(16).rjust(8, PAD_CHAR) + time.nsec.to_s(16).rjust(8, PAD_CHAR) +
random_hex(prefix_hex, mode)
[result[0..7], result[8..11], result[12..15], result[16..19], result[20..31]].join('-')
end

private

def random_hex(prefix_hex, mode)
rand_len = DEFAULT_RAND_LEN - prefix_hex.size
case mode
when :random then SecureRandom.hex(rand_len / 2)
when :ceil then ''.rjust(rand_len, CEIL_CHAR)
when :floor then ''.rjust(rand_len, FLOOR_CHAR)
else raise "Unknown mode [#{mode}]"
end
end

def validate_prefix_and_get_hex(prefix)
return '' if prefix.nil?

raise "Expecting integer Got #{prefix.class.name}" unless prefix.is_a? Integer

if (prefix > 16_777_215) || prefix.negative?
raise "Integer prefix out of range. Allowed: min - 0, max - 16,777,215 (hex: ffffff). Got: #{prefix}."
end

prefix.to_s(16).rjust(PREFIX_LEN, PAD_CHAR)
end
end
end
5 changes: 5 additions & 0 deletions lib/lsuuid/version.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# frozen_string_literal: true

module LSUUID
VERSION = '0.1.0'
end
40 changes: 40 additions & 0 deletions lsuuid.gemspec
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# frozen_string_literal: true

require_relative 'lib/lsuuid/version'

Gem::Specification.new do |spec|
spec.name = 'lsuuid'
spec.version = LSUUID::VERSION
spec.authors = ['Hypto Engineering Team']
spec.email = ['engineering@hypto.in']

spec.summary = 'Universally Unique Lexicographically Sortable Identifier'
spec.description = 'Universally Unique Lexicographically Sortable Identifier'
spec.homepage = 'https://github.com/hwslabs/lsuuid'
spec.license = 'MIT'
spec.required_ruby_version = '>= 2.4.0'

# spec.metadata['allowed_push_host'] = 'TODO: Set to 'https://mygemserver.com''

spec.metadata['homepage_uri'] = spec.homepage
spec.metadata['source_code_uri'] = 'https://github.com/hwslabs/lsuuid'
spec.metadata['changelog_uri'] = 'https://github.com/hwslabs/lsuuid/blob/main/CHANGELOG.md'
spec.metadata['rubygems_mfa_required'] = 'true'

# Specify which files should be added to the gem when it is released.
# The `git ls-files -z` loads the files in the RubyGem that have been added into git.
spec.files = Dir.chdir(File.expand_path(__dir__)) do
`git ls-files -z`.split("\x0").reject do |f|
(f == __FILE__) || f.match(%r{\A(?:(?:test|spec|features)/|\.(?:git|travis|circleci)|appveyor)})
end
end
spec.bindir = 'exe'
spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
spec.require_paths = ['lib']

# Uncomment to register a new dependency of your gem
# spec.add_dependency "example-gem", "~> 1.0"

# For more information and examples about making a new gem, checkout our
# guide at: https://bundler.io/guides/creating_gem.html
end
44 changes: 44 additions & 0 deletions spec/lsuuid_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# frozen_string_literal: true

UUID_REGEXP = /\A[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\z/i.freeze

RSpec.describe LSUUID do # rubocop:disable Metrics/BlockLength
it 'has a version number' do
expect(LSUUID::VERSION).not_to be nil
end

it 'should generate identifier in a valid UUID format' do
lsuuid = LSUUID.generate
expect(lsuuid.size).to eq(36)
expect(!(UUID_REGEXP =~ lsuuid).nil?).to eq(true)
end

it 'should generate least possible uuid for given params in floor mode' do
lsuuid = LSUUID.generate(mode: :floor)
expect(lsuuid[26..-1]).to eq('0000000000')
end

it 'should generate highest possible uuid for given params in ceil mode' do
lsuuid = LSUUID.generate(mode: :ceil)
expect(lsuuid[26..-1]).to eq('ffffffffff')
end

it 'should generate uuid with first 6 chars as 0s for prefix 0 ' do
lsuuid = LSUUID.generate(prefix: 0)
expect(lsuuid[0..5]).to eq('000000')
end

it 'should generate uuid with first 6 chars as fs for max prefix[16_777_215]' do
lsuuid = LSUUID.generate(prefix: 16_777_215)
expect(lsuuid[0..5]).to eq('ffffff')
end

it 'should generate same identifier for same input except for random suffix' do
time = Time.now
test_prefix = 15_332
lsuuid1 = LSUUID.generate(prefix: test_prefix, time: time, mode: :random)
lsuuid2 = LSUUID.generate(prefix: test_prefix, time: time, mode: :random)
expect(lsuuid1[0..25]).to eq(lsuuid2[0..25])
expect(lsuuid1[26..-1]).not_to eq(lsuuid2[26..-1])
end
end
15 changes: 15 additions & 0 deletions spec/spec_helper.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# frozen_string_literal: true

require 'lsuuid'

RSpec.configure do |config|
# Enable flags like --only-failures and --next-failure
config.example_status_persistence_file_path = '.rspec_status'

# Disable RSpec exposing methods globally on `Module` and `main`
config.disable_monkey_patching!

config.expect_with :rspec do |c|
c.syntax = :expect
end
end

0 comments on commit d771304

Please sign in to comment.