|
| 1 | +# or more contributor license agreements. See the NOTICE file |
| 2 | +# distributed with this work for additional information |
| 3 | +# regarding copyright ownership. The ASF licenses this file |
| 4 | +# to you under the Apache License, Version 2.0 (the |
| 5 | +# "License"); you may not use this file except in compliance |
| 6 | +# with the License. You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, |
| 11 | +# software distributed under the License is distributed on an |
| 12 | +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 13 | +# KIND, either express or implied. See the License for the |
| 14 | +# specific language governing permissions and limitations |
| 15 | +# under the License. |
| 16 | + |
| 17 | +require_relative "buffer-alignable" |
| 18 | + |
| 19 | +module ArrowFormat |
| 20 | + class DenseBitmapBuilder |
| 21 | + include BufferAlignable |
| 22 | + |
| 23 | + def initialize |
| 24 | + @buffer = +"".b |
| 25 | + @n_bits = 0 |
| 26 | + @byte = 0 |
| 27 | + end |
| 28 | + |
| 29 | + def append(value) |
| 30 | + @byte |= 1 << @n_bits if value |
| 31 | + @n_bits += 1 |
| 32 | + flush if @n_bits == 8 |
| 33 | + self |
| 34 | + end |
| 35 | + |
| 36 | + def finish |
| 37 | + flush if @n_bits > 0 |
| 38 | + padding_size = buffer_padding_size(@buffer) |
| 39 | + @buffer.append_as_bytes(padding(padding_size)) if padding_size > 0 |
| 40 | + @buffer.freeze |
| 41 | + IO::Buffer.for(@buffer) |
| 42 | + end |
| 43 | + |
| 44 | + private |
| 45 | + def flush |
| 46 | + @buffer.append_as_bytes([@byte].pack("C")) |
| 47 | + @n_bits = 0 |
| 48 | + @byte = 0 |
| 49 | + end |
| 50 | + end |
| 51 | + |
| 52 | + class SparseBitmapBuilder |
| 53 | + include BufferAlignable |
| 54 | + |
| 55 | + def initialize(default) |
| 56 | + @default = default |
| 57 | + @indexes = [] |
| 58 | + end |
| 59 | + |
| 60 | + def set(index) |
| 61 | + @indexes << index |
| 62 | + end |
| 63 | + |
| 64 | + def finish(size) |
| 65 | + builder = DenseBitmapBuilder.new |
| 66 | + not_set_value = @default |
| 67 | + set_value = !@default |
| 68 | + previous_index = 0 |
| 69 | + @indexes.sort.each do |index| |
| 70 | + previous_index.upto(index - 1) do |
| 71 | + builder.append(not_set_value) |
| 72 | + end |
| 73 | + builder.append(set_value) |
| 74 | + previous_index = index + 1 |
| 75 | + end |
| 76 | + if previous_index.zero? |
| 77 | + n_remains = size |
| 78 | + else |
| 79 | + n_remains = size - previous_index |
| 80 | + end |
| 81 | + n_remains.times do |
| 82 | + builder.append(not_set_value) |
| 83 | + end |
| 84 | + builder.finish |
| 85 | + end |
| 86 | + end |
| 87 | +end |
0 commit comments