-
Notifications
You must be signed in to change notification settings - Fork 9k
Expand file tree
/
Copy pathFunctionsBitToArray.cpp
More file actions
441 lines (374 loc) · 17.7 KB
/
Copy pathFunctionsBitToArray.cpp
File metadata and controls
441 lines (374 loc) · 17.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
#include <Columns/ColumnArray.h>
#include <Columns/ColumnString.h>
#include <Columns/ColumnVector.h>
#include <DataTypes/DataTypeArray.h>
#include <DataTypes/DataTypeString.h>
#include <DataTypes/DataTypesNumber.h>
#include <Functions/FunctionFactory.h>
#include <Functions/IFunction.h>
#include <IO/WriteBufferFromVector.h>
#include <IO/WriteHelpers.h>
#include <bit>
namespace DB
{
namespace ErrorCodes
{
extern const int ILLEGAL_TYPE_OF_ARGUMENT;
extern const int ILLEGAL_COLUMN;
}
/** Functions for an unusual conversion to a string or array:
*
* bitmaskToList - takes an integer - a bitmask, returns a string of degrees of 2 separated by a comma.
* for example, bitmaskToList(50) = '2,16,32'
*
* bitmaskToArray(x) - Returns an array of powers of two in the binary form of x. For example, bitmaskToArray(50) = [2, 16, 32].
*
*/
namespace
{
class FunctionBitmaskToList final : public IFunction
{
public:
static constexpr auto name = "bitmaskToList";
static FunctionPtr create(ContextPtr) { return std::make_shared<FunctionBitmaskToList>(); }
String getName() const override
{
return name;
}
size_t getNumberOfArguments() const override { return 1; }
bool isInjective(const ColumnsWithTypeAndName &) const override { return true; }
bool isSuitableForShortCircuitArgumentsExecution(const DataTypesWithConstInfo & /*arguments*/) const override { return true; }
DataTypePtr getReturnTypeImpl(const DataTypes & arguments) const override
{
const DataTypePtr & type = arguments[0];
if (!isInteger(type))
throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "Cannot format {} as bitmask string", type->getName());
return std::make_shared<DataTypeString>();
}
DataTypePtr getReturnTypeForDefaultImplementationForDynamic() const override
{
return std::make_shared<DataTypeString>();
}
bool useDefaultImplementationForConstants() const override { return true; }
ColumnPtr executeImpl(const ColumnsWithTypeAndName & arguments, const DataTypePtr &, size_t input_rows_count) const override
{
ColumnPtr res;
if (!((res = executeType<UInt8>(arguments, input_rows_count))
|| (res = executeType<UInt16>(arguments, input_rows_count))
|| (res = executeType<UInt32>(arguments, input_rows_count))
|| (res = executeType<UInt64>(arguments, input_rows_count))
|| (res = executeType<UInt128>(arguments, input_rows_count))
|| (res = executeType<UInt256>(arguments, input_rows_count))
|| (res = executeType<Int8>(arguments, input_rows_count))
|| (res = executeType<Int16>(arguments, input_rows_count))
|| (res = executeType<Int32>(arguments, input_rows_count))
|| (res = executeType<Int64>(arguments, input_rows_count))
|| (res = executeType<Int128>(arguments, input_rows_count))
|| (res = executeType<Int256>(arguments, input_rows_count))))
throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of argument of function {}",
arguments[0].column->getName(), getName());
return res;
}
private:
template <typename T>
static void writeBitmask(T x, WriteBuffer & out)
{
using UnsignedT = make_unsigned_t<T>;
UnsignedT u_x = x;
bool first = true;
while (u_x)
{
UnsignedT y = u_x & (u_x - 1);
UnsignedT bit = u_x ^ y;
u_x = y;
if (!first)
writeChar(',', out);
first = false;
writeIntText(static_cast<T>(bit), out);
}
}
template <typename T>
ColumnPtr executeType(const ColumnsWithTypeAndName & columns, size_t input_rows_count) const
{
if (const ColumnVector<T> * col_from = checkAndGetColumn<ColumnVector<T>>(columns[0].column.get()))
{
auto col_to = ColumnString::create();
const typename ColumnVector<T>::Container & vec_from = col_from->getData();
ColumnString::Chars & data_to = col_to->getChars();
ColumnString::Offsets & offsets_to = col_to->getOffsets();
data_to.resize(input_rows_count * 2);
offsets_to.resize(input_rows_count);
WriteBufferFromVector<ColumnString::Chars> buf_to(data_to);
for (size_t i = 0; i < input_rows_count; ++i)
{
writeBitmask<T>(vec_from[i], buf_to);
offsets_to[i] = buf_to.count();
}
buf_to.finalize();
return col_to;
}
return nullptr;
}
};
class FunctionBitmaskToArray final : public IFunction
{
public:
static constexpr auto name = "bitmaskToArray";
static FunctionPtr create(ContextPtr) { return std::make_shared<FunctionBitmaskToArray>(); }
String getName() const override
{
return name;
}
size_t getNumberOfArguments() const override { return 1; }
bool isInjective(const ColumnsWithTypeAndName &) const override { return true; }
bool isSuitableForShortCircuitArgumentsExecution(const DataTypesWithConstInfo & /*arguments*/) const override { return true; }
DataTypePtr getReturnTypeImpl(const DataTypes & arguments) const override
{
if (!isInteger(arguments[0]))
throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "Illegal type {} of argument of function {}",
arguments[0]->getName(), getName());
return std::make_shared<DataTypeArray>(arguments[0]);
}
bool useDefaultImplementationForConstants() const override { return true; }
template <typename T>
bool tryExecute(const IColumn * column, ColumnPtr & out_column) const
{
using UnsignedT = make_unsigned_t<T>;
if (const ColumnVector<T> * col_from = checkAndGetColumn<ColumnVector<T>>(column))
{
auto col_values = ColumnVector<T>::create();
auto col_offsets = ColumnArray::ColumnOffsets::create();
typename ColumnVector<T>::Container & res_values = col_values->getData();
ColumnArray::Offsets & res_offsets = col_offsets->getData();
const typename ColumnVector<T>::Container & vec_from = col_from->getData();
size_t size = vec_from.size();
res_offsets.resize(size);
res_values.reserve(size * 2);
for (size_t row = 0; row < size; ++row)
{
UnsignedT x = vec_from[row];
while (x)
{
UnsignedT y = x & (x - 1);
UnsignedT bit = x ^ y;
x = y;
res_values.push_back(bit);
}
res_offsets[row] = res_values.size();
}
out_column = ColumnArray::create(std::move(col_values), std::move(col_offsets));
return true;
}
return false;
}
ColumnPtr executeImpl(const ColumnsWithTypeAndName & arguments, const DataTypePtr &, size_t /*input_rows_count*/) const override
{
const IColumn * in_column = arguments[0].column.get();
ColumnPtr out_column;
if (tryExecute<UInt8>(in_column, out_column) ||
tryExecute<UInt16>(in_column, out_column) ||
tryExecute<UInt32>(in_column, out_column) ||
tryExecute<UInt64>(in_column, out_column) ||
tryExecute<UInt128>(in_column, out_column) ||
tryExecute<UInt256>(in_column, out_column) ||
tryExecute<Int8>(in_column, out_column) ||
tryExecute<Int16>(in_column, out_column) ||
tryExecute<Int32>(in_column, out_column) ||
tryExecute<Int64>(in_column, out_column) ||
tryExecute<Int128>(in_column, out_column) ||
tryExecute<Int256>(in_column, out_column))
return out_column;
throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of first argument of function {}",
arguments[0].column->getName(), getName());
}
};
class FunctionBitPositionsToArray final : public IFunction
{
public:
static constexpr auto name = "bitPositionsToArray";
static FunctionPtr create(ContextPtr) { return std::make_shared<FunctionBitPositionsToArray>(); }
String getName() const override
{
return name;
}
size_t getNumberOfArguments() const override { return 1; }
bool isInjective(const ColumnsWithTypeAndName &) const override { return true; }
bool isSuitableForShortCircuitArgumentsExecution(const DataTypesWithConstInfo & /*arguments*/) const override { return true; }
DataTypePtr getReturnTypeImpl(const DataTypes & arguments) const override
{
if (!isInteger(arguments[0]))
throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT,
"Illegal type {} of argument of function {}",
getName(),
arguments[0]->getName());
return std::make_shared<DataTypeArray>(std::make_shared<DataTypeUInt64>());
}
DataTypePtr getReturnTypeForDefaultImplementationForDynamic() const override
{
return std::make_shared<DataTypeArray>(std::make_shared<DataTypeUInt64>());
}
bool useDefaultImplementationForConstants() const override { return true; }
template <typename T>
ColumnPtr executeType(const IColumn * column, size_t input_rows_count) const
{
const ColumnVector<T> * col_from = checkAndGetColumn<ColumnVector<T>>(column);
if (!col_from)
return nullptr;
auto result_array_values = ColumnVector<UInt64>::create();
auto result_array_offsets = ColumnArray::ColumnOffsets::create();
auto & result_array_values_data = result_array_values->getData();
auto & result_array_offsets_data = result_array_offsets->getData();
auto & vec_from = col_from->getData();
result_array_offsets_data.resize(input_rows_count);
result_array_values_data.reserve(input_rows_count * 2);
using UnsignedType = make_unsigned_t<T>;
for (size_t row = 0; row < input_rows_count; ++row)
{
UnsignedType x = static_cast<UnsignedType>(vec_from[row]);
if constexpr (is_big_int_v<UnsignedType>)
{
for (unsigned limb = 0; limb < UnsignedType::_impl::item_count; ++limb)
{
UInt64 item = x.items[UnsignedType::_impl::little(limb)];
while (item)
{
result_array_values_data.push_back(limb * 64 + std::countr_zero(item));
item &= (item - 1);
}
}
}
else
{
while (x)
{
/// С++20 char8_t is not an unsigned integral type anymore https://godbolt.org/z/Mqcb7qn58
/// and thus you cannot use std::countr_zero on it.
if constexpr (std::is_same_v<UnsignedType, UInt8>)
result_array_values_data.push_back(std::countr_zero(static_cast<unsigned char>(x)));
else
result_array_values_data.push_back(std::countr_zero(x));
x &= (x - 1);
}
}
result_array_offsets_data[row] = result_array_values_data.size();
}
auto result_column = ColumnArray::create(std::move(result_array_values), std::move(result_array_offsets));
return result_column;
}
ColumnPtr executeImpl(const ColumnsWithTypeAndName & arguments, const DataTypePtr &, size_t input_rows_count) const override
{
const IColumn * in_column = arguments[0].column.get();
ColumnPtr result_column;
if (!((result_column = executeType<UInt8>(in_column, input_rows_count))
|| (result_column = executeType<UInt16>(in_column, input_rows_count))
|| (result_column = executeType<UInt32>(in_column, input_rows_count))
|| (result_column = executeType<UInt64>(in_column, input_rows_count))
|| (result_column = executeType<UInt128>(in_column, input_rows_count))
|| (result_column = executeType<UInt256>(in_column, input_rows_count))
|| (result_column = executeType<Int8>(in_column, input_rows_count))
|| (result_column = executeType<Int16>(in_column, input_rows_count))
|| (result_column = executeType<Int32>(in_column, input_rows_count))
|| (result_column = executeType<Int64>(in_column, input_rows_count))
|| (result_column = executeType<Int128>(in_column, input_rows_count))
|| (result_column = executeType<Int256>(in_column, input_rows_count))))
{
throw Exception(ErrorCodes::ILLEGAL_COLUMN,
"Illegal column {} of first argument of function {}",
arguments[0].column->getName(),
getName());
}
return result_column;
}
};
}
REGISTER_FUNCTION(BitToArray)
{
FunctionDocumentation::Description bitPositionsToArray_description = R"(
This function returns the positions (in ascending order) of the 1 bits in the binary representation of an unsigned integer.
Signed input integers are first casted to an unsigned integer.
)";
FunctionDocumentation::Syntax bitPositionsToArray_syntax = "bitPositionsToArray(arg)";
FunctionDocumentation::Arguments bitPositionsToArray_arguments = {
{"arg", "An integer value.", {"(U)Int*"}}
};
FunctionDocumentation::ReturnedValue bitPositionsToArray_returned_value = {"Returns an array with the ascendingly ordered positions of 1 bits in the binary representation of the input.", {"Array(UInt64)"}};
FunctionDocumentation::Examples bitPositionsToArray_examples =
{
{
"Single bit set",
"SELECT bitPositionsToArray(toInt8(1)) AS bit_positions",
R"(
┌─bit_positions─┐
│ [0] │
└───────────────┘
)"
},
{
"All bits set",
"SELECT bitPositionsToArray(toInt8(-1)) AS bit_positions",
R"(
┌─bit_positions─────┐
│ [0,1,2,3,4,5,6,7] │
└───────────────────┘
)"
}
};
FunctionDocumentation::IntroducedIn bitPositionsToArray_introduced_in = {21, 7};
FunctionDocumentation::Category bitPositionsToArray_category = FunctionDocumentation::Category::Encoding;
FunctionDocumentation bitPositionsToArray_documentation = {bitPositionsToArray_description, bitPositionsToArray_syntax, bitPositionsToArray_arguments, {}, bitPositionsToArray_returned_value, bitPositionsToArray_examples, bitPositionsToArray_introduced_in, bitPositionsToArray_category};
FunctionDocumentation::Description bitmaskToArray_description = R"(
This function decomposes an integer into a sum of powers of two.
The powers of two are returned as an ascendingly ordered array.
)";
FunctionDocumentation::Syntax bitmaskToArray_syntax = "bitmaskToArray(num)";
FunctionDocumentation::Arguments bitmaskToArray_arguments = {{"num", "An integer value.", {"(U)Int*"}}};
FunctionDocumentation::ReturnedValue bitmaskToArray_returned_value = {"Returns an array with the ascendingly ordered powers of two which sum up to the input number.", {"Array(UInt64)"}};
FunctionDocumentation::Examples bitmaskToArray_examples = {
{
"Basic example",
"SELECT bitmaskToArray(50) AS powers_of_two",
R"(
┌─powers_of_two─┐
│ [2,16,32] │
└───────────────┘
)"
},
{
"Single power of two",
"SELECT bitmaskToArray(8) AS powers_of_two",
R"(
┌─powers_of_two─┐
│ [8] │
└───────────────┘
)"
},
};
FunctionDocumentation::IntroducedIn bitmaskToArray_introduced_in = {1, 1};
FunctionDocumentation::Category bitmaskToArray_category = FunctionDocumentation::Category::Encoding;
FunctionDocumentation bitmaskToArray_documentation = {bitmaskToArray_description, bitmaskToArray_syntax, bitmaskToArray_arguments, {}, bitmaskToArray_returned_value, bitmaskToArray_examples, bitmaskToArray_introduced_in, bitmaskToArray_category};
FunctionDocumentation::Description bitmaskToList_description = R"(
Like bitmaskToArray but returns the powers of two as a comma-separated string.
)";
FunctionDocumentation::Syntax bitmaskToList_syntax = "bitmaskToList(num)";
FunctionDocumentation::Arguments bitmaskToList_arguments = {
{"num", "An integer value.", {"(U)Int*"}}
};
FunctionDocumentation::ReturnedValue bitmaskToList_returned_value = {"Returns a string containing comma-separated powers of two.", {"String"}};
FunctionDocumentation::Examples bitmaskToList_examples = {
{
"Basic example", "SELECT bitmaskToList(50) AS powers_list",
R"(
┌─powers_list─┐
│ 2,16,32 │
└─────────────┘
)"
},
};
FunctionDocumentation::IntroducedIn bitmaskToList_introduced_in = {1, 1};
FunctionDocumentation::Category bitmaskToList_category = FunctionDocumentation::Category::Encoding;
FunctionDocumentation bitmaskToList_documentation = {bitmaskToList_description, bitmaskToList_syntax, bitmaskToList_arguments, {}, bitmaskToList_returned_value, bitmaskToList_examples, bitmaskToList_introduced_in, bitmaskToList_category};
factory.registerFunction<FunctionBitPositionsToArray>(bitPositionsToArray_documentation);
factory.registerFunction<FunctionBitmaskToArray>(bitmaskToArray_documentation);
factory.registerFunction<FunctionBitmaskToList>(bitmaskToList_documentation);
}
}