anybase 0.0.15 → 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
- SHA1:
3
- metadata.gz: d0a553c5494e6bec8b36fe351538873d77a6649b
4
- data.tar.gz: dabf637b3b92b006fe73ccbd94fe3c39933f68b4
2
+ SHA256:
3
+ metadata.gz: 5baa56322ae7a48da69d9f80ef11027fc165be8d1dc74b499bdf72963be7db6b
4
+ data.tar.gz: 91b9f90581a14d77d46fff1e37027da986aa00cf337b7f8aedaa984253321c4f
5
5
  SHA512:
6
- metadata.gz: 8d9a45c0289ff82c8ce0630279bfc54322ae29f7a089ee29f7b0ca3ab8294447afebb93174fefbc224c355685b5f248b9da03ef138f75b188ae1fbe1ebc1eaca
7
- data.tar.gz: 870ceff52e3ad3d304af5eae2cc1aac33327389f474f61ccaf8a3460117e55cfda4d1ff616d7cc95383aa0b27c037170c84873a75f58a89222b2a4bcac65fa58
6
+ metadata.gz: dd0b37c4a057f5933b852af5239a1c8f5eb80a494e09790adaf069c4e14b6d2f649ba53598e7d1851bfbc2c2f62dedb735d818c113b810011d9406f134236b45
7
+ data.tar.gz: a0c12647a67196ecb55519a68ecbf1c198f9401af6940099fbb9600d007bcb193a5e78b1293f29c95e00b33d9f8fdf264777efa07661198bd41e7aba8f00d25f
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,186 @@
1
+ require:
2
+ - rubocop-performance
3
+
4
+ AllCops:
5
+ TargetRubyVersion: 2.0
6
+ DisplayCopNames: true
7
+ DisplayStyleGuide: true
8
+ SuggestExtensions: false
9
+ NewCops: enable
10
+ Exclude:
11
+ - "tmp/*"
12
+ - "vendor/**/*"
13
+
14
+ Gemspec/RequiredRubyVersion:
15
+ Enabled: true
16
+
17
+ Layout/ArgumentAlignment:
18
+ EnforcedStyle: with_fixed_indentation
19
+
20
+ Layout/ArrayAlignment:
21
+ Enabled: false
22
+
23
+ Layout/BlockEndNewline:
24
+ Enabled: true
25
+
26
+ Layout/CaseIndentation:
27
+ EnforcedStyle: end
28
+
29
+ Layout/DotPosition:
30
+ Enabled: false
31
+
32
+ Layout/EmptyLineAfterGuardClause:
33
+ Enabled: false
34
+
35
+ Layout/EmptyLinesAroundBlockBody:
36
+ Enabled: true
37
+
38
+ Layout/EmptyLineBetweenDefs:
39
+ Enabled: true
40
+ AllowAdjacentOneLineDefs: true
41
+
42
+ Layout/EndAlignment:
43
+ EnforcedStyleAlignWith: variable
44
+
45
+ Layout/HashAlignment:
46
+ Enabled: false
47
+
48
+ Layout/LeadingCommentSpace:
49
+ Enabled: false
50
+
51
+ Layout/LineEndStringConcatenationIndentation:
52
+ EnforcedStyle: indented
53
+
54
+ Layout/LineLength:
55
+ Enabled: false
56
+
57
+ Layout/ParameterAlignment:
58
+ Enabled: false
59
+
60
+ Layout/RescueEnsureAlignment:
61
+ Enabled: false
62
+
63
+ Style/SingleLineBlockParams:
64
+ Enabled: false
65
+
66
+ Layout/SpaceAfterComma:
67
+ Enabled: false
68
+
69
+ Layout/SpaceBeforeFirstArg:
70
+ Enabled: false
71
+
72
+ Lint/AssignmentInCondition:
73
+ AllowSafeAssignment: true
74
+
75
+ Lint/DuplicateBranch:
76
+ Enabled: false
77
+
78
+ Lint/EmptyClass:
79
+ AllowComments: true
80
+
81
+ Lint/EmptyWhen:
82
+ Enabled: false
83
+
84
+ Lint/SuppressedException:
85
+ Enabled: false
86
+
87
+ Metrics/AbcSize:
88
+ Enabled: false
89
+
90
+ Metrics/BlockLength:
91
+ Enabled: false
92
+
93
+ Metrics/BlockNesting:
94
+ Enabled: false
95
+
96
+ Metrics/ClassLength:
97
+ Enabled: false
98
+
99
+ Metrics/CyclomaticComplexity:
100
+ Enabled: false
101
+
102
+ Metrics/MethodLength:
103
+ Enabled: false
104
+
105
+ Metrics/ModuleLength:
106
+ Enabled: false
107
+
108
+ Metrics/ParameterLists:
109
+ Enabled: false
110
+
111
+ Metrics/PerceivedComplexity:
112
+ Enabled: false
113
+
114
+ Naming/AccessorMethodName:
115
+ Enabled: false
116
+
117
+ Performance/Casecmp:
118
+ Enabled: false
119
+
120
+ Performance/RedundantMerge:
121
+ Enabled: true
122
+ MaxKeyValuePairs: 1
123
+
124
+ Performance/RedundantStringChars:
125
+ Enabled: false
126
+
127
+ Style/AsciiComments:
128
+ Enabled: false
129
+
130
+ Style/BlockDelimiters:
131
+ Enabled: false
132
+
133
+ Style/CommentAnnotation:
134
+ Enabled: false
135
+
136
+ Style/Documentation:
137
+ Enabled: false
138
+
139
+ Style/EmptyElse:
140
+ Enabled: false
141
+
142
+ Style/IfUnlessModifier:
143
+ Enabled: false
144
+
145
+ Style/MultilineTernaryOperator:
146
+ Enabled: false
147
+
148
+ Style/NegatedIf:
149
+ Enabled: false
150
+
151
+ Style/ParallelAssignment:
152
+ Enabled: false
153
+
154
+ Style/RaiseArgs:
155
+ Enabled: true
156
+
157
+ Style/Semicolon:
158
+ AllowAsExpressionSeparator: true
159
+
160
+ Style/SingleLineMethods:
161
+ Enabled: false
162
+
163
+ Style/StringLiterals:
164
+ EnforcedStyle: double_quotes
165
+
166
+ Style/StringLiteralsInInterpolation:
167
+ Enabled: false
168
+
169
+ Style/SymbolProc:
170
+ Enabled: false
171
+
172
+ Style/WordArray:
173
+ Enabled: false
174
+
175
+ ###
176
+ # In here for code supporting old versions of Ruby
177
+ ###
178
+
179
+ # Ruby 2.0 doesn't support the `+""` unary.
180
+ Performance/UnfreezeString:
181
+ Enabled: false
182
+
183
+ # Ruby 2.3 introduced the magic comment, so we need to call `String#freeze` on strings we
184
+ # care about for earlier versions (such as the Gem's VERSION string.)
185
+ Style/RedundantFreeze:
186
+ Enabled: false
data/CHANGELOG.md ADDED
@@ -0,0 +1,79 @@
1
+ # Changelog
2
+
3
+ This file tracks the notable changes made to this project. It is meant for humans to read,
4
+ and is loosely based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
5
+
6
+ ## Unreleased
7
+
8
+ [Unreleased commits](https://github.com/polleverywhere/anybase/compare/v0.1.0...HEAD)
9
+
10
+ ## 0.1.0 (2022-09-30)
11
+
12
+ There's a bunch of changes, including some breaking ones in this commit. Starting with this
13
+ release, this gem is owned and maintained by Poll Everywhere.
14
+
15
+ [0.1.0 commits](https://github.com/polleverywhere/anybase/compare/v0.0.15...v0.1.0)
16
+
17
+ ### Added
18
+
19
+ - This Changelog.
20
+ - A Code of Conduct for community contributions.
21
+ - Rubocop and the Poll Everywhere style rules.
22
+ - New gemspec metadata fields — especially the MFA requirement to submit to RubyGems.
23
+ - Modern gem defaults like "bin/consle".
24
+ - Instead of just an empty `RuntimeError`, the following errors no return to give more
25
+ information about what the error is:
26
+ + `NegativeSignListedAsDigitError`
27
+ + `NegativeSignTooLongError`
28
+ + `UnknownNegativeSignError`
29
+
30
+ ### Changed
31
+
32
+ - Ownership to Poll Everywhere (per the conversation with the previous owner](https://github.com/joshbuddy/anybase/issues/6)).
33
+ - Switch to using named parameters instead of an "opts" hash. (This means you can't pass
34
+ options using hash rockets anymore. For example `Anybase("abc", :ignore_case => true)` will
35
+ no longer work. Use `Anybase("abc", ignore_case: true)` instead.)
36
+ - The `Anybase#random` parameter named "zero_pad" was renamed to "trim_leading_zeros", and
37
+ this new parameter should be passed the opposite of value of the former. (So if you called
38
+ `random(4, zero_pad: false)` before, now call `random(4, trim_leading_zeros: true)`.)
39
+ - When intializing an `Anybase` object, the "sign" option was renamed to "negative_sign".
40
+ - Calling `Anybase#normalize` now always returns a new string.
41
+ - Use GitHub Actions instead of Travis to run CI tests.
42
+ - Updated RSpec.
43
+
44
+
45
+ ### Fixed
46
+
47
+ - Passing `ignore_case: true` modified the digits string passed in at object creation. The
48
+ code now makes a copy for its use so that user input isn't unexpectedly modified.
49
+
50
+ ### Deprecated
51
+
52
+ - Support for Ruby series that are [no longer maintained](https://www.ruby-lang.org/en/downloads/branches/).
53
+ (At the time of publication, that was any series older than Ruby 2.7.)
54
+
55
+ ### Removed
56
+
57
+ - Support for Ruby 1.9.3. You must use Ruby 2.0 or higher.
58
+
59
+
60
+ ## Previous versions
61
+
62
+ Older versions didn't keep a changelog, but here is a list along with a link to the commits
63
+ for each version:
64
+
65
+ - [0.0.15 (2016-02-11)](https://github.com/polleverywhere/anybase/compare/v0.0.14...v0.0.15)
66
+ - [0.0.14 (2011-12-20)](https://github.com/polleverywhere/anybase/compare/v0.0.13...v0.0.14)
67
+ - [0.0.13 (2011-12-20)](https://github.com/polleverywhere/anybase/compare/v0.0.12...v0.0.13)
68
+ - [0.0.12 (2011-11-18)](https://github.com/polleverywhere/anybase/compare/v0.0.11...v0.0.12)
69
+ - [0.0.11 (2010-08-07)](https://github.com/polleverywhere/anybase/compare/v0.0.10...v0.0.11)
70
+ - [0.0.10 (2010-07-26)](https://github.com/polleverywhere/anybase/compare/v0.0.9...v0.0.10)
71
+ - [0.0.9 (2010-05-17)](https://github.com/polleverywhere/anybase/compare/v0.0.8...v0.0.9)
72
+ - [0.0.8 (2010-03-15)](https://github.com/polleverywhere/anybase/compare/v0.0.7...v0.0.8)
73
+ - [0.0.7 (2010-03-01)](https://github.com/polleverywhere/anybase/compare/v0.0.6...v0.0.7)
74
+ - [0.0.6 (2010-02-02)](https://github.com/polleverywhere/anybase/compare/v0.0.5...v0.0.6)
75
+ - [0.0.5 (2010-01-24)](https://github.com/polleverywhere/anybase/compare/v0.0.4...v0.0.5)
76
+ - [0.0.4 (2010-01-24)](https://github.com/polleverywhere/anybase/compare/v0.0.3...v0.0.4)
77
+ - [0.0.3 (2009-12-10)](https://github.com/polleverywhere/anybase/compare/v0.0.2...v0.0.3)
78
+ - [0.0.2 (2009-12-03)](https://github.com/polleverywhere/anybase/compare/v0.0.1...v0.0.2)
79
+ - [0.0.1 (2009-11-21)](https://github.com/polleverywhere/anybase/releases/tag/v0.0.1)
@@ -0,0 +1,116 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a
6
+ harassment-free experience for everyone, regardless of age, body size, visible or invisible
7
+ disability, ethnicity, sex characteristics, gender identity and expression, level of
8
+ experience, education, socio-economic status, nationality, personal appearance, race,
9
+ religion, or sexual identity and orientation.
10
+
11
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse,
12
+ inclusive, and healthy community.
13
+
14
+ ## Our Standards
15
+
16
+ Examples of behavior that contributes to a positive environment for our community include:
17
+
18
+ * Demonstrating empathy and kindness toward other people
19
+ * Being respectful of differing opinions, viewpoints, and experiences
20
+ * Giving and gracefully accepting constructive feedback
21
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning
22
+ from the experience
23
+ * Focusing on what is best not just for us as individuals, but for the overall community
24
+
25
+ Examples of unacceptable behavior include:
26
+
27
+ * The use of sexualized language or imagery, and sexual attention or advances of any kind
28
+ * Trolling, insulting or derogatory comments, and personal or political attacks
29
+ * Public or private harassment
30
+ * Publishing others' private information, such as a physical or email address, without their
31
+ explicit permission
32
+ * Other conduct which could reasonably be considered inappropriate in a professional
33
+ setting
34
+
35
+ ## Enforcement Responsibilities
36
+
37
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable
38
+ behavior and will take appropriate and fair corrective action in response to any behavior
39
+ that they deem inappropriate, threatening, offensive, or harmful.
40
+
41
+ Community leaders have the right and responsibility to remove, edit, or reject comments,
42
+ commits, code, wiki edits, issues, and other contributions that are not aligned to this
43
+ Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
44
+
45
+ ## Scope
46
+
47
+ This Code of Conduct applies within all community spaces, and also applies when an
48
+ individual is officially representing the community in public spaces. Examples of
49
+ representing our community include using an official e-mail address, posting via an
50
+ official social media account, or acting as an appointed representative at an online or
51
+ offline event.
52
+
53
+ ## Enforcement
54
+
55
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the
56
+ community leaders responsible for enforcement at geeks@polleverywhere.com. All complaints
57
+ will be reviewed and investigated promptly and fairly.
58
+
59
+ All community leaders are obligated to respect the privacy and security of the reporter of
60
+ any incident.
61
+
62
+ ## Enforcement Guidelines
63
+
64
+ Community leaders will follow these Community Impact Guidelines in determining the
65
+ consequences for any action they deem in violation of this Code of Conduct:
66
+
67
+ ### 1. Correction
68
+
69
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional
70
+ or unwelcome in the community.
71
+
72
+ **Consequence**: A private, written warning from community leaders, providing clarity around
73
+ the nature of the violation and an explanation of why the behavior was inappropriate. A
74
+ public apology may be requested.
75
+
76
+ ### 2. Warning
77
+
78
+ **Community Impact**: A violation through a single incident or series of actions.
79
+
80
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the
81
+ people involved, including unsolicited interaction with those enforcing the Code of
82
+ Conduct, for a specified period of time. This includes avoiding interactions in community
83
+ spaces as well as external channels like social media. Violating these terms may lead to
84
+ a temporary or permanent ban.
85
+
86
+ ### 3. Temporary Ban
87
+
88
+ **Community Impact**: A serious violation of community standards, including sustained
89
+ inappropriate behavior.
90
+
91
+ **Consequence**: A temporary ban from any sort of interaction or public communication with
92
+ the community for a specified period of time. No public or private interaction with the
93
+ people involved, including unsolicited interaction with those enforcing the Code of
94
+ Conduct, is allowed during this period. Violating these terms may lead to a permanent
95
+ ban.
96
+
97
+ ### 4. Permanent Ban
98
+
99
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including
100
+ sustained inappropriate behavior, harassment of an individual, or aggression toward or
101
+ disparagement of classes of individuals.
102
+
103
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
104
+
105
+ ## Attribution
106
+
107
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
108
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
109
+
110
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
111
+
112
+ [homepage]: https://www.contributor-covenant.org
113
+
114
+ For answers to common questions about this code of conduct, see the FAQ at
115
+ https://www.contributor-covenant.org/faq. Translations are available at
116
+ https://www.contributor-covenant.org/translations.
data/Gemfile CHANGED
@@ -1,4 +1,13 @@
1
+ # frozen_string_literal: true
2
+
1
3
  source "https://rubygems.org"
2
4
 
3
5
  # Specify your gem's dependencies in anybase.gemspec
4
6
  gemspec
7
+
8
+ major, minor, _patch = RUBY_VERSION.split(".").map(&:to_i)
9
+
10
+ gem "rake"
11
+ gem "rspec"
12
+ gem "rubocop", "<= 1.36", require: false
13
+ gem "rubocop-performance", "<= 1.15", require: false if major > 2 || (major == 2 && minor >= 2)
data/Gemfile.lock ADDED
@@ -0,0 +1,61 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ anybase (0.1.0)
5
+
6
+ GEM
7
+ remote: https://rubygems.org/
8
+ specs:
9
+ ast (2.4.2)
10
+ diff-lcs (1.5.0)
11
+ json (2.6.2)
12
+ parallel (1.22.1)
13
+ parser (3.1.2.1)
14
+ ast (~> 2.4.1)
15
+ rainbow (3.1.1)
16
+ rake (13.0.6)
17
+ regexp_parser (2.5.0)
18
+ rexml (3.2.5)
19
+ rspec (3.11.0)
20
+ rspec-core (~> 3.11.0)
21
+ rspec-expectations (~> 3.11.0)
22
+ rspec-mocks (~> 3.11.0)
23
+ rspec-core (3.11.0)
24
+ rspec-support (~> 3.11.0)
25
+ rspec-expectations (3.11.1)
26
+ diff-lcs (>= 1.2.0, < 2.0)
27
+ rspec-support (~> 3.11.0)
28
+ rspec-mocks (3.11.1)
29
+ diff-lcs (>= 1.2.0, < 2.0)
30
+ rspec-support (~> 3.11.0)
31
+ rspec-support (3.11.1)
32
+ rubocop (1.36.0)
33
+ json (~> 2.3)
34
+ parallel (~> 1.10)
35
+ parser (>= 3.1.2.1)
36
+ rainbow (>= 2.2.2, < 4.0)
37
+ regexp_parser (>= 1.8, < 3.0)
38
+ rexml (>= 3.2.5, < 4.0)
39
+ rubocop-ast (>= 1.20.1, < 2.0)
40
+ ruby-progressbar (~> 1.7)
41
+ unicode-display_width (>= 1.4.0, < 3.0)
42
+ rubocop-ast (1.21.0)
43
+ parser (>= 3.1.1.0)
44
+ rubocop-performance (1.15.0)
45
+ rubocop (>= 1.7.0, < 2.0)
46
+ rubocop-ast (>= 0.4.0)
47
+ ruby-progressbar (1.11.0)
48
+ unicode-display_width (2.3.0)
49
+
50
+ PLATFORMS
51
+ arm64-darwin-21
52
+
53
+ DEPENDENCIES
54
+ anybase!
55
+ rake
56
+ rspec
57
+ rubocop (<= 1.36)
58
+ rubocop-performance (<= 1.15)
59
+
60
+ BUNDLED WITH
61
+ 2.3.19
data/LICENSE ADDED
@@ -0,0 +1,7 @@
1
+ Copyright © 2021 Joshua Hull
2
+
3
+ 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:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ 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.
data/README.md ADDED
@@ -0,0 +1,72 @@
1
+ # Anybase
2
+
3
+ ## Arbitrary number bases
4
+
5
+ So often, I need to create random number bases, with random digits, to satisfy
6
+ some crazy requirement.
7
+
8
+ Here is an example of how you'd do hex in Anybase.
9
+
10
+ ```ruby
11
+ base = Anybase.new('0123456789abcdef')
12
+ base.to_i('f0a')
13
+ => 3850
14
+ base.to_native(123450)
15
+ => "1e23a"
16
+ ```
17
+
18
+ As well, you can tell Anybase to ignore case.
19
+
20
+ ```ruby
21
+ base = Anybase.new('0123456789abcdef', ignore_case: true)
22
+ base.to_i('F0A')
23
+ => 3850
24
+ ```
25
+
26
+ Anybase can also have synonyms.
27
+
28
+ ```ruby
29
+ base = Anybase.new('0123456789abcdef', synonyms: {'0' => 'oO'}, ignore_case: true)
30
+ base.to_i('FoA')
31
+ => 3850
32
+ base.to_i('FOA')
33
+ => 3850
34
+ ```
35
+
36
+ If you just want to translate the number to look at it you can use #normalize
37
+
38
+ ```ruby
39
+ base = Anybase.new('0123456789abcdef', synonyms: {'0' => 'oO'}, ignore_case: true)
40
+ base.normalize('FoA')
41
+ => 'f0a'
42
+ ```
43
+
44
+ If you want to use negative numbers, assign the negative sign character using the
45
+ "negative_sign" option:
46
+
47
+ ```ruby
48
+ base = Anybase.new('0123456789abcdef', negative_sign: '-')
49
+ base.to_native(-12345)
50
+ => '-3039'
51
+ ```
52
+
53
+ Anybase can also zeropad your output with whatever your "zero" character is.
54
+
55
+ ```ruby
56
+ Anybase.new("012345678").to_native(1234, zero_pad: 8)
57
+ => '00001621'
58
+ ```
59
+
60
+ Anybase also lets you create random numbers of any number of digits
61
+
62
+ ```ruby
63
+ Anybase.new("012345678").random(20)
64
+ => '62400274212676317317'
65
+ ```
66
+
67
+ Anybase gives you a few built-in: `Anybase::Hex`, `Anybase::Base64`,
68
+ `Anybase::Base64ForURL` and `Anybase::Base62` (should all be pretty
69
+ self-explanatory)
70
+
71
+ As well, there is an `AnyBase::Base73ForURL`. This includes the characters:
72
+ `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789$-_.+!*\'(),`
data/Rakefile CHANGED
@@ -1,10 +1,8 @@
1
- require 'bundler/gem_tasks'
2
- require 'rspec/core/rake_task'
3
-
4
- desc "Run specs"
5
- RSpec::Core::RakeTask.new do |t|
6
- t.pattern = "./spec/**/*_spec.rb" # don't need this, it's default.
7
- # Put spec opts in a file named .rspec in root
8
- end
9
-
10
- task :default => [:spec]
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ task default: :spec
@@ -1,3 +1,5 @@
1
+ # frozen_string_literal: true
2
+
1
3
  class Anybase
2
- VERSION = '0.0.15'
3
- end
4
+ VERSION = "0.1.0".freeze
5
+ end
data/lib/anybase.rb CHANGED
@@ -1,117 +1,132 @@
1
+ # frozen_string_literal: true
2
+
1
3
  require "anybase/version"
2
4
  require "securerandom"
3
5
 
4
6
  class Anybase
7
+ UnrecognizedCharacterError = Class.new(StandardError)
8
+ NegativeSignListedAsDigitError = Class.new(StandardError)
9
+ NegativeSignTooLongError = Class.new(StandardError)
10
+ UnknownNegativeSignError = Class.new(StandardError)
5
11
 
6
- UnrecognizedCharacterError = Class.new(RuntimeError)
7
-
8
- attr_reader :chars, :char_map, :num_map, :regexp
9
-
10
- def initialize(chars, opts = nil)
11
- @chars = chars
12
- @ignore_case = opts && opts.key?(:ignore_case) ? opts[:ignore_case] : false
13
- @sign = opts && opts.key?(:sign) ? opts[:sign] : nil
14
- raise if @sign && @chars.index(@sign)
15
- @synonyms = opts && opts[:synonyms]
16
- @synonyms_tr = ['', ''] if @synonyms
17
- @char_map = Hash.new{|h,k| raise UnrecognizedCharacterError.new("the character `#{k.chr}' is not included in #{@chars}")}
18
- @num_map = {}
19
- if ignore_case?
20
- @chars.downcase!
21
- end
22
- regexp_str = '['
23
- @chars.split('').each_with_index do |c, i|
24
- regexp_str << Regexp.quote(c)
25
- add_mapping(c, i)
26
- @num_map[i] = c
27
- if @synonyms && @synonyms[c]
28
- @synonyms[c].split('').each { |sc|
29
- regexp_str << Regexp.quote(sc)
30
- @synonyms_tr[1] << c
31
- @synonyms_tr[0] << sc
32
- }
12
+ attr_reader :digits, :char_map, :num_map, :regexp, :negative_sign
13
+
14
+ def initialize(digit_string, ignore_case: false, negative_sign: nil, synonyms: {})
15
+ raise NegativeSignTooLongError if negative_sign && negative_sign.size > 1
16
+ raise NegativeSignListedAsDigitError if negative_sign && digit_string.index(negative_sign)
17
+
18
+ self.digits = digit_string.dup
19
+ self.ignore_case = ignore_case
20
+ self.negative_sign = negative_sign
21
+ self.synonyms = synonyms
22
+ self.synonyms_tr = [String.new, String.new]
23
+ self.char_map = Hash.new { |_h,k| raise UnrecognizedCharacterError, "the character `#{k}' is not included in #{digits}" }
24
+ self.num_map = {}
25
+
26
+ digits.downcase! if ignore_case?
27
+
28
+ regexp_str = String.new("[")
29
+ digits.each_char.with_index do |char, i|
30
+ regexp_str << Regexp.quote(char)
31
+ char_map[char] = i
32
+ num_map[i] = char
33
+
34
+ next unless synonyms[char]
35
+
36
+ synonyms[char].each_char do |synonym|
37
+ regexp_str << Regexp.quote(synonym)
38
+ synonyms_tr[0] << synonym
39
+ synonyms_tr[1] << char
33
40
  end
34
41
  end
35
- regexp_str << ']+'
36
- @regexp = @ignore_case ? Regexp.new(regexp_str, Regexp::IGNORECASE) : Regexp.new(regexp_str)
42
+ regexp_str << "]+"
43
+ self.regexp = ignore_case? ? Regexp.new(regexp_str, Regexp::IGNORECASE) : Regexp.new(regexp_str)
37
44
  end
38
45
 
39
46
  def match(str)
40
- if match = @regexp.match(str)
41
- match.begin(0) == 0 ? match[0] : nil
47
+ if (match = regexp.match(str)) && match.begin(0).zero?
48
+ match[0]
42
49
  else
43
50
  nil
44
51
  end
45
52
  end
46
53
 
47
54
  def ignore_case?
48
- @ignore_case
55
+ ignore_case
49
56
  end
50
57
 
51
- def size(digits)
52
- chars.length ** digits
58
+ def size(length)
59
+ digits.length**length
53
60
  end
54
61
 
55
62
  def normalize(val)
56
- val = val.downcase if ignore_case?
57
- @synonyms ? val.tr(*@synonyms_tr) : val
63
+ val = ignore_case? ? val.downcase : val.dup
64
+ synonyms.empty? ? val : val.tr(*synonyms_tr)
58
65
  end
59
66
 
60
- def random(digits, opts = nil)
61
- zero_pad = opts && opts.key?(:zero_pad) ? opts[:zero_pad] : true
62
- number = ''
63
- digits.times { number << chars[SecureRandom.random_number(chars.size)]}
64
- unless zero_pad
65
- number.sub!(/\A#{Regexp.quote(chars[0].chr)}+/, '')
66
- number = chars[0].chr if number.empty?
67
+ def random(length, trim_leading_zeros: false)
68
+ number = String.new
69
+ length.times { number << digits[SecureRandom.random_number(digits.size)] }
70
+
71
+ if trim_leading_zeros
72
+ number.sub!(/\A#{Regexp.quote(digits[0])}+/, "")
73
+ number = digits[0] if number.empty?
67
74
  end
75
+
68
76
  number
69
77
  end
70
78
 
71
79
  def to_i(val)
72
80
  val = normalize(val)
73
- op = if @sign and val[0] == @sign[0]
81
+ num = 0
82
+ op = if negative_sign && (val[0] == negative_sign[0])
74
83
  val.slice!(0, 1)
75
84
  :-
76
85
  else
77
86
  :+
78
87
  end
79
- num = 0
80
- (0...val.size).each{|i|
81
- num = num.send(op, (chars.size ** (val.size - i - 1)) * char_map[val[i]])
82
- }
88
+
89
+ (0...val.size).each do |i|
90
+ num = num.send(op, (digits.size**(val.size - i - 1)) * char_map[val[i]])
91
+ end
92
+
83
93
  num
84
94
  end
85
95
 
86
- def to_native(val, options = nil)
87
- if val < 0
88
- if @sign
89
- val = val.abs
90
- signed = true
91
- else
92
- raise
93
- end
96
+ def to_native(val, zero_pad: 1)
97
+ zero_pad = 1 if zero_pad < 1
98
+ negative = if val < 0
99
+ raise UnknownNegativeSignError unless negative_sign
100
+
101
+ val = val.abs
102
+ true
103
+ else
104
+ false
94
105
  end
95
- str = ''
106
+
107
+ str = String.new
96
108
  until val.zero?
97
- digit = val % chars.size
98
- val /= chars.size
109
+ digit = val % digits.size
110
+ val /= digits.size
99
111
  str[0, 0] = num_map[digit]
100
112
  end
101
- if options && options[:zero_pad] && str.size < options[:zero_pad]
102
- str[0, 0] = num_map[0] * (options[:zero_pad] - str.size)
103
- end
104
- str == '' ? num_map[0].dup : (signed ? @sign.dup << str : str)
105
- end
106
113
 
107
- def add_mapping(c, i)
108
- char_map[c[0]] = i
114
+ str[0, 0] = num_map[0] * (zero_pad - str.size) if str.size < zero_pad
115
+ str[0, 0] = negative_sign if negative
116
+
117
+ str
109
118
  end
110
- private :add_mapping
111
119
 
112
- Hex = Anybase.new('0123456789abcdef', :ignore_case => true)
113
- Base62 = Anybase.new('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789')
114
- Base64 = Anybase.new('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/')
115
- Base64ForURL = Anybase.new('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_')
116
- Base73ForURL = Anybase.new('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789$-_.+!*\'(),')
120
+ private
121
+
122
+ attr_writer :digits, :char_map, :num_map, :regexp, :negative_sign
123
+ attr_accessor :ignore_case, :synonyms, :synonyms_tr
124
+ end
125
+
126
+ class Anybase
127
+ Hex = Anybase.new("0123456789abcdef", ignore_case: true)
128
+ Base62 = Anybase.new("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")
129
+ Base64 = Anybase.new("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")
130
+ Base64ForURL = Anybase.new("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_")
131
+ Base73ForURL = Anybase.new("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789$-_.+!*'(),")
117
132
  end
metadata CHANGED
@@ -1,69 +1,43 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: anybase
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.0.15
4
+ version: 0.1.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Joshual Hull
8
8
  - Brad Gessler
9
- autorequire:
9
+ - Brad Lindsay
10
+ autorequire:
10
11
  bindir: bin
11
12
  cert_chain: []
12
- date: 2016-02-11 00:00:00.000000000 Z
13
- dependencies:
14
- - !ruby/object:Gem::Dependency
15
- name: rspec
16
- requirement: !ruby/object:Gem::Requirement
17
- requirements:
18
- - - ">="
19
- - !ruby/object:Gem::Version
20
- version: '0'
21
- type: :development
22
- prerelease: false
23
- version_requirements: !ruby/object:Gem::Requirement
24
- requirements:
25
- - - ">="
26
- - !ruby/object:Gem::Version
27
- version: '0'
28
- - !ruby/object:Gem::Dependency
29
- name: rake
30
- requirement: !ruby/object:Gem::Requirement
31
- requirements:
32
- - - ">="
33
- - !ruby/object:Gem::Version
34
- version: '0'
35
- type: :development
36
- prerelease: false
37
- version_requirements: !ruby/object:Gem::Requirement
38
- requirements:
39
- - - ">="
40
- - !ruby/object:Gem::Version
41
- version: '0'
42
- description: Numbers from anybase to anybase
43
- email:
44
- - joshbuddy@gmail.com
45
- - brad@bradgessler.com
13
+ date: 2022-09-30 00:00:00.000000000 Z
14
+ dependencies: []
15
+ description: Create or translate numbers from any base to any base
16
+ email: geeks@polleverywhere.com
46
17
  executables: []
47
18
  extensions: []
48
19
  extra_rdoc_files: []
49
20
  files:
50
- - ".gitignore"
51
- - ".travis.yml"
21
+ - ".rspec"
22
+ - ".rubocop.yml"
23
+ - CHANGELOG.md
24
+ - CODE_OF_CONDUCT.md
52
25
  - Gemfile
53
- - README.rdoc
26
+ - Gemfile.lock
27
+ - LICENSE
28
+ - README.md
54
29
  - Rakefile
55
- - anybase.gemspec
56
30
  - lib/anybase.rb
57
31
  - lib/anybase/version.rb
58
- - spec/from_spec.rb
59
- - spec/spec.opts
60
- - spec/spec_helper.rb
61
- - spec/to_spec.rb
62
- - spec/util_spec.rb
63
- homepage: http://github.com/joshbuddy/anybase
64
- licenses: []
65
- metadata: {}
66
- post_install_message:
32
+ homepage: https://github.com/polleverywhere/anybase
33
+ licenses:
34
+ - MIT
35
+ metadata:
36
+ homepage_uri: https://github.com/polleverywhere/anybase
37
+ source_code_uri: https://github.com/polleverywhere/anybase
38
+ changelog_uri: https://github.com/polleverywhere/anybase/CHANGELOG.md
39
+ rubygems_mfa_required: 'true'
40
+ post_install_message:
67
41
  rdoc_options: []
68
42
  require_paths:
69
43
  - lib
@@ -71,21 +45,15 @@ required_ruby_version: !ruby/object:Gem::Requirement
71
45
  requirements:
72
46
  - - ">="
73
47
  - !ruby/object:Gem::Version
74
- version: '0'
48
+ version: '2.0'
75
49
  required_rubygems_version: !ruby/object:Gem::Requirement
76
50
  requirements:
77
51
  - - ">="
78
52
  - !ruby/object:Gem::Version
79
53
  version: '0'
80
54
  requirements: []
81
- rubyforge_project: anybase
82
- rubygems_version: 2.4.6
83
- signing_key:
55
+ rubygems_version: 3.3.19
56
+ signing_key:
84
57
  specification_version: 4
85
- summary: Numbers from anybase to anybase
86
- test_files:
87
- - spec/from_spec.rb
88
- - spec/spec.opts
89
- - spec/spec_helper.rb
90
- - spec/to_spec.rb
91
- - spec/util_spec.rb
58
+ summary: Create or translate numbers from any base to any base
59
+ test_files: []
data/.gitignore DELETED
@@ -1,3 +0,0 @@
1
- .DS_Store
2
- pkg
3
- Gemfile.lock
data/.travis.yml DELETED
@@ -1,13 +0,0 @@
1
- language: ruby
2
- rvm:
3
- - 1.9.3
4
- - 2.2
5
- - 2.1
6
- - 2.0
7
- - jruby-19mode # JRuby in 1.9 mode
8
- - rbx-2
9
-
10
- # Force build to be use Travis' newer container-based builds, which seem
11
- # more reliable.
12
- # https://docs.travis-ci.com/user/workers/container-based-infrastructure/#Routing-your-build-to-container-based-infrastructure
13
- sudo: false
data/README.rdoc DELETED
@@ -1,56 +0,0 @@
1
- =Anybase
2
-
3
- ==Arbitrary number bases
4
-
5
- So often, I need to create random number bases, with random digits, to satisfy some crazy requirement.
6
-
7
- Here is an example of how you'd do hex in Anybase.
8
-
9
- base = Anybase.new('0123456789abcdef')
10
- base.to_i('f0a')
11
- => 3850
12
- base.to_native(123450)
13
- => "1e23a"
14
-
15
- As well, you can tell Anybase to ignore case.
16
-
17
- base = Anybase.new('0123456789abcdef', :ignore_case => true)
18
- base.to_i('F0A')
19
- => 3850
20
-
21
- Anybase can also have synonyms.
22
-
23
- base = Anybase.new('0123456789abcdef', :synonyms => {'0' => 'oO'}, :ignore_case => true)
24
- base.to_i('FoA')
25
- => 3850
26
- base.to_i('FOA')
27
- => 3850
28
-
29
- If you just want to translate the number to look at it you can use #normalize
30
-
31
- base = Anybase.new('0123456789abcdef', :synonyms => {'0' => 'oO'}, :ignore_case => true)
32
- base.normalize('FoA')
33
- => 'f0a'
34
-
35
- If you want to use negative numbers, assign the sign character using the sign option
36
-
37
- base = Anybase.new('0123456789abcdef', :sign => '-')
38
- base.to_native(-12345)
39
- => '-3039'
40
-
41
- Anybase can also zeropad your output with whatever your "zero" character is.
42
-
43
- Anybase.new("012345678").to_native(1234, :zero_pad => 8)
44
- => '00001621'
45
-
46
- Anybase also lets you create random numbers of any number of digits
47
-
48
- Anybase.new("012345678").random(20)
49
- => '62400274212676317317'
50
-
51
- Anybase gives you a few built-in:
52
- <tt>Anybase::Hex</tt>, <tt>Anybase::Base64</tt>, <tt>Anybase::Base64ForURL</tt> and <tt>Anybase::Base62</tt>
53
- (should all be pretty self-explanatory)
54
-
55
- As well, there is an <tt>AnyBase::Base73ForURL</tt>. This includes the characters:
56
- <tt>ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789$-_.+!*\'(),</tt>
data/anybase.gemspec DELETED
@@ -1,24 +0,0 @@
1
- # -*- encoding: utf-8 -*-
2
- $:.push File.expand_path("../lib", __FILE__)
3
- require "anybase/version"
4
-
5
- Gem::Specification.new do |s|
6
- s.name = "anybase"
7
- s.version = Anybase::VERSION
8
- s.authors = ["Joshual Hull", "Brad Gessler"]
9
- s.email = ["joshbuddy@gmail.com", "brad@bradgessler.com"]
10
- s.homepage = "http://github.com/joshbuddy/anybase"
11
- s.summary = %q{Numbers from anybase to anybase}
12
- s.description = %q{Numbers from anybase to anybase}
13
-
14
- s.rubyforge_project = "anybase"
15
-
16
- s.files = `git ls-files`.split("\n")
17
- s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
18
- s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
19
- s.require_paths = ["lib"]
20
-
21
- # specify any dependencies here; for example:
22
- s.add_development_dependency "rspec"
23
- s.add_development_dependency "rake"
24
- end
data/spec/from_spec.rb DELETED
@@ -1,31 +0,0 @@
1
- require 'spec_helper'
2
-
3
- describe Anybase, "from" do
4
- it "should translate to a number" do
5
- expect(Anybase.new("012345678").to_i('2350')).to eq(1746)
6
- end
7
-
8
- it "should raise an exception if any char isn't included" do
9
- expect { Anybase.new("012345678").to_i('a2350') }.to raise_error(Anybase::UnrecognizedCharacterError)
10
- end
11
-
12
- it "should fold case" do
13
- base = Anybase.new("012345678abcd", :ignore_case => true)
14
- str = 'a23D5d0AbBc'
15
- expect(base.to_i(str)).to eq(base.to_i(str.swapcase))
16
- end
17
-
18
- it "should translate negative numbers with a sign" do
19
- expect(Anybase.new("012345678", :sign => '9').to_i('911')).to eq(-10)
20
- end
21
-
22
- it "should use synonymous" do
23
- expect(Anybase.new("012345678", :synonyms => {'0' => 'oO'}).to_i('O235o')).to eq(1746)
24
- expect { Anybase.new("012345678", :synonyms => {'0' => 'o'}).to_i('235O') }.to raise_error(Anybase::UnrecognizedCharacterError)
25
- end
26
-
27
- it "should use synonymous & ignore case" do
28
- expect(Anybase.new("012345678", :synonyms => {'0' => 'o'}, :ignore_case => true).to_i('235O')).to eq(1746)
29
- end
30
-
31
- end
data/spec/spec.opts DELETED
@@ -1,7 +0,0 @@
1
- --colour
2
- --format
3
- specdoc
4
- --loadby
5
- mtime
6
- --reverse
7
- --backtrace
data/spec/spec_helper.rb DELETED
@@ -1,4 +0,0 @@
1
- require 'rubygems'
2
- require 'bundler/setup'
3
- require 'rspec'
4
- require 'anybase'
data/spec/to_spec.rb DELETED
@@ -1,43 +0,0 @@
1
- require 'spec_helper'
2
-
3
- describe Anybase, "to" do
4
- it "should translate base to a number from a string " do
5
- expect(Anybase.new("012345678").to_native(1827)).to eq("2450")
6
- end
7
-
8
- it "should never return an empty string for 0" do
9
- expect(Anybase.new("012345678").to_native(0)).to eq("0")
10
- end
11
-
12
- it "should normally raise on negative numbers" do
13
- expect { Anybase.new("012345678").to_native(-10)}.to raise_error(RuntimeError)
14
- end
15
-
16
- it "should translate negative numbers with a sign" do
17
- expect(Anybase.new("012345678", :sign => '9').to_native(-10)).to eq('911')
18
- end
19
-
20
- it "should zeropad" do
21
- expect(Anybase.new("012345678").to_native(1234, :zero_pad => 2)).to eq('1621')
22
- expect(Anybase.new("012345678").to_native(1234, :zero_pad => 4)).to eq('1621')
23
- expect(Anybase.new("012345678").to_native(1234, :zero_pad => 8)).to eq('00001621')
24
- end
25
-
26
- it "create random numbers" do
27
- allow(SecureRandom).to receive(:random_number).and_return(5,4,3,2,1,0)
28
- result = Anybase.new("012345678").random(10)
29
- expect(result).to eq('5432100000')
30
-
31
- allow(SecureRandom).to receive(:random_number).and_return(0,0,1,2,3,4,5)
32
- expect(Anybase.new("012345678").random(10, :zero_pad => false)).to eq('12345555')
33
- end
34
-
35
- it "return a zero if thats all it can for a random number" do
36
- result = Anybase.new("0").random(10)
37
- expect(result).to eq('0000000000')
38
-
39
- result = Anybase.new("0").random(10, :zero_pad => false)
40
- expect(result).to eq('0')
41
- end
42
-
43
- end
data/spec/util_spec.rb DELETED
@@ -1,23 +0,0 @@
1
- require 'spec_helper'
2
-
3
- describe Anybase, "util" do
4
- it "should tell you the size for an arbitrary number of digits" do
5
- expect(Anybase.new("012345678").size(10)).to eq(3486784401)
6
- expect(Anybase.new("012345678").size(10) * Anybase.new("012345678").size(10)).to eq(Anybase.new("012345678").size(20))
7
- end
8
-
9
- it "should normalize a number" do
10
- expect(Anybase.new("01", :synonyms => {'0' => 'o', '1' => 'l'}, :ignore_case => true).normalize("l10oO1o")).to eq('1100010')
11
- end
12
-
13
- it "raise if the sign is in the chars" do
14
- expect{ Anybase.new("01", :sign => '0') }.to raise_error(RuntimeError)
15
- end
16
-
17
- it "should allow matching" do
18
- funny_octal = Anybase.new("012345678", :synonyms => {'0' => 'oO'})
19
- expect(funny_octal.match('235O')).to eq('235O')
20
- expect(funny_octal.match('235Ozzz')).to eq('235O')
21
- expect(funny_octal.match('a235O')).to eq(nil)
22
- end
23
- end