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