Skip to content

Commit

Permalink
Fix nanoid error
Browse files Browse the repository at this point in the history
  • Loading branch information
drexed committed Sep 20, 2024
1 parent 97f0106 commit e2cffdd
Show file tree
Hide file tree
Showing 5 changed files with 33 additions and 8 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

## [1.5.2] - 2024-09-20
### Changed
- Fixed nanoid of differing length error

## [1.5.1] - 2024-09-20
### Changed
- Use after commit on create instead of after create
Expand Down
2 changes: 1 addition & 1 deletion Gemfile.lock
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
PATH
remote: .
specs:
lite-uxid (1.5.1)
lite-uxid (1.5.2)

GEM
remote: https://rubygems.org/
Expand Down
4 changes: 0 additions & 4 deletions lib/lite/uxid/base/irreversible.rb
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,6 @@ def coder_value_for(key)
opts.delete(key) || Lite::Uxid.configuration.send(sym_key)
end

def coder_bytes
@coder_bytes ||= SecureRandom.random_bytes(coder_size).bytes
end

def coder_charset
@coder_charset ||= coder_value_for(:charset)
end
Expand Down
29 changes: 27 additions & 2 deletions lib/lite/uxid/nanoid.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,38 @@ module Uxid
class Nanoid < Base::Irreversible

def encode
uxid = (0...coder_size).each_with_object(+"") do |i, str|
str << coder_charset[coder_bytes[i] & 63]
uxid = +""

loop do
cached_bytes = bytes

(0...step).each do |idx|
byte = cached_bytes[idx] & mask
char = byte && coder_charset[byte]
next unless char

uxid << char
return uxid if uxid.size == coder_size
end
end

"#{coder_prefix}#{uxid}"
end

private

def bytes
SecureRandom.random_bytes(coder_size).bytes
end

def mask
@mask ||= (2 << (Math.log(coder_length - 1) / Math.log(2))) - 1
end

def step
@step = (1.6 * mask * coder_size / coder_length).ceil
end

end
end
end
2 changes: 1 addition & 1 deletion lib/lite/uxid/version.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
module Lite
module Uxid

VERSION = "1.5.1"
VERSION = "1.5.2"

end
end

0 comments on commit e2cffdd

Please sign in to comment.