datasketches-cpp
Loading...
Searching...
No Matches
array_of_strings_sketch_impl.hpp
1/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20#ifndef ARRAY_OF_STRINGS_SKETCH_IMPL_HPP_
21#define ARRAY_OF_STRINGS_SKETCH_IMPL_HPP_
22
23#include <stdexcept>
24
25#include "common_defs.hpp"
26#include "theta_helpers.hpp"
27
28namespace datasketches {
29
30inline array_of_strings default_array_of_strings_update_policy::create() const {
31 return array_of_strings(0, "");
32}
33
34inline void default_array_of_strings_update_policy::update(
35 array_of_strings& array, const array_of_strings& input
36) const {
37 const auto length = static_cast<size_t>(input.size());
38 array = array_of_strings(static_cast<uint8_t>(length), "");
39 for (size_t i = 0; i < length; ++i) array[i] = input[i];
40}
41
42inline void default_array_of_strings_update_policy::update(
43 array_of_strings& array, const array_of_strings* input
44) const {
45 if (input == nullptr) {
46 array = array_of_strings(0, "");
47 return;
48 }
49 const auto length = static_cast<size_t>(input->size());
50 array = array_of_strings(static_cast<uint8_t>(length), "");
51 for (size_t i = 0; i < length; ++i) array[i] = (*input)[i];
52}
53
63class array_of_strings_key_hasher {
64public:
65 explicit array_of_strings_key_hasher(uint64_t seed): hasher_(seed), size_(0) {}
66
67 void add_utf8(const std::string& str) {
68 const uint8_t* bytes = reinterpret_cast<const uint8_t*>(str.data());
69 const size_t length = str.size();
70 size_t i = 0;
71 while (i < length) {
72 const uint8_t lead = bytes[i++];
73 if (lead < 0x80) { // ASCII
74 add_code_unit(lead);
75 continue;
76 }
77 uint8_t second_min;
78 uint8_t second_max;
79 const unsigned num_continuation = get_sequence_rule(lead, second_min, second_max);
80 if (num_continuation == 0) { // Invalid UTF8
81 add_code_unit(REPLACEMENT_CHAR);
82 continue;
83 }
84 uint32_t code_point = lead & (0x3F >> num_continuation);
85 unsigned num_read = 0;
86 while (num_read < num_continuation && i < length) {
87 const uint8_t byte = bytes[i];
88 const bool valid = num_read == 0 ? byte >= second_min && byte <= second_max : (byte & 0xC0) == 0x80;
89 if (!valid) break;
90 code_point = (code_point << 6) | (byte & 0x3F);
91 ++i;
92 ++num_read;
93 }
94 if (num_read < num_continuation) {
95 // the bytes consumed so far are the longest valid prefix, resume at the next byte
96 add_code_unit(REPLACEMENT_CHAR);
97 } else {
98 add_code_point(code_point);
99 }
100 }
101 }
102
103 void add_code_unit(uint16_t unit) {
104 if (size_ == sizeof(buffer_)) flush();
105 buffer_[size_++] = static_cast<uint8_t>(unit);
106 buffer_[size_++] = static_cast<uint8_t>(unit >> 8);
107 }
108
109 uint64_t hash() {
110 flush();
111 return hasher_.hash();
112 }
113
114private:
115 enum : uint16_t { REPLACEMENT_CHAR = 0xFFFD };
116
117 XXHash64 hasher_;
118 uint8_t buffer_[256];
119 size_t size_;
120
121 void flush() {
122 hasher_.add(buffer_, size_);
123 size_ = 0;
124 }
125
126 void add_code_point(uint32_t code_point) {
127 if (code_point >= 0xD800 && code_point <= 0xDFFF) {
128 add_code_unit(REPLACEMENT_CHAR);
129 } else if (code_point < 0x10000) {
130 add_code_unit(static_cast<uint16_t>(code_point));
131 } else {
132 code_point -= 0x10000;
133 add_code_unit(static_cast<uint16_t>(0xD800 | (code_point >> 10)));
134 add_code_unit(static_cast<uint16_t>(0xDC00 | (code_point & 0x3FF)));
135 }
136 }
137
143 static unsigned get_sequence_rule(uint8_t lead, uint8_t& second_min, uint8_t& second_max) {
144 second_min = 0x80;
145 second_max = 0xBF;
146 if (lead >= 0xC2 && lead <= 0xDF) return 1;
147 if (lead == 0xE0) second_min = 0xA0; // no overlong forms
148 // ED A0-BF encodes a surrogate, which Java's decoder accepts here and replaces once decoded
149 if (lead >= 0xE0 && lead <= 0xEF) return 2;
150 if (lead == 0xF0) second_min = 0x90; // no overlong forms
151 if (lead == 0xF4) second_max = 0x8F; // nothing above U+10FFFF
152 if (lead >= 0xF0 && lead <= 0xF4) return 3;
153 return 0;
154 }
155};
156
157inline uint64_t hash_array_of_strings_key(const array_of_strings& key) {
158 // Matches Java Util.PRIME for ArrayOfStrings key hashing.
159 static constexpr uint64_t STRING_ARR_HASH_SEED = 0x7A3CCA71ULL;
160 array_of_strings_key_hasher hasher(STRING_ARR_HASH_SEED);
161 const auto size = static_cast<size_t>(key.size());
162 for (size_t i = 0; i < size; ++i) {
163 if (i > 0) hasher.add_code_unit(',');
164 hasher.add_utf8(key[i]);
165 }
166 return hasher.hash();
167}
168
169template<typename Allocator, typename Policy>
175
176template<typename Allocator>
177template<typename Sketch>
179 const Sketch& sketch, bool ordered
180): Base(sketch, ordered) {}
181
182template<typename Allocator>
184 Base&& base
185): Base(std::move(base)) {}
186
187template<typename Allocator>
188template<typename SerDe>
189void compact_array_of_strings_tuple_sketch<Allocator>::serialize(std::ostream& os, const SerDe& sd) const {
190 Base::serialize(os, sd);
191}
192
193template<typename Allocator>
194template<typename SerDe>
196 unsigned header_size_bytes, const SerDe& sd
197) const -> vector_bytes {
198 return Base::serialize(header_size_bytes, sd);
199}
200
201template<typename Allocator>
202template<typename SerDe>
204 std::istream& is, uint64_t seed, const SerDe& sd, const Allocator& allocator
205) -> compact_array_of_strings_tuple_sketch {
206 auto base = Base::deserialize(is, seed, sd, allocator);
207 return compact_array_of_strings_tuple_sketch(std::move(base));
208}
209
210template<typename Allocator>
211template<typename SerDe>
213 const void* bytes, size_t size, uint64_t seed, const SerDe& sd, const Allocator& allocator
215 auto base = Base::deserialize(bytes, size, seed, sd, allocator);
216 return compact_array_of_strings_tuple_sketch(std::move(base));
217}
218
219template<typename Allocator>
220default_array_of_strings_serde<Allocator>::default_array_of_strings_serde(const Allocator& allocator):
221 summary_allocator_(allocator) {}
222
223template<typename Allocator>
224void default_array_of_strings_serde<Allocator>::serialize(
225 std::ostream& os, const array_of_strings* items, unsigned num
226) const {
227 unsigned i = 0;
228 try {
229 for (; i < num; ++i) {
230 const uint32_t total_bytes = compute_total_bytes(items[i]);
231 const uint8_t num_nodes = items[i].size();
232 write(os, total_bytes);
233 write(os, num_nodes);
234 const std::string* data = items[i].data();
235 for (uint8_t j = 0; j < num_nodes; ++j) {
236 const uint32_t length = static_cast<uint32_t>(data[j].size());
237 write(os, length);
238 os.write(data[j].data(), length);
239 }
240 }
241 } catch (const std::invalid_argument&) {
242 throw;
243 } catch (const std::exception&) {
244 throw std::runtime_error("array_of_strings stream write failed at item " + std::to_string(i));
245 }
246}
247
248template<typename Allocator>
249void default_array_of_strings_serde<Allocator>::deserialize(
250 std::istream& is, array_of_strings* items, unsigned num
251) const {
252 unsigned i = 0;
253 bool failure = false;
254 try {
255 for (; i < num; ++i) {
256 const uint32_t total_bytes = read<uint32_t>(is);
257 if (!is) { failure = true; break; }
258 const uint8_t num_nodes = read<uint8_t>(is);
259 if (!is) { failure = true; break; }
260 check_num_nodes(num_nodes);
261 size_t item_bytes = sizeof(total_bytes) + sizeof(num_nodes);
262 array_of_strings array(num_nodes, "");
263 for (uint8_t j = 0; j < num_nodes; ++j) {
264 const uint32_t length = read<uint32_t>(is);
265 if (!is) { failure = true; break; }
266 std::string value(length, '\0');
267 if (length != 0) {
268 is.read(&value[0], length);
269 if (!is) { failure = true; break; }
270 }
271 array[j] = std::move(value);
272 item_bytes += sizeof(length) + length;
273 }
274 if (failure) break;
275 check_value<size_t>(item_bytes, total_bytes, "array_of_strings total_bytes");
276 summary_allocator alloc(summary_allocator_);
277 std::allocator_traits<summary_allocator>::construct(alloc, &items[i], std::move(array));
278 }
279 } catch (const std::invalid_argument&) {
280 destroy_items(items, i);
281 throw;
282 } catch (const std::exception&) {
283 failure = true;
284 }
285 if (failure) {
286 destroy_items(items, i);
287 throw std::runtime_error("array_of_strings stream read failed at item " + std::to_string(i));
288 }
289}
290
291template<typename Allocator>
292size_t default_array_of_strings_serde<Allocator>::serialize(
293 void* ptr, size_t capacity, const array_of_strings* items, unsigned num
294) const {
295 uint8_t* ptr8 = static_cast<uint8_t*>(ptr);
296 size_t bytes_written = 0;
297
298 for (unsigned i = 0; i < num; ++i) {
299 const uint32_t total_bytes = compute_total_bytes(items[i]);
300 const uint8_t num_nodes = static_cast<uint8_t>(items[i].size());
301 check_memory_size(bytes_written + total_bytes, capacity);
302 bytes_written += copy_to_mem(total_bytes, ptr8 + bytes_written);
303 bytes_written += copy_to_mem(num_nodes, ptr8 + bytes_written);
304 const std::string* data = items[i].data();
305 for (uint8_t j = 0; j < num_nodes; ++j) {
306 const uint32_t length = static_cast<uint32_t>(data[j].size());
307
308 bytes_written += copy_to_mem(length, ptr8 + bytes_written);
309 bytes_written += copy_to_mem(data[j].data(), ptr8 + bytes_written, length);
310 }
311 }
312 return bytes_written;
313}
314
315template<typename Allocator>
316size_t default_array_of_strings_serde<Allocator>::deserialize(
317 const void* ptr, size_t capacity, array_of_strings* items, unsigned num
318) const {
319 const uint8_t* ptr8 = static_cast<const uint8_t*>(ptr);
320 size_t bytes_read = 0;
321
322 unsigned i = 0;
323
324 try {
325 for (; i < num; ++i) {
326 check_memory_size(bytes_read + sizeof(uint32_t), capacity);
327 const size_t item_start = bytes_read;
328 uint32_t total_bytes;
329 bytes_read += copy_from_mem(ptr8 + bytes_read, total_bytes);
330 check_memory_size(item_start + total_bytes, capacity);
331
332 check_memory_size(bytes_read + sizeof(uint8_t), capacity);
333 uint8_t num_nodes;
334 bytes_read += copy_from_mem(ptr8 + bytes_read, num_nodes);
335 check_num_nodes(num_nodes);
336
337 array_of_strings array(num_nodes, "");
338 for (uint8_t j = 0; j < num_nodes; ++j) {
339 check_memory_size(bytes_read + sizeof(uint32_t), capacity);
340 uint32_t length;
341 bytes_read += copy_from_mem(ptr8 + bytes_read, length);
342
343 check_memory_size(bytes_read + length, capacity);
344 std::string value(length, '\0');
345 if (length != 0) {
346 bytes_read += copy_from_mem(ptr8 + bytes_read, &value[0], length);
347 }
348 array[j] = std::move(value);
349 }
350 check_value<size_t>(bytes_read - item_start, total_bytes, "array_of_strings total_bytes");
351 summary_allocator alloc(summary_allocator_);
352 std::allocator_traits<summary_allocator>::construct(alloc, &items[i], std::move(array));
353 }
354 } catch (const std::invalid_argument&) {
355 destroy_items(items, i);
356 throw;
357 } catch (const std::exception&) {
358 destroy_items(items, i);
359 throw std::runtime_error("array_of_strings bytes read failed at item " + std::to_string(i));
360 }
361 return bytes_read;
362}
363
364template<typename Allocator>
365size_t default_array_of_strings_serde<Allocator>::size_of_item(const array_of_strings& item) const {
366 return compute_total_bytes(item);
367}
368
369template<typename Allocator>
370void default_array_of_strings_serde<Allocator>::check_num_nodes(uint8_t num_nodes) {
371 if (num_nodes > 127) {
372 throw std::invalid_argument("array_of_strings size exceeds 127");
373 }
374}
375
376template<typename Allocator>
377void default_array_of_strings_serde<Allocator>::destroy_items(array_of_strings* items, unsigned num) const {
378 summary_allocator alloc(summary_allocator_);
379 for (unsigned i = 0; i < num; ++i) {
380 std::allocator_traits<summary_allocator>::destroy(alloc, &items[i]);
381 }
382}
383
384template<typename Allocator>
385uint32_t default_array_of_strings_serde<Allocator>::compute_total_bytes(const array_of_strings& item) {
386 const auto count = item.size();
387 check_num_nodes(static_cast<uint8_t>(count));
388 size_t total = sizeof(uint32_t) + sizeof(uint8_t) + count * sizeof(uint32_t);
389 const std::string* data = item.data();
390 for (uint32_t j = 0; j < count; ++j) {
391 total += data[j].size();
392 }
393 return static_cast<uint32_t>(total);
394}
395
396} /* namespace datasketches */
397
398#endif
XXHash (64 bit), based on Yann Collet's descriptions, see http://cyan4973.github.io/xxHash/.
Definition xxhash64.h:25
bool add(const void *input, uint64_t length)
add a chunk of bytes
Definition xxhash64.h:43
Feeds strings to XXHash64 as UTF-16LE code units, which is how Java hashes a String with XxHash....
Definition array_of_strings_sketch_impl.hpp:63
Extended class of compact_tuple_sketch for array of strings.
Definition array_of_strings_sketch.hpp:105
void serialize(std::ostream &os, const SerDe &sd=SerDe()) const
This method serializes the sketch into a given stream in a binary form.
Definition array_of_strings_sketch_impl.hpp:189
static compact_array_of_strings_tuple_sketch deserialize(std::istream &is, uint64_t seed=DEFAULT_SEED, const SerDe &sd=SerDe(), const Allocator &allocator=Allocator())
This method deserializes a sketch from a given stream.
compact_array_of_strings_tuple_sketch(const Sketch &sketch, bool ordered=true)
Copy constructor.
Definition array_of_strings_sketch_impl.hpp:178
void serialize(std::ostream &os, const SerDe &sd=SerDe()) const
DataSketches namespace.
Definition binomial_bounds.hpp:38
update_tuple_sketch< array_of_strings, array_of_strings, Policy, Allocator > update_array_of_strings_tuple_sketch
Convenience alias for update_tuple_sketch for array of strings.
Definition array_of_strings_sketch.hpp:172
compact_array_of_strings_tuple_sketch< Allocator > compact_array_of_strings_sketch(const update_array_of_strings_tuple_sketch< Allocator, Policy > &sketch, bool ordered=true)
Converts an array of strings tuple sketch to a compact sketch (ordered or unordered).
Definition array_of_strings_sketch_impl.hpp:170
uint64_t hash_array_of_strings_key(const array_of_strings &key)
Hashes an array of strings key the same way as Java's ArrayOfStringsTupleSketch (org....
Definition array_of_strings_sketch_impl.hpp:157