fast_camelize 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 8df8e6d4f213e8794d25126d2e6e3ef259fd3ca8bfd7f6a401cf2a4217a81091
4
+ data.tar.gz: bf13cc73a25de18fd05beed12aca15ea3ea4bcf1d1ea034f47f62ca13912bf8d
5
+ SHA512:
6
+ metadata.gz: fd55a665b83784a260a991c351b2d21f70fb0f458efaaca562cfdd75c6b75f84af96609b8ceaea43b8caa81fafb020175c5379ea15a56743ae20c3754428bf6a
7
+ data.tar.gz: b31ee42cd8af43fa5e43e841a385c82240777dc16a61e52a75272c2b15249d119512e989eb6a11a538a9d79c75e68eab54cdc71ea226a54857a4f47e3be664ef
@@ -0,0 +1,6 @@
1
+ version: 2
2
+ updates:
3
+ - package-ecosystem: "bundler"
4
+ directory: "/"
5
+ schedule:
6
+ interval: "daily"
@@ -0,0 +1,35 @@
1
+ name: Main
2
+ on:
3
+ - push
4
+ - pull_request_target
5
+ jobs:
6
+ ci:
7
+ name: CI
8
+ runs-on: ubuntu-latest
9
+ env:
10
+ CI: true
11
+ steps:
12
+ - uses: actions/checkout@master
13
+ - uses: ruby/setup-ruby@v1
14
+ with:
15
+ bundler-cache: true
16
+ ruby-version: 3.0
17
+ - name: Lint and test
18
+ run: |
19
+ bundle exec rubocop --parallel
20
+ bundle exec rake test
21
+ bundle exec steep check
22
+ automerge:
23
+ name: AutoMerge
24
+ needs: ci
25
+ runs-on: ubuntu-latest
26
+ if: github.event_name == 'pull_request_target' && github.actor == 'dependabot[bot]'
27
+ steps:
28
+ - uses: actions/github-script@v3
29
+ with:
30
+ script: |
31
+ github.pulls.merge({
32
+ owner: context.payload.repository.owner.login,
33
+ repo: context.payload.repository.name,
34
+ pull_number: context.payload.pull_request.number
35
+ })
data/.gitignore ADDED
@@ -0,0 +1,10 @@
1
+ /.bundle/
2
+ /.vscode
3
+ /.yardoc
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
10
+ /lib/fast_camelize/fast_camelize.bundle
data/.rubocop.yml ADDED
@@ -0,0 +1,34 @@
1
+ AllCops:
2
+ DisplayCopNames: true
3
+ DisplayStyleGuide: true
4
+ SuggestExtensions: false
5
+ TargetRubyVersion: 3.0
6
+ NewCops: enable
7
+ Exclude:
8
+ - 'vendor/**/*'
9
+ - 'yard/**/*'
10
+ - 'tmp/**/*'
11
+
12
+ Gemspec/RequiredRubyVersion:
13
+ Enabled: false
14
+
15
+ Layout/LineLength:
16
+ Max: 80
17
+
18
+ Lint/AmbiguousBlockAssociation:
19
+ Enabled: false
20
+
21
+ Naming/RescuedExceptionsVariableName:
22
+ Enabled: false
23
+
24
+ Style/Documentation:
25
+ Enabled: false
26
+
27
+ Style/FormatString:
28
+ EnforcedStyle: percent
29
+
30
+ Style/FormatStringToken:
31
+ Enabled: false
32
+
33
+ Style/PerlBackrefs:
34
+ Enabled: false
data/CHANGELOG.md ADDED
@@ -0,0 +1,16 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
6
+
7
+ ## [Unreleased]
8
+
9
+ ## [0.1.0] - 2020-10-09
10
+
11
+ ### Added
12
+
13
+ - 🎉 Initial release! 🎉
14
+
15
+ [unreleased]: https://github.com/kddeisz/fast_camelize/compare/v0.1.0...HEAD
16
+ [0.1.0]: https://github.com/kddeisz/fast_camelize/compare/39c5a7...v0.1.0
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at kevin.deisz@gmail.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [https://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: https://contributor-covenant.org
74
+ [version]: https://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ source 'https://rubygems.org'
4
+
5
+ gemspec
6
+
7
+ gem 'activesupport'
8
+ gem 'benchmark-ips'
9
+ gem 'bundler'
10
+ gem 'minitest'
11
+ gem 'rake'
12
+ gem 'rake-compiler'
13
+ gem 'rubocop'
14
+ gem 'simplecov'
15
+ gem 'steep'
data/Gemfile.lock ADDED
@@ -0,0 +1,90 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ fast_camelize (0.1.0)
5
+
6
+ GEM
7
+ remote: https://rubygems.org/
8
+ specs:
9
+ activesupport (6.1.3.1)
10
+ concurrent-ruby (~> 1.0, >= 1.0.2)
11
+ i18n (>= 1.6, < 2)
12
+ minitest (>= 5.1)
13
+ tzinfo (~> 2.0)
14
+ zeitwerk (~> 2.3)
15
+ ast (2.4.2)
16
+ benchmark-ips (2.8.4)
17
+ concurrent-ruby (1.1.8)
18
+ docile (1.3.5)
19
+ ffi (1.15.0)
20
+ i18n (1.8.10)
21
+ concurrent-ruby (~> 1.0)
22
+ language_server-protocol (3.16.0.0)
23
+ listen (3.5.1)
24
+ rb-fsevent (~> 0.10, >= 0.10.3)
25
+ rb-inotify (~> 0.9, >= 0.9.10)
26
+ minitest (5.14.4)
27
+ parallel (1.20.1)
28
+ parser (3.0.1.0)
29
+ ast (~> 2.4.1)
30
+ rainbow (3.0.0)
31
+ rake (13.0.3)
32
+ rake-compiler (1.1.1)
33
+ rake
34
+ rb-fsevent (0.10.4)
35
+ rb-inotify (0.10.1)
36
+ ffi (~> 1.0)
37
+ rbs (1.1.1)
38
+ regexp_parser (2.1.1)
39
+ rexml (3.2.5)
40
+ rubocop (1.12.1)
41
+ parallel (~> 1.10)
42
+ parser (>= 3.0.0.0)
43
+ rainbow (>= 2.2.2, < 4.0)
44
+ regexp_parser (>= 1.8, < 3.0)
45
+ rexml
46
+ rubocop-ast (>= 1.2.0, < 2.0)
47
+ ruby-progressbar (~> 1.7)
48
+ unicode-display_width (>= 1.4.0, < 3.0)
49
+ rubocop-ast (1.4.1)
50
+ parser (>= 2.7.1.5)
51
+ ruby-progressbar (1.11.0)
52
+ simplecov (0.21.2)
53
+ docile (~> 1.1)
54
+ simplecov-html (~> 0.11)
55
+ simplecov_json_formatter (~> 0.1)
56
+ simplecov-html (0.12.3)
57
+ simplecov_json_formatter (0.1.2)
58
+ steep (0.43.1)
59
+ activesupport (>= 5.1)
60
+ language_server-protocol (>= 3.15, < 4.0)
61
+ listen (~> 3.0)
62
+ parallel (>= 1.0.0)
63
+ parser (>= 2.7)
64
+ rainbow (>= 2.2.2, < 4.0)
65
+ rbs (~> 1.1.0)
66
+ terminal-table (>= 2, < 4)
67
+ terminal-table (3.0.0)
68
+ unicode-display_width (~> 1.1, >= 1.1.1)
69
+ tzinfo (2.0.4)
70
+ concurrent-ruby (~> 1.0)
71
+ unicode-display_width (1.7.0)
72
+ zeitwerk (2.4.2)
73
+
74
+ PLATFORMS
75
+ ruby
76
+
77
+ DEPENDENCIES
78
+ activesupport
79
+ benchmark-ips
80
+ bundler
81
+ fast_camelize!
82
+ minitest
83
+ rake
84
+ rake-compiler
85
+ rubocop
86
+ simplecov
87
+ steep
88
+
89
+ BUNDLED WITH
90
+ 2.2.3
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2021-present Kevin Deisz
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
13
+ all 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
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,53 @@
1
+ # `String#camelize` Ruby Extension
2
+
3
+ [![Build Status](https://github.com/kddeisz/fast_camelize/workflows/Main/badge.svg)](https://github.com/kddeisz/fast_camelize/actions)
4
+ [![Gem Version](https://img.shields.io/gem/v/fast_camelize.svg)](https://rubygems.org/gems/fast_camelize)
5
+
6
+ `fast_camelize` is a C extension that provides a fast implementation of [ActiveSupport's `String#camelize` method](http://api.rubyonrails.org/classes/String.html#method-i-camelize).
7
+
8
+ ## Is it fast?
9
+
10
+ At last check, these were the benchmarks (obtained by running `bin/bench` with ActiveSupport 6.1.3):
11
+
12
+ ```
13
+ Warming up --------------------------------------
14
+ ActiveSupport 20.000 i/100ms
15
+ FastCamelize 74.000 i/100ms
16
+ Calculating -------------------------------------
17
+ ActiveSupport 202.091 (± 7.4%) i/s - 1.020k in 5.081583s
18
+ FastCamelize 974.025 (± 2.3%) i/s - 4.884k in 5.016944s
19
+
20
+ Comparison:
21
+ FastCamelize: 974.0 i/s
22
+ ActiveSupport: 202.1 i/s - 4.82x (± 0.00) slower
23
+ ```
24
+
25
+ ## Installation
26
+
27
+ Add this line to your application's Gemfile:
28
+
29
+ ```ruby
30
+ gem 'fast_camelize'
31
+ ```
32
+
33
+ And then execute:
34
+
35
+ $ bundle
36
+
37
+ Or install it yourself as:
38
+
39
+ $ gem install fast_camelize
40
+
41
+ ## Development
42
+
43
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
44
+
45
+ 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 tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
46
+
47
+ ## Contributing
48
+
49
+ Bug reports and pull requests are welcome on GitHub at https://github.com/kddeisz/fast_camelize.
50
+
51
+ ## License
52
+
53
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'rake/testtask'
5
+ require 'rake/extensiontask'
6
+
7
+ Rake::ExtensionTask.new(:compile) do |ext|
8
+ ext.name = 'fast_camelize'
9
+ ext.ext_dir = 'ext/fast_camelize'
10
+ ext.lib_dir = 'lib/fast_camelize'
11
+ ext.gem_spec = Gem::Specification.load('fast_camelize.gemspec')
12
+ end
13
+
14
+ Rake::TestTask.new(:test) do |t|
15
+ t.libs << 'test'
16
+ t.libs << 'lib'
17
+ t.test_files = FileList['test/**/*_test.rb']
18
+ end
19
+
20
+ Rake::Task[:test].prerequisites << :compile
21
+
22
+ task default: :test
data/Steepfile ADDED
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ target :lib do
4
+ signature 'sig'
5
+ check 'lib'
6
+ end
data/bin/bench ADDED
@@ -0,0 +1,24 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require 'bundler/setup'
5
+ require 'benchmark/ips'
6
+
7
+ require 'fast_camelize'
8
+ require 'active_support/inflector'
9
+
10
+ source =
11
+ %w[_ - : :: / 漢字 😊🎉] + ('a'..'z').to_a + ('A'..'Z').to_a + ('0'..'9').to_a
12
+ words = 500.times.map { Array.new(100) { source.sample }.join }
13
+
14
+ Benchmark.ips do |x|
15
+ x.report('ActiveSupport') do
16
+ words.each { |word| ActiveSupport::Inflector.as_camelize(word) }
17
+ end
18
+
19
+ x.report('FastCamelize') do
20
+ words.each { |word| FastCamelize.camelize(word) }
21
+ end
22
+
23
+ x.compare!
24
+ end
data/bin/console ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require 'bundler/setup'
5
+ require 'fast_camelize'
6
+
7
+ require 'irb'
8
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
@@ -0,0 +1,4 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'mkmf'
4
+ create_makefile('fast_camelize/fast_camelize')
@@ -0,0 +1,191 @@
1
+ #include <ctype.h>
2
+ #include <stdbool.h>
3
+ #include <ruby.h>
4
+ #include <ruby/encoding.h>
5
+
6
+ /**
7
+ * This function works by maintaining a state machine that tracks which
8
+ * characters are allowed at any given state, and reacting appropriately. The
9
+ * state machine looks like:
10
+ *
11
+ * ┌ * ┐ ┌ _/ ┐
12
+ * │ v │ v
13
+ * ┌─────────────┐ ┌─────────────┐
14
+ * │ │─── _/ ───>│ │
15
+ * ──>│ DEFAULT │ │ SEGSTART │
16
+ * │ │<─── * ────│ │
17
+ * └─────────────┘ └─────────────┘
18
+ * ^ │ ^
19
+ * * │ │
20
+ * │ │ │
21
+ * ┌─────────────┐ │ |
22
+ * │ │<─ a-zA-Z0-9 ──┘ |
23
+ * │ SEGBODY │ |
24
+ * │ │──── _/ ────────────┘
25
+ * └─────────────┘
26
+ * │ ^
27
+ * └ a-zA-Z0-9 ┘
28
+ */
29
+
30
+ // This is the current state of the state machine being used to compile the
31
+ // camelized string.
32
+ enum state {
33
+ STATE_DEFAULT,
34
+ STATE_SEGSTART,
35
+ STATE_SEGBODY
36
+ };
37
+
38
+ // Determines if this is an ASCII alphanumeric character.
39
+ static inline int isasciialnum(int character) {
40
+ return (
41
+ (character >= 'a' && character <= 'z') ||
42
+ (character >= 'A' && character <= 'Z') ||
43
+ (character >= '0' && character <= '9')
44
+ );
45
+ }
46
+
47
+ // Copies a segment of characters over onto the output buffer. If the segment
48
+ // is a key in the acronyms hash, then it's going to copy over the value from
49
+ // the hash instead.
50
+ static void copy_segment(char *result, size_t *result_size, char *segment, size_t *segment_size, VALUE acronyms, bool capitalize) {
51
+ segment[*segment_size] = '\0';
52
+ VALUE acronym = rb_hash_aref(acronyms, rb_str_new_cstr(segment));
53
+
54
+ if (acronym == Qnil) {
55
+ strncpy(result + *result_size, segment, *segment_size);
56
+ if (capitalize) result[*result_size] = toupper(result[*result_size]);
57
+ *result_size += *segment_size;
58
+ } else {
59
+ size_t acronym_size = RSTRING_LEN(acronym);
60
+ strncpy(result + *result_size, StringValueCStr(acronym), acronym_size);
61
+ *result_size += acronym_size;
62
+ }
63
+
64
+ *segment_size = 0;
65
+ }
66
+
67
+ // Makes a camelized version of the given string. Effectively implementing the
68
+ // following Ruby code:
69
+ //
70
+ // gsub!(/(?:_|(\/))([a-z\d]*)/i) { "#{$1}#{acronyms[$2] || $2.capitalize}" }
71
+ // gsub!("/", "::")
72
+ //
73
+ static VALUE camelize(VALUE string, VALUE kwargs) {
74
+ static ID keywords[1];
75
+ CONST_ID(keywords[0], "acronyms");
76
+
77
+ VALUE options[1] = { Qundef };
78
+ rb_get_kwargs(kwargs, keywords, 0, 1, options);
79
+
80
+ // Configure the options based on the inputted keyword arguments
81
+ VALUE acronyms = options[0] == Qundef ? rb_hash_new() : options[0];
82
+
83
+ // Set the initial state and build a buffer for the resulting string
84
+ enum state state = STATE_DEFAULT;
85
+
86
+ char result[RSTRING_LEN(string) * sizeof(unsigned int) * 2];
87
+ char segment[RSTRING_LEN(string) * sizeof(unsigned int) * 2];
88
+
89
+ size_t result_size = 0;
90
+ size_t segment_size = 0;
91
+
92
+ // Set up a couple of variables necessary for iterating through the string
93
+ rb_encoding *encoding = rb_enc_from_index(ENCODING_GET(string));
94
+ int codepoint_size;
95
+ unsigned int codepoint;
96
+
97
+ // Determine the bounds of the string for our loop
98
+ char *pointer = RSTRING_PTR(string);
99
+ char *end = RSTRING_END(string);
100
+
101
+ while (pointer < end) {
102
+ codepoint = rb_enc_codepoint_len(pointer, end, &codepoint_size, encoding);
103
+ pointer += codepoint_size;
104
+
105
+ switch (state) {
106
+ case STATE_DEFAULT:
107
+ if (codepoint != '_' && codepoint != '/') {
108
+ rb_enc_mbcput(codepoint, &segment[segment_size], encoding);
109
+ segment_size += codepoint_size;
110
+ } else {
111
+ if (segment_size > 0) {
112
+ copy_segment(result, &result_size, segment, &segment_size, acronyms, false);
113
+ }
114
+ if (codepoint == '/') {
115
+ strncpy(result + result_size, "::", 2);
116
+ result_size += 2;
117
+ }
118
+ state = STATE_SEGSTART;
119
+ }
120
+
121
+ break;
122
+ case STATE_SEGSTART:
123
+ if (codepoint == '_') {
124
+ // do nothing
125
+ } else if (codepoint == '/') {
126
+ strncpy(result + result_size, "::", 2);
127
+ result_size += 2;
128
+ } else if (isasciialnum(codepoint)) {
129
+ segment[segment_size++] = codepoint;
130
+ state = STATE_SEGBODY;
131
+ } else {
132
+ rb_enc_mbcput(codepoint, &result[result_size], encoding);
133
+ result_size += codepoint_size;
134
+ state = STATE_DEFAULT;
135
+ }
136
+ break;
137
+ case STATE_SEGBODY:
138
+ if (isasciialnum(codepoint)) {
139
+ segment[segment_size++] = codepoint;
140
+ } else {
141
+ copy_segment(result, &result_size, segment, &segment_size, acronyms, true);
142
+
143
+ if (codepoint == '_') {
144
+ state = STATE_SEGSTART;
145
+ } else if (codepoint == '/') {
146
+ strncpy(result + result_size, "::", 2);
147
+ result_size += 2;
148
+ state = STATE_SEGSTART;
149
+ } else {
150
+ rb_enc_mbcput(codepoint, &result[result_size], encoding);
151
+ result_size += codepoint_size;
152
+ state = STATE_DEFAULT;
153
+ }
154
+ }
155
+ break;
156
+ }
157
+ }
158
+
159
+ // If we're in the DEFAULT or SEGBODY state, then we need to flush out the
160
+ // remaining segment.
161
+ if ((state == STATE_SEGBODY || state == STATE_DEFAULT) && segment_size > 0) {
162
+ copy_segment(result, &result_size, segment, &segment_size, acronyms, true);
163
+ }
164
+
165
+ return rb_enc_str_new(result, result_size, encoding);
166
+ }
167
+
168
+ // FastCamelize::camelize
169
+ static VALUE fast_camelize(int argc, VALUE* argv, VALUE self) {
170
+ VALUE string = Qnil;
171
+ VALUE kwargs = Qnil;
172
+ rb_scan_args(argc, argv, "10:", &string, &kwargs);
173
+
174
+ return RB_TYPE_P(string, T_STRING) ? camelize(string, kwargs) : Qnil;
175
+ }
176
+
177
+ // String#camelize
178
+ static VALUE string_camelize(int argc, VALUE* argv, VALUE self) {
179
+ VALUE kwargs = Qnil;
180
+ rb_scan_args(argc, argv, "00:", &kwargs);
181
+
182
+ return camelize(self, kwargs);
183
+ }
184
+
185
+ // Hook into Ruby and define the FastCamelize::camelize and
186
+ // String#camelize.
187
+ void Init_fast_camelize(void) {
188
+ VALUE rb_mFastCamelize = rb_define_module("FastCamelize");
189
+ rb_define_singleton_method(rb_mFastCamelize, "camelize", fast_camelize, -1);
190
+ rb_define_method(rb_cString, "camelize", string_camelize, -1);
191
+ }
@@ -0,0 +1,26 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'lib/fast_camelize/version'
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = 'fast_camelize'
7
+ spec.version = FastCamelize::VERSION
8
+ spec.authors = ['Kevin Deisz']
9
+ spec.email = ['kevin.deisz@gmail.com']
10
+
11
+ spec.summary = 'Fast String#camelize implementation'
12
+ spec.description = 'Provides a C-optimized method for camelizing a string'
13
+ spec.homepage = 'https://github.com/kddeisz/fast_camelize'
14
+ spec.license = 'MIT'
15
+
16
+ spec.files = Dir.chdir(__dir__) do
17
+ `git ls-files -z`.split("\x0").reject do |f|
18
+ f.match(%r{^(test|spec|features)/})
19
+ end
20
+ end
21
+
22
+ spec.bindir = 'exe'
23
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
24
+ spec.require_paths = %w[lib]
25
+ spec.extensions = ['ext/fast_camelize/extconf.rb']
26
+ end
@@ -0,0 +1,59 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'fast_camelize/version'
4
+ require 'fast_camelize/fast_camelize'
5
+
6
+ # By default, FastCamelize already defines String#camelize and
7
+ # FastCamelize::camelize. In the case that we're using ActiveSupport,
8
+ # however, there is the additional functionality of defined acronyms that we
9
+ # need to account for. In this case, we're going to first allow ActiveSupport to
10
+ # do that work, then we're going to do the actual camelization.
11
+ module FastCamelize
12
+ # Override ActiveSupport::Inflector::camelize to use FastCamelize::camelize.
13
+ module ActiveSupportInflectorPatch
14
+ # Disabling rubocop here so that we can directly match the implementation in
15
+ # the Rails source, so it's easier when Rails changes it.
16
+ # rubocop:disable all
17
+ def camelize(string, uppercase_first_letter = true)
18
+ # This assignment is largely just here for type checking. This module is
19
+ # always going to be included in ActiveSupport::Inflector, but rbs doesn't
20
+ # have requires_ancestor-ish support yet.
21
+ inflections = ActiveSupport::Inflector.inflections
22
+
23
+ string = string.to_s
24
+ if uppercase_first_letter
25
+ string = string.sub(/^[a-z\d]*/) { |match| inflections.acronyms[match] || match.capitalize }
26
+ else
27
+ string = string.sub(inflections.acronyms_camelize_regex) { |match| match.downcase }
28
+ end
29
+
30
+ FastCamelize.camelize(string, acronyms: inflections.acronyms)
31
+ end
32
+ # rubocop:disable all
33
+ end
34
+
35
+ # Override ActiveSupport::Inflector::method_added so that if and when the
36
+ # camelize method gets defined, we can immediately redefine it.
37
+ module ActiveSupportDelayedPatch
38
+ def method_added(method)
39
+ FastCamelize.active_support if method == :camelize
40
+ super
41
+ end
42
+ end
43
+
44
+ # Hook into ActiveSupport::Inflector to take advantage of FastCamelize.
45
+ def self.active_support
46
+ ActiveSupport::Inflector.alias_method(:as_camelize, :camelize)
47
+ ActiveSupport::Inflector.include(ActiveSupportInflectorPatch)
48
+ end
49
+ end
50
+
51
+ if defined?(ActiveSupport)
52
+ FastCamelize.active_support
53
+ else
54
+ module ActiveSupport
55
+ module Inflector
56
+ prepend(FastCamelize::ActiveSupportDelayedPatch)
57
+ end
58
+ end
59
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FastCamelize
4
+ VERSION = '0.1.0'
5
+ end
@@ -0,0 +1,10 @@
1
+ module FastCamelize
2
+ VERSION: String
3
+
4
+ def self.active_support: () -> void
5
+ def self.camelize: (String string, ?acronyms: Hash[String, String]) -> String
6
+ end
7
+
8
+ class String
9
+ def camelize: (?acronyms: Hash[String, String]) -> String
10
+ end
metadata ADDED
@@ -0,0 +1,65 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: fast_camelize
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Kevin Deisz
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2021-04-16 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: Provides a C-optimized method for camelizing a string
14
+ email:
15
+ - kevin.deisz@gmail.com
16
+ executables: []
17
+ extensions:
18
+ - ext/fast_camelize/extconf.rb
19
+ extra_rdoc_files: []
20
+ files:
21
+ - ".github/dependabot.yml"
22
+ - ".github/workflows/main.yml"
23
+ - ".gitignore"
24
+ - ".rubocop.yml"
25
+ - CHANGELOG.md
26
+ - CODE_OF_CONDUCT.md
27
+ - Gemfile
28
+ - Gemfile.lock
29
+ - LICENSE
30
+ - README.md
31
+ - Rakefile
32
+ - Steepfile
33
+ - bin/bench
34
+ - bin/console
35
+ - bin/setup
36
+ - ext/fast_camelize/extconf.rb
37
+ - ext/fast_camelize/fast_camelize.c
38
+ - fast_camelize.gemspec
39
+ - lib/fast_camelize.rb
40
+ - lib/fast_camelize/version.rb
41
+ - sig/fast_camelize.rbs
42
+ homepage: https://github.com/kddeisz/fast_camelize
43
+ licenses:
44
+ - MIT
45
+ metadata: {}
46
+ post_install_message:
47
+ rdoc_options: []
48
+ require_paths:
49
+ - lib
50
+ required_ruby_version: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ required_rubygems_version: !ruby/object:Gem::Requirement
56
+ requirements:
57
+ - - ">="
58
+ - !ruby/object:Gem::Version
59
+ version: '0'
60
+ requirements: []
61
+ rubygems_version: 3.2.3
62
+ signing_key:
63
+ specification_version: 4
64
+ summary: Fast String#camelize implementation
65
+ test_files: []