popcount 0.0.1 → 1.0.0

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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: a72937ff61a76dcbead04577f42cc34b15e5126b3fd9ccef5e0cffcd6d1a8878
4
+ data.tar.gz: c79783d678ebc97f811309d421716729f11a14314341e0af73397550ad6ae09e
5
+ SHA512:
6
+ metadata.gz: 3671ecd21cd74d38114976eb52566a4936933a85b1d9edfe0468c76840c4ce875e69c2c7adb19a7f7a2eab539fde2ea991cb1fc7b5b69a193818e5f2ab7fc72f
7
+ data.tar.gz: 22a96cff94c8dae60058999f949c16d89c6df18d269e17ba4ae1f72b00b9b4871cd3b7a5e046f0836fd30c9e451908b88bcc91c1db604888a7452805c10896d1
data/README.md CHANGED
@@ -1,6 +1,8 @@
1
1
  # PopCount
2
2
 
3
- This is library PopCount on Ruby.
3
+ [![CI](https://github.com/itochan/popcount/actions/workflows/ci.yml/badge.svg)](https://github.com/itochan/popcount/actions/workflows/ci.yml)
4
+
5
+ Population count (the number of set bits) for Ruby's `String`, `Integer` and `IO::Buffer`, implemented as a C extension.
4
6
 
5
7
  ## Installation
6
8
 
@@ -18,12 +20,86 @@ Or install it yourself as:
18
20
 
19
21
  ## Usage
20
22
 
21
- TODO: Write usage instructions here
23
+ ```ruby
24
+ require "popcount"
25
+
26
+ "Ruby".popcount # => 16 (set bits in the bytes of the string)
27
+ "あ".popcount # => 9 (counts bytes, not characters)
28
+ 255.popcount # => 8
29
+ (2**100 - 1).popcount # => 100 (Bignum works too)
30
+ -1.popcount # ArgumentError: popcount is undefined for negative integers
31
+
32
+ IO::Buffer.for("Ruby").popcount # => 16 (counts binary data without copying it into a String)
33
+ ```
34
+
35
+ Each of these classes gets three methods that always return the same result:
36
+
37
+ | Method | Implementation |
38
+ |---|---|
39
+ | `popcount` | 8 bytes at a time with the fastest routine available, chosen at load time (default; see below) |
40
+ | `popcount_cpu` | Alias of `popcount` (the 2011 name) |
41
+ | `popcount_table` | A 256-entry lookup table, byte by byte |
42
+
43
+ If another library already defines one of these methods, it is left untouched and a warning is printed when the gem is loaded.
44
+
45
+ The extension needs GCC or Clang (including RubyInstaller on Windows); with other compilers `popcount` falls back to the lookup table.
46
+
47
+ On x86, `popcount` uses the POPCNT instruction when the CPU has it; the choice is made when the gem is loaded, so it still runs on CPUs without POPCNT. `PopCount::CPU_IMPLEMENTATION` is a diagnostic name for the routine in use (currently `"popcnt"`, `"builtin"` or `"table"`; more may be added). Setting `POPCOUNT_DISABLE_POPCNT=1` before loading forces the plain builtin.
48
+
49
+ ### Ruby 4.1 and later
50
+
51
+ Ruby 4.1 adds `String#bit_count`, `Integer#bit_count` and `IO::Buffer#bit_count`, which count the same bits. On those Rubies this gem's methods are deprecated: each one warns once with category `:deprecated` (shown with `-W:deprecated` or `-w`) and still returns its own result. Switch to `bit_count` and drop the gem when you no longer support older Rubies.
52
+
53
+ ```
54
+ String#popcount is deprecated; use String#bit_count (built in since Ruby 4.1; the popcount gem is no longer needed)
55
+ ```
56
+
57
+ Whether Ruby itself has `bit_count` is checked when the gem is built (installed), so a `bit_count` that another library adds on an older Ruby does not trigger the warning.
58
+
59
+ ```ruby
60
+ "Ruby".popcount # Ruby 3.3 - 4.0 with this gem
61
+ "Ruby".bit_count # Ruby 4.1+, built in
62
+ ```
63
+
64
+ ### Migrating from 0.0.1
65
+
66
+ The `PopCount` class API has been removed. `PopCount` is now only a namespace for constants (`PopCount::VERSION` and `PopCount::CPU_IMPLEMENTATION`).
67
+
68
+ ```ruby
69
+ PopCount.new("Ruby").count # 0.0.1; now raises NoMethodError
70
+ "Ruby".popcount # use this instead
71
+ ```
72
+
73
+ ### Verifying a release
74
+
75
+ Releases from 1.0.0 on are published by GitHub Actions ([`release.yml`](.github/workflows/release.yml)) and carry three attestations:
76
+
77
+ - **RubyGems.org:** the gem is pushed with [Trusted Publishing](https://guides.rubygems.org/trusted-publishing/) and has a Sigstore attestation.
78
+ - **The `.gem` file:** GitHub build provenance links it to the commit and workflow run that built it.
79
+
80
+ $ gem fetch popcount --version 1.0.0
81
+ $ gh attestation verify popcount-1.0.0.gem --repo itochan/popcount
82
+
83
+ - **The GitHub Release:** releases are immutable, and GitHub signs each release and its `.gem` asset when they are published.
84
+
85
+ $ gh release verify v1.0.0 --repo itochan/popcount
86
+ $ gh release verify-asset v1.0.0 popcount-1.0.0.gem --repo itochan/popcount
87
+
88
+ ## Development
89
+
90
+ Tools are managed with [mise](https://mise.jdx.dev/) (`mise.toml`), and Git hooks and lint with [hk](https://hk.jdx.dev/) (`hk.pkl`).
91
+
92
+ $ mise install # Ruby, hk and the linters (see mise.toml)
93
+ $ bundle install # rake-compiler, RSpec, RuboCop
94
+ $ hk install --mise # pre-commit and commit-msg hooks (or `hk install --global --mise` on Git 2.54+)
95
+ $ bundle exec rake # compile the extension and run the specs
96
+ $ hk check --all # RuboCop, clang-format, gitleaks, typos, jactionlint, file hygiene checks
97
+ $ hk fix --all # apply the fixes
22
98
 
23
99
  ## Contributing
24
100
 
25
101
  1. Fork it
26
102
  2. Create your feature branch (`git checkout -b my-new-feature`)
27
- 3. Commit your changes (`git commit -am 'Added some feature'`)
103
+ 3. Commit your changes using [Conventional Commits](https://www.conventionalcommits.org/) (`git commit -am 'feat: add some feature'`)
28
104
  4. Push to the branch (`git push origin my-new-feature`)
29
105
  5. Create new Pull Request
data/Rakefile CHANGED
@@ -1,2 +1,22 @@
1
- #!/usr/bin/env rake
2
- require "bundler/gem_tasks"
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'rspec/core/rake_task'
5
+ require 'rake/extensiontask'
6
+
7
+ RSpec::Core::RakeTask.new(:spec)
8
+
9
+ Rake::Task['build'].enhance(['compile'])
10
+
11
+ GEMSPEC = Gem::Specification.load('popcount.gemspec')
12
+
13
+ Rake::ExtensionTask.new('popcount', GEMSPEC) do |ext|
14
+ ext.lib_dir = 'lib/popcount'
15
+ end
16
+
17
+ desc 'Compare String#popcount with String#popcount_table'
18
+ task bench: :compile do
19
+ ruby '-Ilib', 'bench/popcount.rb'
20
+ end
21
+
22
+ task default: %i[clobber compile spec]
@@ -0,0 +1,50 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'mkmf'
4
+
5
+ # Export only Init_popcount (marked RUBY_FUNC_EXPORTED in popcount.c).
6
+ append_cflags('-fvisibility=hidden')
7
+
8
+ # IO::Buffer#popcount needs IO::Buffer's C interface (Ruby marks it experimental).
9
+ have_func('rb_io_buffer_get_bytes_for_reading', 'ruby/io/buffer.h')
10
+
11
+ # x86: also build a POPCNT variant and pick it at load time when the CPU has
12
+ # POPCNT, without requiring it (-mpopcnt would break pre-2008 CPUs).
13
+ popcnt_dispatch = checking_for('x86 POPCNT runtime dispatch') do
14
+ try_link(<<~C)
15
+ #include <ruby.h>
16
+ #if !defined(__x86_64__) && !defined(__i386__)
17
+ #error not x86
18
+ #endif
19
+ #ifndef HAVE_BUILTIN___BUILTIN_POPCOUNTLL
20
+ #error the POPCNT variant needs HAVE_BUILTIN___BUILTIN_POPCOUNTLL from Ruby configure
21
+ #endif
22
+ __attribute__((target("popcnt"))) static int f(unsigned long long x) { return __builtin_popcountll(x); }
23
+ int main(void) { __builtin_cpu_init(); return __builtin_cpu_supports("popcnt") ? f(1) : 0; }
24
+ C
25
+ end
26
+ $defs.push('-DHAVE_POPCNT_DISPATCH') if popcnt_dispatch # rubocop:disable Style/GlobalVars -- mkmf's interface for defines
27
+
28
+ # Ruby 4.1 adds a built-in bit_count; popcount.c then deprecates this gem's
29
+ # methods on that class. This script runs in a fresh process of the Ruby being
30
+ # built for, but RUBYOPT (e.g. -r) can still load Ruby code first, so only a
31
+ # bit_count implemented in C (no source_location) counts; one that a library or
32
+ # backport defines in Ruby on an older Ruby does not.
33
+ { 'STRING' => String, 'INTEGER' => Integer, 'IO_BUFFER' => IO::Buffer }.each do |name, klass|
34
+ builtin = checking_for("built-in #{klass}#bit_count") do
35
+ klass.method_defined?(:bit_count) && klass.instance_method(:bit_count).source_location.nil?
36
+ end
37
+ $defs.push("-DBUILTIN_#{name}_BIT_COUNT=#{builtin ? 1 : 0}") # rubocop:disable Style/GlobalVars
38
+ end
39
+
40
+ # `rake compile -- --enable-werror` (CI) or `gem install popcount -- --enable-werror`.
41
+ # Added after the probes above: a warning in a probe would otherwise silently
42
+ # drop that feature instead of failing the build. Not append_cflags: it silently
43
+ # skips a flag whose test compile fails, which would leave CI without -Werror.
44
+ if enable_config('werror', false)
45
+ werror = checking_for('whether -Werror is accepted as CFLAGS') { try_cflags('-Werror') }
46
+ abort '--enable-werror: the compiler rejected -Werror; see mkmf.log' unless werror
47
+ $CFLAGS << ' -Werror' # rubocop:disable Style/GlobalVars -- mkmf's interface for compiler flags
48
+ end
49
+
50
+ create_makefile('popcount/popcount')
@@ -0,0 +1,401 @@
1
+ #include <ruby.h>
2
+ #ifdef HAVE_RB_IO_BUFFER_GET_BYTES_FOR_READING
3
+ #include <ruby/io/buffer.h>
4
+ #endif
5
+ #include <string.h>
6
+
7
+ /*
8
+ * The POPCNT variant is built from the builtin routine. extconf.rb only sets
9
+ * HAVE_POPCNT_DISPATCH when Ruby's configure found the builtin, but stay safe.
10
+ */
11
+ #if defined(HAVE_POPCNT_DISPATCH) && !defined(HAVE_BUILTIN___BUILTIN_POPCOUNTLL)
12
+ #undef HAVE_POPCNT_DISPATCH
13
+ #endif
14
+
15
+ /* Number of set bits for every byte value, built up 2 bits at a time. */
16
+ #define B2(n) n, n + 1, n + 1, n + 2
17
+ #define B4(n) B2(n), B2(n + 1), B2(n + 1), B2(n + 2)
18
+ #define B6(n) B4(n), B4(n + 1), B4(n + 1), B4(n + 2)
19
+ static const unsigned char popcount_table[256] = {B6(0), B6(1), B6(1), B6(2)};
20
+ #undef B6
21
+ #undef B4
22
+ #undef B2
23
+
24
+ typedef size_t (*popcount_bytes_func)(const unsigned char *, size_t);
25
+
26
+ /* Byte-wise lookup in popcount_table. */
27
+ static size_t popcount_bytes_table(const unsigned char *p, size_t len) {
28
+ size_t count = 0;
29
+ size_t i;
30
+
31
+ for (i = 0; i < len; i++) {
32
+ count += popcount_table[p[i]];
33
+ }
34
+ return count;
35
+ }
36
+
37
+ #ifdef HAVE_BUILTIN___BUILTIN_POPCOUNTLL /* set by Ruby's configure */
38
+ /*
39
+ * 8 bytes at a time with __builtin_popcountll; the remaining len % 8 bytes go
40
+ * through the lookup table. Words are loaded with memcpy, so the buffer needs
41
+ * no particular alignment and is never read past its end.
42
+ *
43
+ * Always inlined, so that each variant below compiles the builtin for its own
44
+ * target: plain x86_64 gets shifts and masks, the popcnt variant gets POPCNT.
45
+ */
46
+ static inline __attribute__((always_inline)) size_t
47
+ popcount_bytes_words(const unsigned char *p, size_t len) {
48
+ size_t count = 0;
49
+ size_t i = 0;
50
+ unsigned long long word;
51
+
52
+ for (; len - i >= sizeof(word); i += sizeof(word)) {
53
+ memcpy(&word, p + i, sizeof(word));
54
+ count += (size_t)__builtin_popcountll(word);
55
+ }
56
+ return count + popcount_bytes_table(p + i, len - i);
57
+ }
58
+
59
+ static size_t popcount_bytes_builtin(const unsigned char *p, size_t len) {
60
+ return popcount_bytes_words(p, len);
61
+ }
62
+
63
+ #ifdef HAVE_POPCNT_DISPATCH /* x86 only; see extconf.rb */
64
+ __attribute__((target("popcnt"))) static size_t
65
+ popcount_bytes_popcnt(const unsigned char *p, size_t len) {
66
+ return popcount_bytes_words(p, len);
67
+ }
68
+ #endif
69
+ #endif
70
+
71
+ /*
72
+ * popcount_bytes_cpu is the routine behind popcount / popcount_cpu. Only x86
73
+ * builds with POPCNT dispatch choose it at load time; elsewhere it is a direct
74
+ * call.
75
+ */
76
+ #ifdef HAVE_POPCNT_DISPATCH
77
+ static popcount_bytes_func popcount_bytes_cpu;
78
+ #elif defined(HAVE_BUILTIN___BUILTIN_POPCOUNTLL)
79
+ #define popcount_bytes_cpu popcount_bytes_builtin
80
+ #else
81
+ #define popcount_bytes_cpu popcount_bytes_table
82
+ #endif
83
+
84
+ /*
85
+ * Sets popcount_bytes_cpu where it is chosen at load time and returns its
86
+ * name. On x86 the POPCNT variant is used when the CPU has POPCNT, unless
87
+ * POPCOUNT_DISABLE_POPCNT is set (so CI can run the specs on both paths).
88
+ */
89
+ static const char *select_popcount_bytes_cpu(void) {
90
+ #ifdef HAVE_POPCNT_DISPATCH
91
+ const char *disable = getenv("POPCOUNT_DISABLE_POPCNT");
92
+
93
+ __builtin_cpu_init();
94
+ if (!(disable && *disable) && __builtin_cpu_supports("popcnt")) {
95
+ popcount_bytes_cpu = popcount_bytes_popcnt;
96
+ return "popcnt";
97
+ }
98
+ popcount_bytes_cpu = popcount_bytes_builtin;
99
+ return "builtin";
100
+ #elif defined(HAVE_BUILTIN___BUILTIN_POPCOUNTLL)
101
+ return "builtin";
102
+ #else
103
+ return "table";
104
+ #endif
105
+ }
106
+
107
+ /*
108
+ * Ruby 4.1 adds String#bit_count, Integer#bit_count and IO::Buffer#bit_count.
109
+ * extconf.rb sets BUILTIN_<CLASS>_BIT_COUNT to 1 for each class whose
110
+ * bit_count is built into the Ruby being built for, so one added by a library
111
+ * or backport never counts. For such a class, each popcount method warns once
112
+ * per process with category :deprecated (shown with -W:deprecated) and keeps
113
+ * counting with this gem's routines. The flags may race across Ractors; the
114
+ * worst case is a duplicate warning.
115
+ */
116
+ enum receiver {
117
+ RECEIVER_STRING,
118
+ RECEIVER_INTEGER,
119
+ RECEIVER_IO_BUFFER,
120
+ RECEIVER_COUNT
121
+ };
122
+ #define POPCOUNT_METHOD_COUNT 3
123
+ /* Also listed for RDoc at the end of Init_popcount. */
124
+ static const char *const popcount_method_names[POPCOUNT_METHOD_COUNT] = {
125
+ "popcount", "popcount_cpu", "popcount_table"};
126
+ static ID popcount_method_ids[POPCOUNT_METHOD_COUNT];
127
+ static VALUE receiver_classes[RECEIVER_COUNT];
128
+ /*
129
+ * Bit i is set while this gem's popcount_method_names[i] has yet to warn. It
130
+ * is 0 for a class without a built-in bit_count, and drops to 0 once every
131
+ * method this gem defined has warned, so the usual cost is a single check.
132
+ */
133
+ static unsigned pending_warnings[RECEIVER_COUNT];
134
+
135
+ static void warn_if_superseded(enum receiver receiver) {
136
+ ID method;
137
+ int i;
138
+
139
+ if (!pending_warnings[receiver]) {
140
+ return;
141
+ }
142
+ method = rb_frame_this_func(); /* the defined name, even through an alias */
143
+ for (i = 0; i < POPCOUNT_METHOD_COUNT; i++) {
144
+ if (method == popcount_method_ids[i]) {
145
+ if (pending_warnings[receiver] & (1u << i)) {
146
+ VALUE name = rb_class_name(receiver_classes[receiver]);
147
+
148
+ pending_warnings[receiver] &= ~(1u << i);
149
+ rb_category_warn(RB_WARN_CATEGORY_DEPRECATED,
150
+ "%" PRIsVALUE "#%s is deprecated; use %" PRIsVALUE
151
+ "#bit_count (built in since Ruby 4.1; the popcount "
152
+ "gem is no longer needed)",
153
+ name, popcount_method_names[i], name);
154
+ }
155
+ break;
156
+ }
157
+ }
158
+ }
159
+
160
+ static VALUE str_popcount_with(VALUE str, popcount_bytes_func f) {
161
+ /*
162
+ * Warn before reading the bytes: a Warning.warn override can run Ruby code
163
+ * that resizes str, so its pointer and length must be fetched afterwards.
164
+ */
165
+ warn_if_superseded(RECEIVER_STRING);
166
+ return SIZET2NUM(
167
+ f((const unsigned char *)RSTRING_PTR(str), (size_t)RSTRING_LEN(str)));
168
+ }
169
+
170
+ /*
171
+ * call-seq:
172
+ * popcount -> integer
173
+ * popcount_cpu -> integer
174
+ *
175
+ * Returns the number of set bits in the bytes of +self+, counted 8 bytes at a
176
+ * time with the routine chosen at load time (see PopCount::CPU_IMPLEMENTATION).
177
+ *
178
+ * "Ruby".popcount # => 16
179
+ *
180
+ * Deprecated on Ruby 4.1 and later; use the built-in String#bit_count.
181
+ */
182
+ static VALUE str_popcount(VALUE self) {
183
+ return str_popcount_with(self, popcount_bytes_cpu);
184
+ }
185
+
186
+ /*
187
+ * call-seq:
188
+ * popcount_table -> integer
189
+ *
190
+ * Same as #popcount, but counts byte by byte with a 256-entry lookup table.
191
+ *
192
+ * Deprecated on Ruby 4.1 and later; use the built-in String#bit_count.
193
+ */
194
+ static VALUE str_popcount_table(VALUE self) {
195
+ return str_popcount_with(self, popcount_bytes_table);
196
+ }
197
+
198
+ NORETURN(static void raise_negative_integer(void));
199
+ static void raise_negative_integer(void) {
200
+ rb_raise(rb_eArgError, "popcount is undefined for negative integers");
201
+ }
202
+
203
+ static VALUE int_popcount_with(VALUE num, popcount_bytes_func f) {
204
+ size_t size;
205
+ VALUE tmp;
206
+ unsigned char *bytes;
207
+ size_t count;
208
+
209
+ warn_if_superseded(RECEIVER_INTEGER);
210
+ if (FIXNUM_P(num)) {
211
+ long value = FIX2LONG(num);
212
+ unsigned long long word;
213
+
214
+ if (value < 0) {
215
+ raise_negative_integer();
216
+ }
217
+ word = (unsigned long long)value;
218
+ return SIZET2NUM(f((const unsigned char *)&word, sizeof(word)));
219
+ }
220
+
221
+ if (RBIGNUM_NEGATIVE_P(num)) {
222
+ raise_negative_integer();
223
+ }
224
+ /* Pack the Bignum into bytes with the public API. */
225
+ size = rb_absint_size(num, NULL);
226
+ bytes = ALLOCV_N(unsigned char, tmp, size);
227
+ rb_integer_pack(num, bytes, size, 1, 0, INTEGER_PACK_LITTLE_ENDIAN);
228
+ count = f(bytes, size);
229
+ ALLOCV_END(tmp);
230
+ return SIZET2NUM(count);
231
+ }
232
+
233
+ /*
234
+ * call-seq:
235
+ * popcount -> integer
236
+ * popcount_cpu -> integer
237
+ *
238
+ * Returns the number of set bits in the binary representation of +self+.
239
+ * Raises ArgumentError for negative integers, whose two's complement has
240
+ * infinitely many set bits.
241
+ *
242
+ * 255.popcount # => 8
243
+ * (2**100).popcount # => 1
244
+ *
245
+ * Deprecated on Ruby 4.1 and later; use the built-in Integer#bit_count.
246
+ */
247
+ static VALUE int_popcount(VALUE self) {
248
+ return int_popcount_with(self, popcount_bytes_cpu);
249
+ }
250
+
251
+ /*
252
+ * call-seq:
253
+ * popcount_table -> integer
254
+ *
255
+ * Same as #popcount, but counts byte by byte with a 256-entry lookup table.
256
+ *
257
+ * Deprecated on Ruby 4.1 and later; use the built-in Integer#bit_count.
258
+ */
259
+ static VALUE int_popcount_table(VALUE self) {
260
+ return int_popcount_with(self, popcount_bytes_table);
261
+ }
262
+
263
+ #ifdef HAVE_RB_IO_BUFFER_GET_BYTES_FOR_READING
264
+ /*
265
+ * IO::Buffer's C interface is marked experimental by Ruby, so it is only used
266
+ * when extconf.rb finds it. The count neither releases the GVL nor calls back
267
+ * into Ruby, so the buffer cannot change underneath it.
268
+ */
269
+ static VALUE io_buffer_popcount_with(VALUE buffer, popcount_bytes_func f) {
270
+ const void *base;
271
+ size_t size;
272
+
273
+ warn_if_superseded(RECEIVER_IO_BUFFER);
274
+ rb_io_buffer_get_bytes_for_reading(buffer, &base, &size);
275
+ /*
276
+ * An empty buffer (IO::Buffer.new(0), a freed buffer) has no memory, so
277
+ * base is NULL, and NULL + 0 in the routines is undefined before C2y.
278
+ */
279
+ if (size == 0) {
280
+ return INT2FIX(0);
281
+ }
282
+ return SIZET2NUM(f(base, size));
283
+ }
284
+
285
+ /*
286
+ * call-seq:
287
+ * popcount -> integer
288
+ * popcount_cpu -> integer
289
+ *
290
+ * Returns the number of set bits in the bytes of +self+, without copying them
291
+ * into a String.
292
+ *
293
+ * IO::Buffer.for("Ruby").popcount # => 16
294
+ *
295
+ * Deprecated on Ruby 4.1 and later; use the built-in IO::Buffer#bit_count.
296
+ */
297
+ static VALUE io_buffer_popcount(VALUE self) {
298
+ return io_buffer_popcount_with(self, popcount_bytes_cpu);
299
+ }
300
+
301
+ /*
302
+ * call-seq:
303
+ * popcount_table -> integer
304
+ *
305
+ * Same as #popcount, but counts byte by byte with a 256-entry lookup table.
306
+ *
307
+ * Deprecated on Ruby 4.1 and later; use the built-in IO::Buffer#bit_count.
308
+ */
309
+ static VALUE io_buffer_popcount_table(VALUE self) {
310
+ return io_buffer_popcount_with(self, popcount_bytes_table);
311
+ }
312
+ #endif
313
+
314
+ /*
315
+ * Defines klass#name unless something else already defines it. Returns
316
+ * whether it defined the method.
317
+ */
318
+ static int define_popcount(VALUE klass, const char *name,
319
+ VALUE (*func)(VALUE)) {
320
+ /* 1 (BOUND_PRIVATE) ignores private methods, e.g. a top-level def. */
321
+ if (rb_method_boundp(klass, rb_intern(name), 1)) {
322
+ rb_warn("%" PRIsVALUE
323
+ "#%s is already defined; popcount does not override it",
324
+ rb_class_name(klass), name);
325
+ return 0;
326
+ }
327
+ rb_define_method(klass, name, func, 0);
328
+ return 1;
329
+ }
330
+
331
+ /*
332
+ * popcount and popcount_cpu share popcount_bytes_cpu (chosen at load time);
333
+ * popcount_table always uses the lookup table. builtin_bit_count (from
334
+ * extconf.rb) makes these methods warn (see warn_if_superseded).
335
+ */
336
+ static void define_popcounts(VALUE klass, enum receiver receiver,
337
+ int builtin_bit_count, VALUE (*cpu)(VALUE),
338
+ VALUE (*table)(VALUE)) {
339
+ VALUE (*const funcs[POPCOUNT_METHOD_COUNT])(VALUE) = {cpu, cpu, table};
340
+ int i;
341
+
342
+ receiver_classes[receiver] = klass;
343
+ if (builtin_bit_count) {
344
+ pending_warnings[receiver] = (1u << POPCOUNT_METHOD_COUNT) - 1;
345
+ }
346
+ for (i = 0; i < POPCOUNT_METHOD_COUNT; i++) {
347
+ if (!define_popcount(klass, popcount_method_names[i], funcs[i])) {
348
+ /* The existing method is not this gem's, so it never warns. */
349
+ pending_warnings[receiver] &= ~(1u << i);
350
+ }
351
+ }
352
+ }
353
+
354
+ /* Exported explicitly: extconf.rb builds with -fvisibility=hidden. */
355
+ RUBY_FUNC_EXPORTED void Init_popcount(void) {
356
+ VALUE popcount_module;
357
+ int i;
358
+
359
+ rb_ext_ractor_safe(true);
360
+
361
+ popcount_module = rb_define_module("PopCount"); /* a variable for RDoc */
362
+ /* A diagnostic name for the routine behind popcount, e.g. "popcnt". */
363
+ rb_define_const(popcount_module, "CPU_IMPLEMENTATION",
364
+ rb_interned_str_cstr(select_popcount_bytes_cpu()));
365
+
366
+ for (i = 0; i < POPCOUNT_METHOD_COUNT; i++) {
367
+ popcount_method_ids[i] = rb_intern(popcount_method_names[i]);
368
+ }
369
+ define_popcounts(rb_cString, RECEIVER_STRING, BUILTIN_STRING_BIT_COUNT,
370
+ str_popcount, str_popcount_table);
371
+ define_popcounts(rb_cInteger, RECEIVER_INTEGER, BUILTIN_INTEGER_BIT_COUNT,
372
+ int_popcount, int_popcount_table);
373
+ #ifdef HAVE_RB_IO_BUFFER_GET_BYTES_FOR_READING
374
+ define_popcounts(rb_cIOBuffer, RECEIVER_IO_BUFFER,
375
+ BUILTIN_IO_BUFFER_BIT_COUNT, io_buffer_popcount,
376
+ io_buffer_popcount_table);
377
+ #endif
378
+
379
+ /*
380
+ * Never compiled. RDoc's C parser only finds methods defined with a string
381
+ * literal, so it cannot see the names define_popcounts takes from
382
+ * popcount_method_names; these lines tell it what is defined above, and
383
+ * give it IO::Buffer, which this file does not define. Keep them in sync
384
+ * (spec/pop_count_spec.rb checks). RDoc takes a comment right before a
385
+ * class or module definition as its documentation, so none goes there
386
+ * (nor before rb_define_module above).
387
+ */
388
+ #if 0
389
+ rb_cIOBuffer = rb_define_class_under(rb_cIO, "Buffer", rb_cObject);
390
+ rb_define_method(rb_cString, "popcount", str_popcount, 0);
391
+ rb_define_alias(rb_cString, "popcount_cpu", "popcount");
392
+ rb_define_method(rb_cString, "popcount_table", str_popcount_table, 0);
393
+ rb_define_method(rb_cInteger, "popcount", int_popcount, 0);
394
+ rb_define_alias(rb_cInteger, "popcount_cpu", "popcount");
395
+ rb_define_method(rb_cInteger, "popcount_table", int_popcount_table, 0);
396
+ rb_define_method(rb_cIOBuffer, "popcount", io_buffer_popcount, 0);
397
+ rb_define_alias(rb_cIOBuffer, "popcount_cpu", "popcount");
398
+ rb_define_method(rb_cIOBuffer, "popcount_table", io_buffer_popcount_table,
399
+ 0);
400
+ #endif
401
+ }
@@ -1,3 +1,7 @@
1
- class PopCount
2
- VERSION = "0.0.1"
1
+ # frozen_string_literal: true
2
+
3
+ # Namespace for the gem's constants: VERSION, and CPU_IMPLEMENTATION (defined by
4
+ # the extension). The counting methods live on String, Integer and IO::Buffer.
5
+ module PopCount
6
+ VERSION = '1.0.0'
3
7
  end
data/lib/popcount.rb CHANGED
@@ -1,5 +1,4 @@
1
- require "popcount/version"
2
- require File.join(File.dirname(__FILE__), "..", "ext", "popcount")
1
+ # frozen_string_literal: true
3
2
 
4
- class PopCount
5
- end
3
+ require_relative 'popcount/version'
4
+ require 'popcount/popcount'
metadata CHANGED
@@ -1,61 +1,56 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: popcount
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.0.1
5
- prerelease:
4
+ version: 1.0.0
6
5
  platform: ruby
7
6
  authors:
8
7
  - itochan
9
- autorequire:
10
8
  bindir: bin
11
9
  cert_chain: []
12
- date: 2012-06-05 00:00:00.000000000 Z
10
+ date: 1980-01-02 00:00:00.000000000 Z
13
11
  dependencies: []
14
- description: This is library PopCount on Ruby.
12
+ description: 'Adds String#popcount, Integer#popcount and IO::Buffer#popcount (plus
13
+ #popcount_cpu and #popcount_table), implemented as a C extension using the compiler
14
+ popcount builtin or a lookup table.'
15
15
  email:
16
16
  - itochan315@gmail.com
17
17
  executables: []
18
18
  extensions:
19
- - ext/extconf.rb
19
+ - ext/popcount/extconf.rb
20
20
  extra_rdoc_files: []
21
21
  files:
22
- - .gitignore
23
- - .rspec
24
- - Gemfile
25
22
  - LICENSE
26
23
  - README.md
27
24
  - Rakefile
28
- - ext/extconf.rb
29
- - ext/popcount.c
25
+ - ext/popcount/extconf.rb
26
+ - ext/popcount/popcount.c
30
27
  - lib/popcount.rb
31
28
  - lib/popcount/version.rb
32
- - popcount.gemspec
33
- - spec/popcount_spec.rb
34
- - spec/spec_helper.rb
35
29
  homepage: https://github.com/itochan/popcount
36
- licenses: []
37
- post_install_message:
30
+ licenses:
31
+ - MIT
32
+ metadata:
33
+ allowed_push_host: https://rubygems.org
34
+ homepage_uri: https://github.com/itochan/popcount
35
+ source_code_uri: https://github.com/itochan/popcount/tree/v1.0.0
36
+ changelog_uri: https://github.com/itochan/popcount/releases/tag/v1.0.0
37
+ bug_tracker_uri: https://github.com/itochan/popcount/issues
38
+ rubygems_mfa_required: 'true'
38
39
  rdoc_options: []
39
40
  require_paths:
40
41
  - lib
41
42
  required_ruby_version: !ruby/object:Gem::Requirement
42
- none: false
43
43
  requirements:
44
- - - ! '>='
44
+ - - ">="
45
45
  - !ruby/object:Gem::Version
46
- version: '0'
46
+ version: '3.3'
47
47
  required_rubygems_version: !ruby/object:Gem::Requirement
48
- none: false
49
48
  requirements:
50
- - - ! '>='
49
+ - - ">="
51
50
  - !ruby/object:Gem::Version
52
51
  version: '0'
53
52
  requirements: []
54
- rubyforge_project:
55
- rubygems_version: 1.8.24
56
- signing_key:
57
- specification_version: 3
58
- summary: PopCount on Ruby.
59
- test_files:
60
- - spec/popcount_spec.rb
61
- - spec/spec_helper.rb
53
+ rubygems_version: 4.0.20
54
+ specification_version: 4
55
+ summary: Population count (number of set bits) for String, Integer and IO::Buffer.
56
+ test_files: []
data/.gitignore DELETED
@@ -1,32 +0,0 @@
1
- *.gem
2
- *.rbc
3
- .bundle
4
- .config
5
- .yardoc
6
- Gemfile.lock
7
- InstalledFiles
8
- _yardoc
9
- coverage
10
- doc/
11
- lib/bundler/man
12
- pkg
13
- rdoc
14
- spec/reports
15
- test/tmp
16
- test/version_tmp
17
- tmp
18
-
19
- # Object files
20
- *.o
21
-
22
- # Libraries
23
- *.lib
24
-
25
- # Shared objects (inc. Windows DLLs)
26
- *.dll
27
- *.so
28
- *.bundle
29
-
30
- # Executables
31
- *.exe
32
- *.out
data/.rspec DELETED
@@ -1,2 +0,0 @@
1
- --color
2
- --format progress
data/Gemfile DELETED
@@ -1,9 +0,0 @@
1
- source :rubygems
2
-
3
- # Specify your gem's dependencies in popcount.gemspec
4
- gemspec
5
-
6
- group :development do
7
- gem "rspec", ">= 2.10.0"
8
- gem "simplecov", ">= 0.6.4"
9
- end
data/ext/extconf.rb DELETED
@@ -1,2 +0,0 @@
1
- require "mkmf"
2
- create_makefile("popcount")
data/ext/popcount.c DELETED
@@ -1,45 +0,0 @@
1
- #include <ruby.h>
2
-
3
- VALUE initialize_m(VALUE, VALUE);
4
- VALUE count_m(VALUE);
5
- VALUE count_cpu_m(VALUE);
6
-
7
- void Init_popcount(void) {
8
- VALUE cPopCount = rb_define_class("PopCount", rb_cObject);
9
- rb_define_private_method(cPopCount, "initialize", initialize_m, 1);
10
- rb_define_method(cPopCount, "count", count_m, 0);
11
- rb_define_method(cPopCount, "count_cpu", count_cpu_m, 0);
12
- }
13
-
14
- VALUE initialize_m(VALUE self, VALUE value) {
15
- rb_ivar_set(self, rb_intern("@value"), value);
16
- }
17
-
18
- VALUE count_m(VALUE self) {
19
- VALUE value = rb_ivar_get(self, rb_intern("@value"));
20
- int count = 0;
21
- int i;
22
- unsigned char *p;
23
- static const char array[256] = {0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8};
24
-
25
- p = RSTRING_PTR(value);
26
- for (i = 0; i < RSTRING_LEN(value); i++) {
27
- count += array[*p++];
28
- }
29
-
30
- return INT2FIX(count);
31
- }
32
-
33
- VALUE count_cpu_m(VALUE self) {
34
- VALUE value = rb_ivar_get(self, rb_intern("@value"));
35
- int count = 0;
36
- int i;
37
- long long *p;
38
-
39
- p = (long long *)RSTRING_PTR(value);
40
- for (i = 0; i < RSTRING_LEN(value); i += sizeof(long long)) {
41
- count += __builtin_popcountll(*p++);
42
- }
43
-
44
- return INT2FIX(count);
45
- }
data/popcount.gemspec DELETED
@@ -1,18 +0,0 @@
1
- # -*- encoding: utf-8 -*-
2
- require File.expand_path('../lib/popcount/version', __FILE__)
3
-
4
- Gem::Specification.new do |gem|
5
- gem.authors = ["itochan"]
6
- gem.email = ["itochan315@gmail.com"]
7
- gem.description = %q{This is library PopCount on Ruby.}
8
- gem.summary = %q{PopCount on Ruby.}
9
- gem.homepage = "https://github.com/itochan/popcount"
10
-
11
- gem.files = `git ls-files`.split($\)
12
- gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
13
- gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
14
- gem.name = "popcount"
15
- gem.require_paths = ["lib"]
16
- gem.extensions = ["ext/extconf.rb"]
17
- gem.version = PopCount::VERSION
18
- end
@@ -1,8 +0,0 @@
1
- require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
2
-
3
- describe PopCount do
4
- it "string popcount" do
5
- pc = PopCount.new("Ruby")
6
- pc.count.should eq 16
7
- end
8
- end
data/spec/spec_helper.rb DELETED
@@ -1,17 +0,0 @@
1
- $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
2
- $LOAD_PATH.unshift(File.dirname(__FILE__))
3
- require 'rspec'
4
- require 'simplecov'
5
- require 'popcount'
6
-
7
- # This file was generated by the `rspec --init` command. Conventionally, all
8
- # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
9
- # Require this file using `require "spec_helper.rb"` to ensure that it is only
10
- # loaded once.
11
- #
12
- # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
13
- RSpec.configure do |config|
14
- config.treat_symbols_as_metadata_keys_with_true_values = true
15
- config.run_all_when_everything_filtered = true
16
- config.filter_run :focus
17
- end