object_hash_rb 0.1.2

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.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 72eee9779bcd4883112e7301185fa089742da6d9e815d65ae5c0ad26490a40bf
4
+ data.tar.gz: fa1385e38e63b39a88fb79c6b690a04d42f001d2689ae67f047bb9af226ee0e9
5
+ SHA512:
6
+ metadata.gz: 97b66383399af06d7301b70ae56eb3da22946355f79ea198f7f175ed6710d6f373f49758037ad3182bfac20224f423bfd6e976b7c8e660aae131dc71f861c28a
7
+ data.tar.gz: 3dd0eb60cbe756d5e15c882d29ff3b740d2f9a2d334a1a2607da104002f9a00c3b09b04fb2c125c3854694654a0c63212124b674ce78123ce7a970be3fe73397
@@ -0,0 +1 @@
1
+ service_name: travis-ci
@@ -0,0 +1,13 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
12
+
13
+ *.gem
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
@@ -0,0 +1,29 @@
1
+ AllCops:
2
+ TargetRubyVersion: 2.4
3
+ NewCops: disable
4
+ SuggestExtensions: false
5
+
6
+ Layout/EndOfLine:
7
+ EnforcedStyle: lf
8
+
9
+ Metrics/BlockLength:
10
+ # Don't enforce in test files.
11
+ Max: 25
12
+ Exclude:
13
+ - 'Rakefile'
14
+ - '**/*.rake'
15
+ - 'spec/**/*.rb'
16
+
17
+ Layout/FirstHashElementIndentation:
18
+ EnforcedStyle: consistent
19
+
20
+ Layout/LineLength:
21
+ Max: 120
22
+
23
+ Style/StringLiterals:
24
+ Enabled: true
25
+ EnforcedStyle: double_quotes
26
+
27
+ Style/StringLiteralsInInterpolation:
28
+ Enabled: true
29
+ EnforcedStyle: double_quotes
@@ -0,0 +1 @@
1
+ 2.7.2
@@ -0,0 +1,6 @@
1
+ ---
2
+ language: ruby
3
+ cache: bundler
4
+ rvm:
5
+ - 2.5.3
6
+ before_install: gem install bundler -v 2.2.3
@@ -0,0 +1,20 @@
1
+ {
2
+ "editor.formatOnSave": false,
3
+ "editor.formatOnSaveTimeout": 5000,
4
+
5
+ "ruby.useBundler": true, //run non-lint commands with bundle exec
6
+ "ruby.useLanguageServer": true, // use the internal language server (see below)
7
+ "ruby.lint": {
8
+ // Static code analysis and formatting.
9
+ "rubocop": {
10
+ "useBundler": true // enable rubocop via bundler
11
+ },
12
+ // Code smell detection.
13
+ "reek": {
14
+ "useBundler": true // enable reek via bundler
15
+ }
16
+ },
17
+ "ruby.format": "rubocop",
18
+ "inlineHasher.singleDefaultFormat": "%2",
19
+ "inlineHasher.showFormatInputBox": false // use rubocop for formatting
20
+ }
@@ -0,0 +1,22 @@
1
+ # CHANGELOG
2
+
3
+ ## 0.1.0
4
+
5
+ Initial revision.
6
+
7
+ ## 0.1.1
8
+
9
+ - Added support for circular references.
10
+ - Built a full test suite, which now passes!
11
+
12
+ ## 0.1.2
13
+
14
+ - Improved code coverage.
15
+ - Added tests for sha384 and sha512.
16
+ - Removed less useful crc32 and adler algorithms.
17
+
18
+ # 0.1.3
19
+
20
+ - Renamed to `object_hash_rb` due to conflict with `objecthash`.
21
+ - Although they have similar functionality, `object_hash_rb` includes performance improvements and support for circular references.
22
+ - Improved handling of special float values (infinite and nan)
@@ -0,0 +1,84 @@
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 harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at ericmyllyoja@gmail.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Download gems from here.
4
+ source "https://rubygems.org"
5
+
6
+ # Specify dependencies
7
+ gemspec
@@ -0,0 +1,76 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ object_hash_rb (0.1.2)
5
+
6
+ GEM
7
+ remote: https://rubygems.org/
8
+ specs:
9
+ ast (2.4.1)
10
+ coveralls (0.8.23)
11
+ json (>= 1.8, < 3)
12
+ simplecov (~> 0.16.1)
13
+ term-ansicolor (~> 1.3)
14
+ thor (>= 0.19.4, < 2.0)
15
+ tins (~> 1.6)
16
+ diff-lcs (1.4.4)
17
+ docile (1.3.4)
18
+ json (2.5.1)
19
+ parallel (1.20.1)
20
+ parser (3.0.0.0)
21
+ ast (~> 2.4.1)
22
+ rainbow (3.0.0)
23
+ rake (13.0.3)
24
+ regexp_parser (2.0.3)
25
+ rexml (3.2.4)
26
+ rspec (3.10.0)
27
+ rspec-core (~> 3.10.0)
28
+ rspec-expectations (~> 3.10.0)
29
+ rspec-mocks (~> 3.10.0)
30
+ rspec-core (3.10.1)
31
+ rspec-support (~> 3.10.0)
32
+ rspec-expectations (3.10.1)
33
+ diff-lcs (>= 1.2.0, < 2.0)
34
+ rspec-support (~> 3.10.0)
35
+ rspec-mocks (3.10.1)
36
+ diff-lcs (>= 1.2.0, < 2.0)
37
+ rspec-support (~> 3.10.0)
38
+ rspec-support (3.10.1)
39
+ rubocop (1.7.0)
40
+ parallel (~> 1.10)
41
+ parser (>= 2.7.1.5)
42
+ rainbow (>= 2.2.2, < 4.0)
43
+ regexp_parser (>= 1.8, < 3.0)
44
+ rexml
45
+ rubocop-ast (>= 1.2.0, < 2.0)
46
+ ruby-progressbar (~> 1.7)
47
+ unicode-display_width (>= 1.4.0, < 2.0)
48
+ rubocop-ast (1.3.0)
49
+ parser (>= 2.7.1.5)
50
+ ruby-progressbar (1.11.0)
51
+ simplecov (0.16.1)
52
+ docile (~> 1.1)
53
+ json (>= 1.8, < 3)
54
+ simplecov-html (~> 0.10.0)
55
+ simplecov-html (0.10.2)
56
+ sync (0.5.0)
57
+ term-ansicolor (1.7.1)
58
+ tins (~> 1.0)
59
+ thor (1.0.1)
60
+ tins (1.26.0)
61
+ sync
62
+ unicode-display_width (1.7.0)
63
+
64
+ PLATFORMS
65
+ ruby
66
+
67
+ DEPENDENCIES
68
+ bundler
69
+ coveralls
70
+ object_hash_rb!
71
+ rake
72
+ rspec
73
+ rubocop
74
+
75
+ BUNDLED WITH
76
+ 2.1.4
@@ -0,0 +1,22 @@
1
+
2
+ The MIT License (MIT)
3
+
4
+ Copyright (c) 2020 Eric Myllyoja
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
@@ -0,0 +1,114 @@
1
+ # object_hash_rb
2
+
3
+ Generate cryptographic hashes from objects and values in Ruby. Supports SHA1 and many others.
4
+
5
+ The library aims to support hashing of objects such as circular object structures, allowing for simplified deep equality checks.
6
+
7
+ Built to generate cryptographic hashes which are compatible with [object-hash](https://github.com/puleos/object-hash) for NodeJS.
8
+
9
+ [![Travis CI](https://img.shields.io/travis/com/mastereric/object_hash_rb/master)](https://travis-ci.com/github/MasterEric/object_hash_rb)
10
+ [![RubyGems](https://)](https://img.shields.io/gem/dv/object_hash_rb/stable)
11
+ [![Coverage Status](https://img.shields.io/coveralls/github/MasterEric/object_hash_rb/master)](https://coveralls.io/github/MasterEric/object_hash_rb)
12
+
13
+ ## Installation
14
+
15
+ Add this line to your application's Gemfile:
16
+
17
+ ```ruby
18
+ gem 'object_hash_rb'
19
+ ```
20
+
21
+ And then execute:
22
+
23
+ $ bundle install
24
+
25
+ Or install it yourself as:
26
+
27
+ $ gem install object_hash_rb
28
+
29
+ ## Usage
30
+
31
+ WARNING: For `object_hash_rb` values to be compatible with NodeJS `object-hash` values, you must disable the `respectTypes` option when hashing in JavaScript.
32
+
33
+ ```ruby
34
+ require "object_hash_rb"
35
+
36
+ # Encode and hash the given input.
37
+ ObjectHash.hash("Hello World")
38
+ => "3415EF7FD82C1A04DEA35838ED84A6CECB03C790"
39
+
40
+ # The input can be any object.
41
+ ObjectHash.hash({ a: 1, b: 2, c: 3 })
42
+ => "86BFBAADC95B656DCA2BF2393EF310A1983D59CB"
43
+
44
+ # The same input has the same output, regardless of key order.
45
+ # Great for deep equality checks.
46
+ ObjectHash.hash({ c: 3, a: 1, b: 2 })
47
+ => "86BFBAADC95B656DCA2BF2393EF310A1983D59CB"
48
+
49
+ # There's even a handler for circular references.
50
+ test = {a: "b"}
51
+ test[:b] = test
52
+ ObjectHash.hash(test)
53
+ => "B28AFE82FB41FE5E3CAF60E2045E46E5F5431C04"
54
+
55
+ # You can use one of several different hashing algorithms...
56
+ ObjectHash.hash("foobar", algorithm: "md5")
57
+ => "EB920AE43AF94B25AE057837D80129EC"
58
+
59
+ # ...or you can select "passthrough" to preview how the library builds hashes.
60
+ ObjectHash.hash(test, algorithm: "passthrough")
61
+ => "object:2:symbol:a:string:1:b,symbol:b:string:12:[CIRCULAR:0],"
62
+
63
+ # If there's a non-standard type you want to hash, you can specify a replacer
64
+ # to substitute the value before it gets hashed.
65
+ class TestStuff
66
+ def generate_name
67
+ "foobar"
68
+ end
69
+ end
70
+ ObjectHash.hash({ a: TestStuff.new }, algorithm: "passthrough",
71
+ replacer: lambda do |x|
72
+ # Replace our type.
73
+ return x.generate_name if x.instance_of? TestStuff
74
+ # Else return the original.
75
+ x
76
+ end)
77
+ => "object:1:symbol:a:string:6:foobar,"
78
+
79
+ # You can also make key order matter.
80
+ ObjectHash.hash({ c: 3, a: 1, b: 2 })
81
+ => "86BFBAADC95B656DCA2BF2393EF310A1983D59CB"
82
+ ObjectHash.hash({ c: 3, a: 1, b: 2 }, unordered_objects: false)
83
+ => "A3566EE29CFE62438C36C72BDA4C21621445E7D0"
84
+
85
+ ```
86
+
87
+ ## Comparisons
88
+
89
+ How does this compare with other libraries?
90
+
91
+ - JS: [puleos/object-hash](https://github.com/puleos/object-hash): `object_hash_rb` is intended to be a compatible port of puelos/object-hash, which has wide adoption. As long as `respectType` is set to false, the JavaScript version will produce identical hashes to this library.
92
+ - Ruby: [benlaurie/objecthash](https://github.com/benlaurie/objecthash/tree/master/ruby): `object_hash_rb` competes with, and has the following improvements over, `benlaurie/objecthash`:
93
+ - Direct compatibility with the JavaScript library.
94
+ - Recent maintenance (at time of writing, `benlaurie/objecthash` has not received any fixes in 3 years, for any of its libraries).
95
+ - Higher performance (`benlaurie/objecthash` cryptographically hashes each value individually, whereas `object_hash_rb` produces a single encoding of the object before hashing.)
96
+ - Support for circular references (`benlaurie/objecthash` has no handler to prevent issues with circular references)
97
+
98
+ ## Development
99
+
100
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
101
+
102
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
103
+
104
+ ## Contributing
105
+
106
+ Bug reports and pull requests are welcome on GitHub at https://github.com/MasterEric/object_hash_rb. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/MasterEric/object_hash_rb/blob/master/CODE_OF_CONDUCT.md).
107
+
108
+ ## License
109
+
110
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
111
+
112
+ ## Code of Conduct
113
+
114
+ Everyone interacting in the ObjectHash project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/MasterEric/object_hash_rb/blob/master/CODE_OF_CONDUCT.md).
@@ -0,0 +1,12 @@
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
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "bundler/setup"
5
+ require "object_hash_rb"
6
+
7
+ # You can add fixtures and/or initialization code here to make experimenting
8
+ # with your gem easier. You can also use a different console, if you like.
9
+
10
+ # (If you use this, don't forget to add pry to your Gemfile!)
11
+ # require "pry"
12
+ # Pry.start
13
+
14
+ require "irb"
15
+ IRB.start(__FILE__)
@@ -0,0 +1,6 @@
1
+ #!/bin/bash
2
+
3
+ rake build
4
+ rake install
5
+ rake release
6
+ rake spec
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "object_hash_rb/version"
4
+
5
+ require_relative "object_hash_rb/encode"
6
+ require_relative "object_hash_rb/cryptohash"
7
+
8
+ # Contains functions which encode the input into a standardized format,
9
+ # then cryptographically hash it.
10
+ module ObjectHash
11
+ # rubocop:disable Lint/SelfAssignment
12
+ Encode = Encode
13
+ CryptoHash = CryptoHash
14
+ # rubocop:enable Lint/SelfAssignment
15
+
16
+ module_function
17
+
18
+ # Encode the input into a standardized format,
19
+ # then cryptographically hash it.
20
+ # @param input: Any object that should be encoded.
21
+ # @param algorithm: Either a string naming the algorithm to use, or a Digest object that can hash the string.
22
+ # To preview the output of encoding, use "passthrough".
23
+ # @param replacer: An optional function called on objects before they are encoded.
24
+ # Use this to replace unencodable objects with Strings or Hashes.
25
+ # @param unordered_objects: If true, objects will have sorted keys.
26
+ # If false, objects with different order in their keys will have different hashes.
27
+ def hash(input, algorithm: "sha1", replacer: nil, unordered_objects: true)
28
+ CryptoHash.perform_cryptohash(
29
+ Encode::Encoder.new(
30
+ replacer: replacer,
31
+ unordered_objects: unordered_objects
32
+ ).perform_encode(input),
33
+ algorithm
34
+ )
35
+ end
36
+ end
@@ -0,0 +1,69 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Universal hashing libraries.
4
+ # MD5, SHA1, SHA2, SHA256, SHA384, SHA512, RMD160
5
+ require "digest"
6
+
7
+ require_relative "error"
8
+
9
+ # @INTERNAL: Please use ObjectHash.hash() instead.
10
+ # Contains functions which cryptographically hash an input string,
11
+ # using a given algorithm. Several common algorithms are implemented,
12
+ # or you can provide your own Digest object.
13
+ module CryptoHash
14
+ # Algorithms which can cryptographically hash an input.
15
+ ALGORITHMS = {
16
+ passthrough: lambda do |input|
17
+ # Return the original input with no modification.
18
+ # Useful for debugging and testing.
19
+ input
20
+ end,
21
+ md5: lambda do |input|
22
+ # Return the MD5 hash.
23
+ Digest::MD5.hexdigest(input).upcase
24
+ end,
25
+ sha1: lambda do |input|
26
+ # Return the SHA1 hash.
27
+ Digest::SHA1.hexdigest(input).upcase
28
+ end,
29
+ sha2: lambda do |input|
30
+ # Return the SHA2 hash (256 bit digest).
31
+ Digest::SHA2.new(256).hexdigest(input).upcase
32
+ end,
33
+ sha256: lambda do |input|
34
+ # Return the SHA2 hash (256-bit digest).
35
+ Digest::SHA2.new(256).hexdigest(input).upcase
36
+ end,
37
+ sha384: lambda do |input|
38
+ # Return the SHA2 hash (384-bit digest).
39
+ Digest::SHA2.new(384).hexdigest(input).upcase
40
+ end,
41
+ sha512: lambda do |input|
42
+ # Return the SHA2 hash (512-bit digest).
43
+ Digest::SHA2.new(512).hexdigest(input).upcase
44
+ end,
45
+ rmd160: lambda do |input|
46
+ # Return the RMD160 hash.
47
+ Digest::RMD160.hexdigest(input).upcase
48
+ end
49
+ }.freeze
50
+
51
+ module_function
52
+
53
+ # @INTERNAL: Please use ObjectHash.hash() instead.
54
+ # Call the appropriate algorithm on the input.
55
+ # @param input A string to hash.
56
+ # @param algorithm Either a string for an algorithm to use, or a Digest to perform the hash.
57
+ def perform_cryptohash(input, algorithm)
58
+ # Allow users to specify their own Digest object.
59
+ return algorithm.hexdigest(input) if algorithm.respond_to?(:hexdigest)
60
+
61
+ alg = algorithm.strip.downcase.to_sym
62
+
63
+ # Throw an error if the algorithm is unknown.
64
+ raise UnknownAlgorithmError, algorithm unless ALGORITHMS.key?(alg)
65
+
66
+ # Return the result of the algorithm.
67
+ ALGORITHMS[alg].call(input)
68
+ end
69
+ end
@@ -0,0 +1,160 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Add helper methods to the Time class.
4
+ require "time"
5
+
6
+ # @INTERNAL: Please use ObjectHash.hash() instead.
7
+ # Contains methods to encode any object into a string.
8
+ # Performs the functions of the typeHasher in the original JS library.
9
+ # Encode is a class rather than a module since it has to maintain a state.
10
+ module Encode
11
+ # Used by the Encoder with js_prototypes enabled,
12
+ # to emulate a key with a value of undefined.
13
+ class Undefined; end
14
+
15
+ # Performs encoding while managing state.
16
+ class Encoder
17
+ private
18
+
19
+ #
20
+ # OPTIONS
21
+ #
22
+
23
+ # Provide an optional function which will process values before parsing.
24
+ @replacer = nil
25
+ # If true, object keys will be sorted alphabetically.
26
+ # If false, key order will be respected.
27
+ @unordered_objects = true
28
+
29
+ #
30
+ # ENCODING METHODS
31
+ #
32
+
33
+ # Each method encodes certain types, and is named after the type it encodes,
34
+ # and is called dynamically based on that, thus the uppercase.
35
+ # rubocop:disable Naming/MethodName
36
+
37
+ def encode_Array(input)
38
+ # Encode each element, then concatenate together.
39
+ "array:#{input.length}:#{input.map { |y| encode_value(y) }.reduce(:+)}"
40
+ end
41
+
42
+ def encode_Circular(input)
43
+ encode_String("[CIRCULAR:#{@context.index(input)}]")
44
+ end
45
+
46
+ def encode_Hash(input)
47
+ # Keeps track of what elements have been processed already.
48
+ # Used to prevent parsing circular references.
49
+ keys = @unordered_objects ? input.keys.sort : input.keys
50
+
51
+ # Check each key and format it.
52
+ "object:#{input.length}:#{keys.map do |key|
53
+ value = input[key]
54
+ return encode_Circular(value) if !@context.empty? && @context.index(value)
55
+
56
+ @context.push(input[key])
57
+ "#{encode_value(key)}:#{encode_value(value)},"
58
+ end.reduce(:+)}"
59
+ end
60
+
61
+ def encode_Number(input)
62
+ "number:#{input}"
63
+ end
64
+
65
+ def encode_Integer(input)
66
+ encode_Number(input)
67
+ end
68
+
69
+ def encode_Float(input)
70
+ return "number:NaN" if input.nan?
71
+
72
+ return input.positive? ? "number:Infinity" : "number:-Infinity" if input.infinite?
73
+
74
+ encode_Number(input)
75
+ end
76
+
77
+ def encode_String(input)
78
+ "string:#{input.length}:#{input}"
79
+ end
80
+
81
+ def encode_Symbol(input)
82
+ "symbol:#{input}"
83
+ end
84
+
85
+ def encode_Boolean(input)
86
+ "bool:#{input}"
87
+ end
88
+
89
+ def encode_TrueClass(input)
90
+ encode_Boolean(input)
91
+ end
92
+
93
+ def encode_FalseClass(input)
94
+ encode_Boolean(input)
95
+ end
96
+
97
+ def encode_Time(input)
98
+ "date:#{input.strftime("%Y-%m-%dT%H:%M:%S.%LZ")}"
99
+ end
100
+
101
+ def encode_DateTime(input)
102
+ "date:#{input.strftime("%Y-%m-%dT%H:%M:%S.%LZ")}"
103
+ end
104
+
105
+ def encode_NilClass(_input)
106
+ "Null"
107
+ end
108
+
109
+ def encode_Undefined(_input)
110
+ "Undefined"
111
+ end
112
+
113
+ # End encoding methods.
114
+ # rubocop:enable Naming/MethodName
115
+
116
+ # @param t: Type of the input value.
117
+ # Allows recursive calls which switch which type is used.
118
+ def encode_value(input)
119
+ # If the user specified a custom replacer...
120
+ input = @replacer.call(input) unless @replacer.nil?
121
+
122
+ begin
123
+ # Call the appropriate method by name, if it exists,
124
+ # and return its result.
125
+ method("encode_#{input.class}").call(input)
126
+ rescue NameError
127
+ raise NoEncoderError, input.class.to_s
128
+ end
129
+ end
130
+
131
+ public
132
+
133
+ # When initializing, you can provide options to modify how the encoder functions.
134
+ def initialize(replacer: nil, unordered_objects: true)
135
+ # OPTIONS
136
+ @replacer = replacer
137
+ @unordered_objects = unordered_objects
138
+
139
+ # Used for circular reference handling.
140
+ @context = []
141
+ end
142
+
143
+ def encode_cleanup
144
+ @context = []
145
+ end
146
+
147
+ # @INTERNAL: Please use ObjectHash.hash() instead.
148
+ # Encodes the input value to match a standardized format.
149
+ def perform_encode(input)
150
+ # Encode the value.
151
+ result = encode_value(input)
152
+
153
+ # Cleanup.
154
+ encode_cleanup
155
+
156
+ # Return the encoded value.
157
+ result
158
+ end
159
+ end
160
+ end
@@ -0,0 +1,24 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Defines an error which is thrown when
4
+ # the user attempts to use an algorithm which is not defined.
5
+ #
6
+ # If the algorithm you want isn't implemented,
7
+ # please create an issue on GitHub.
8
+ # I can add the library that implements it as an optional dependency.
9
+ class UnknownAlgorithmError < StandardError
10
+ def initialize(algorithm = "~")
11
+ super("Attempted to hash with unknown algorithm (got #{algorithm})")
12
+ end
13
+ end
14
+
15
+ # Defines an error which is thrown when
16
+ # the user attempts to use an algorithm which is not defined.
17
+ #
18
+ # If the type you want is standard in Ruby, and doesn't have an encoder yet,
19
+ # please create an issue on GitHub.
20
+ class NoEncoderError < StandardError
21
+ def initialize(type = "~")
22
+ super("Attempted to encode unknown class (got #{type})")
23
+ end
24
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ObjectHash
4
+ VERSION = "0.1.2"
5
+ end
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/object_hash_rb/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "object_hash_rb"
7
+ spec.version = ObjectHash::VERSION
8
+ spec.authors = ["MasterEric"]
9
+
10
+ spec.summary = "Generate cryptographic hashes from objects and values."
11
+ spec.description = "Generate cryptographic hashes from objects and values in Ruby."\
12
+ "Built for compatibility with `object-hash` for JavaScript."
13
+ spec.homepage = "https://github.com/MasterEric/object_hash_rb"
14
+ spec.license = "MIT"
15
+
16
+ # TODO: Should this be set lower to increase compatibility?
17
+ spec.required_ruby_version = Gem::Requirement.new(">= 2.4.0")
18
+
19
+ spec.metadata["homepage_uri"] = "https://github.com/MasterEric/object_hash_rb"
20
+ spec.metadata["source_code_uri"] = "https://github.com/MasterEric/object_hash_rb"
21
+ spec.metadata["changelog_uri"] = "https://github.com/MasterEric/object_hash_rb/CHANGELOG.md"
22
+
23
+ # Specify which files should be added to the gem when it is released.
24
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
25
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
26
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{\A(?:test|spec|features)/}) }
27
+ end
28
+ spec.bindir = "exe"
29
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
30
+ spec.require_paths = ["lib"]
31
+
32
+ # Add dependencies from the Gemfile.
33
+ spec.add_development_dependency "bundler"
34
+ spec.add_development_dependency "coveralls"
35
+ spec.add_development_dependency "rake"
36
+ spec.add_development_dependency "rspec"
37
+ spec.add_development_dependency "rubocop"
38
+ end
metadata ADDED
@@ -0,0 +1,139 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: object_hash_rb
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.2
5
+ platform: ruby
6
+ authors:
7
+ - MasterEric
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2021-01-01 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: coveralls
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rake
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rspec
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: '0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: rubocop
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - ">="
74
+ - !ruby/object:Gem::Version
75
+ version: '0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - ">="
81
+ - !ruby/object:Gem::Version
82
+ version: '0'
83
+ description: Generate cryptographic hashes from objects and values in Ruby.Built for
84
+ compatibility with `object-hash` for JavaScript.
85
+ email:
86
+ executables: []
87
+ extensions: []
88
+ extra_rdoc_files: []
89
+ files:
90
+ - ".coveralls.yml"
91
+ - ".gitignore"
92
+ - ".rspec"
93
+ - ".rubocop.yml"
94
+ - ".ruby-version"
95
+ - ".travis.yml"
96
+ - ".vscode/settings.json"
97
+ - CHANGELOG.md
98
+ - CODE_OF_CONDUCT.md
99
+ - Gemfile
100
+ - Gemfile.lock
101
+ - LICENSE.md
102
+ - README.md
103
+ - Rakefile
104
+ - bin/console
105
+ - bin/release
106
+ - bin/setup
107
+ - lib/object_hash_rb.rb
108
+ - lib/object_hash_rb/cryptohash.rb
109
+ - lib/object_hash_rb/encode.rb
110
+ - lib/object_hash_rb/error.rb
111
+ - lib/object_hash_rb/version.rb
112
+ - object_hash_rb.gemspec
113
+ homepage: https://github.com/MasterEric/object_hash_rb
114
+ licenses:
115
+ - MIT
116
+ metadata:
117
+ homepage_uri: https://github.com/MasterEric/object_hash_rb
118
+ source_code_uri: https://github.com/MasterEric/object_hash_rb
119
+ changelog_uri: https://github.com/MasterEric/object_hash_rb/CHANGELOG.md
120
+ post_install_message:
121
+ rdoc_options: []
122
+ require_paths:
123
+ - lib
124
+ required_ruby_version: !ruby/object:Gem::Requirement
125
+ requirements:
126
+ - - ">="
127
+ - !ruby/object:Gem::Version
128
+ version: 2.4.0
129
+ required_rubygems_version: !ruby/object:Gem::Requirement
130
+ requirements:
131
+ - - ">="
132
+ - !ruby/object:Gem::Version
133
+ version: '0'
134
+ requirements: []
135
+ rubygems_version: 3.1.4
136
+ signing_key:
137
+ specification_version: 4
138
+ summary: Generate cryptographic hashes from objects and values.
139
+ test_files: []