applied-ai-018 commited on
Commit
a7f82aa
·
verified ·
1 Parent(s): 3230c19

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. ckpts/universal/global_step80/zero/24.attention.dense.weight/fp32.pt +3 -0
  2. ckpts/universal/global_step80/zero/24.post_attention_layernorm.weight/exp_avg_sq.pt +3 -0
  3. ckpts/universal/global_step80/zero/3.mlp.dense_h_to_4h_swiglu.weight/exp_avg_sq.pt +3 -0
  4. ckpts/universal/global_step80/zero/7.attention.dense.weight/exp_avg_sq.pt +3 -0
  5. venv/lib/python3.10/site-packages/annotated_types/__init__.py +396 -0
  6. venv/lib/python3.10/site-packages/annotated_types/__pycache__/__init__.cpython-310.pyc +0 -0
  7. venv/lib/python3.10/site-packages/annotated_types/__pycache__/test_cases.cpython-310.pyc +0 -0
  8. venv/lib/python3.10/site-packages/annotated_types/py.typed +0 -0
  9. venv/lib/python3.10/site-packages/annotated_types/test_cases.py +147 -0
  10. venv/lib/python3.10/site-packages/async_timeout-4.0.3.dist-info/INSTALLER +1 -0
  11. venv/lib/python3.10/site-packages/async_timeout-4.0.3.dist-info/LICENSE +13 -0
  12. venv/lib/python3.10/site-packages/async_timeout-4.0.3.dist-info/METADATA +131 -0
  13. venv/lib/python3.10/site-packages/async_timeout-4.0.3.dist-info/RECORD +10 -0
  14. venv/lib/python3.10/site-packages/async_timeout-4.0.3.dist-info/WHEEL +5 -0
  15. venv/lib/python3.10/site-packages/async_timeout-4.0.3.dist-info/top_level.txt +1 -0
  16. venv/lib/python3.10/site-packages/async_timeout-4.0.3.dist-info/zip-safe +1 -0
  17. venv/lib/python3.10/site-packages/pyarrow/__pycache__/__init__.cpython-310.pyc +0 -0
  18. venv/lib/python3.10/site-packages/pyarrow/__pycache__/_compute_docstrings.cpython-310.pyc +0 -0
  19. venv/lib/python3.10/site-packages/pyarrow/__pycache__/_generated_version.cpython-310.pyc +0 -0
  20. venv/lib/python3.10/site-packages/pyarrow/__pycache__/acero.cpython-310.pyc +0 -0
  21. venv/lib/python3.10/site-packages/pyarrow/__pycache__/benchmark.cpython-310.pyc +0 -0
  22. venv/lib/python3.10/site-packages/pyarrow/__pycache__/cffi.cpython-310.pyc +0 -0
  23. venv/lib/python3.10/site-packages/pyarrow/__pycache__/compute.cpython-310.pyc +0 -0
  24. venv/lib/python3.10/site-packages/pyarrow/__pycache__/conftest.cpython-310.pyc +0 -0
  25. venv/lib/python3.10/site-packages/pyarrow/__pycache__/csv.cpython-310.pyc +0 -0
  26. venv/lib/python3.10/site-packages/pyarrow/__pycache__/cuda.cpython-310.pyc +0 -0
  27. venv/lib/python3.10/site-packages/pyarrow/__pycache__/dataset.cpython-310.pyc +0 -0
  28. venv/lib/python3.10/site-packages/pyarrow/__pycache__/feather.cpython-310.pyc +0 -0
  29. venv/lib/python3.10/site-packages/pyarrow/__pycache__/flight.cpython-310.pyc +0 -0
  30. venv/lib/python3.10/site-packages/pyarrow/__pycache__/fs.cpython-310.pyc +0 -0
  31. venv/lib/python3.10/site-packages/pyarrow/__pycache__/ipc.cpython-310.pyc +0 -0
  32. venv/lib/python3.10/site-packages/pyarrow/__pycache__/json.cpython-310.pyc +0 -0
  33. venv/lib/python3.10/site-packages/pyarrow/__pycache__/jvm.cpython-310.pyc +0 -0
  34. venv/lib/python3.10/site-packages/pyarrow/__pycache__/orc.cpython-310.pyc +0 -0
  35. venv/lib/python3.10/site-packages/pyarrow/__pycache__/pandas_compat.cpython-310.pyc +0 -0
  36. venv/lib/python3.10/site-packages/pyarrow/__pycache__/substrait.cpython-310.pyc +0 -0
  37. venv/lib/python3.10/site-packages/pyarrow/__pycache__/types.cpython-310.pyc +0 -0
  38. venv/lib/python3.10/site-packages/pyarrow/__pycache__/util.cpython-310.pyc +0 -0
  39. venv/lib/python3.10/site-packages/pyarrow/include/arrow/array/array_base.h +301 -0
  40. venv/lib/python3.10/site-packages/pyarrow/include/arrow/array/array_nested.h +863 -0
  41. venv/lib/python3.10/site-packages/pyarrow/include/arrow/array/array_run_end.h +133 -0
  42. venv/lib/python3.10/site-packages/pyarrow/include/arrow/array/builder_base.h +370 -0
  43. venv/lib/python3.10/site-packages/pyarrow/include/arrow/array/builder_dict.h +737 -0
  44. venv/lib/python3.10/site-packages/pyarrow/include/arrow/array/builder_nested.h +838 -0
  45. venv/lib/python3.10/site-packages/pyarrow/include/arrow/array/builder_run_end.h +303 -0
  46. venv/lib/python3.10/site-packages/pyarrow/include/arrow/array/concatenate.h +37 -0
  47. venv/lib/python3.10/site-packages/pyarrow/include/arrow/array/util.h +96 -0
  48. venv/lib/python3.10/site-packages/pyarrow/include/arrow/compute/row/grouper.h +184 -0
  49. venv/lib/python3.10/site-packages/pyarrow/include/arrow/json/api.h +21 -0
  50. venv/lib/python3.10/site-packages/pyarrow/include/arrow/testing/extension_type.h +211 -0
ckpts/universal/global_step80/zero/24.attention.dense.weight/fp32.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b7650f092df2ee10108669c65ab8399bc04bef7415e2ba2e0ed08347f92acc2d
3
+ size 16778317
ckpts/universal/global_step80/zero/24.post_attention_layernorm.weight/exp_avg_sq.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:61299b23a1e4dfadfb19e0d5685db32abd6a57045df2bc6ffd12e5ffe85c0a56
3
+ size 9387
ckpts/universal/global_step80/zero/3.mlp.dense_h_to_4h_swiglu.weight/exp_avg_sq.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:edbb344876a6a1b7717b9987cd3e45a2702ac3bdc89143b186cca9b5e287d7be
3
+ size 33555627
ckpts/universal/global_step80/zero/7.attention.dense.weight/exp_avg_sq.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:19076cfd454afeebec12bff407e2a1ac218f80f30af4f067597544549e009326
3
+ size 16778411
venv/lib/python3.10/site-packages/annotated_types/__init__.py ADDED
@@ -0,0 +1,396 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import sys
3
+ from dataclasses import dataclass
4
+ from datetime import timezone
5
+ from typing import TYPE_CHECKING, Any, Callable, Iterator, Optional, SupportsFloat, SupportsIndex, TypeVar, Union
6
+
7
+ if sys.version_info < (3, 8):
8
+ from typing_extensions import Protocol, runtime_checkable
9
+ else:
10
+ from typing import Protocol, runtime_checkable
11
+
12
+ if sys.version_info < (3, 9):
13
+ from typing_extensions import Annotated, Literal
14
+ else:
15
+ from typing import Annotated, Literal
16
+
17
+ if sys.version_info < (3, 10):
18
+ EllipsisType = type(Ellipsis)
19
+ KW_ONLY = {}
20
+ SLOTS = {}
21
+ else:
22
+ from types import EllipsisType
23
+
24
+ KW_ONLY = {"kw_only": True}
25
+ SLOTS = {"slots": True}
26
+
27
+
28
+ __all__ = (
29
+ 'BaseMetadata',
30
+ 'GroupedMetadata',
31
+ 'Gt',
32
+ 'Ge',
33
+ 'Lt',
34
+ 'Le',
35
+ 'Interval',
36
+ 'MultipleOf',
37
+ 'MinLen',
38
+ 'MaxLen',
39
+ 'Len',
40
+ 'Timezone',
41
+ 'Predicate',
42
+ 'LowerCase',
43
+ 'UpperCase',
44
+ 'IsDigits',
45
+ 'IsFinite',
46
+ 'IsNotFinite',
47
+ 'IsNan',
48
+ 'IsNotNan',
49
+ 'IsInfinite',
50
+ 'IsNotInfinite',
51
+ 'doc',
52
+ 'DocInfo',
53
+ '__version__',
54
+ )
55
+
56
+ __version__ = '0.6.0'
57
+
58
+
59
+ T = TypeVar('T')
60
+
61
+
62
+ # arguments that start with __ are considered
63
+ # positional only
64
+ # see https://peps.python.org/pep-0484/#positional-only-arguments
65
+
66
+
67
+ class SupportsGt(Protocol):
68
+ def __gt__(self: T, __other: T) -> bool:
69
+ ...
70
+
71
+
72
+ class SupportsGe(Protocol):
73
+ def __ge__(self: T, __other: T) -> bool:
74
+ ...
75
+
76
+
77
+ class SupportsLt(Protocol):
78
+ def __lt__(self: T, __other: T) -> bool:
79
+ ...
80
+
81
+
82
+ class SupportsLe(Protocol):
83
+ def __le__(self: T, __other: T) -> bool:
84
+ ...
85
+
86
+
87
+ class SupportsMod(Protocol):
88
+ def __mod__(self: T, __other: T) -> T:
89
+ ...
90
+
91
+
92
+ class SupportsDiv(Protocol):
93
+ def __div__(self: T, __other: T) -> T:
94
+ ...
95
+
96
+
97
+ class BaseMetadata:
98
+ """Base class for all metadata.
99
+
100
+ This exists mainly so that implementers
101
+ can do `isinstance(..., BaseMetadata)` while traversing field annotations.
102
+ """
103
+
104
+ __slots__ = ()
105
+
106
+
107
+ @dataclass(frozen=True, **SLOTS)
108
+ class Gt(BaseMetadata):
109
+ """Gt(gt=x) implies that the value must be greater than x.
110
+
111
+ It can be used with any type that supports the ``>`` operator,
112
+ including numbers, dates and times, strings, sets, and so on.
113
+ """
114
+
115
+ gt: SupportsGt
116
+
117
+
118
+ @dataclass(frozen=True, **SLOTS)
119
+ class Ge(BaseMetadata):
120
+ """Ge(ge=x) implies that the value must be greater than or equal to x.
121
+
122
+ It can be used with any type that supports the ``>=`` operator,
123
+ including numbers, dates and times, strings, sets, and so on.
124
+ """
125
+
126
+ ge: SupportsGe
127
+
128
+
129
+ @dataclass(frozen=True, **SLOTS)
130
+ class Lt(BaseMetadata):
131
+ """Lt(lt=x) implies that the value must be less than x.
132
+
133
+ It can be used with any type that supports the ``<`` operator,
134
+ including numbers, dates and times, strings, sets, and so on.
135
+ """
136
+
137
+ lt: SupportsLt
138
+
139
+
140
+ @dataclass(frozen=True, **SLOTS)
141
+ class Le(BaseMetadata):
142
+ """Le(le=x) implies that the value must be less than or equal to x.
143
+
144
+ It can be used with any type that supports the ``<=`` operator,
145
+ including numbers, dates and times, strings, sets, and so on.
146
+ """
147
+
148
+ le: SupportsLe
149
+
150
+
151
+ @runtime_checkable
152
+ class GroupedMetadata(Protocol):
153
+ """A grouping of multiple BaseMetadata objects.
154
+
155
+ `GroupedMetadata` on its own is not metadata and has no meaning.
156
+ All it the the constraint and metadata should be fully expressable
157
+ in terms of the `BaseMetadata`'s returned by `GroupedMetadata.__iter__()`.
158
+
159
+ Concrete implementations should override `GroupedMetadata.__iter__()`
160
+ to add their own metadata.
161
+ For example:
162
+
163
+ >>> @dataclass
164
+ >>> class Field(GroupedMetadata):
165
+ >>> gt: float | None = None
166
+ >>> description: str | None = None
167
+ ...
168
+ >>> def __iter__(self) -> Iterable[BaseMetadata]:
169
+ >>> if self.gt is not None:
170
+ >>> yield Gt(self.gt)
171
+ >>> if self.description is not None:
172
+ >>> yield Description(self.gt)
173
+
174
+ Also see the implementation of `Interval` below for an example.
175
+
176
+ Parsers should recognize this and unpack it so that it can be used
177
+ both with and without unpacking:
178
+
179
+ - `Annotated[int, Field(...)]` (parser must unpack Field)
180
+ - `Annotated[int, *Field(...)]` (PEP-646)
181
+ """ # noqa: trailing-whitespace
182
+
183
+ @property
184
+ def __is_annotated_types_grouped_metadata__(self) -> Literal[True]:
185
+ return True
186
+
187
+ def __iter__(self) -> Iterator[BaseMetadata]:
188
+ ...
189
+
190
+ if not TYPE_CHECKING:
191
+ __slots__ = () # allow subclasses to use slots
192
+
193
+ def __init_subclass__(cls, *args: Any, **kwargs: Any) -> None:
194
+ # Basic ABC like functionality without the complexity of an ABC
195
+ super().__init_subclass__(*args, **kwargs)
196
+ if cls.__iter__ is GroupedMetadata.__iter__:
197
+ raise TypeError("Can't subclass GroupedMetadata without implementing __iter__")
198
+
199
+ def __iter__(self) -> Iterator[BaseMetadata]: # noqa: F811
200
+ raise NotImplementedError # more helpful than "None has no attribute..." type errors
201
+
202
+
203
+ @dataclass(frozen=True, **KW_ONLY, **SLOTS)
204
+ class Interval(GroupedMetadata):
205
+ """Interval can express inclusive or exclusive bounds with a single object.
206
+
207
+ It accepts keyword arguments ``gt``, ``ge``, ``lt``, and/or ``le``, which
208
+ are interpreted the same way as the single-bound constraints.
209
+ """
210
+
211
+ gt: Union[SupportsGt, None] = None
212
+ ge: Union[SupportsGe, None] = None
213
+ lt: Union[SupportsLt, None] = None
214
+ le: Union[SupportsLe, None] = None
215
+
216
+ def __iter__(self) -> Iterator[BaseMetadata]:
217
+ """Unpack an Interval into zero or more single-bounds."""
218
+ if self.gt is not None:
219
+ yield Gt(self.gt)
220
+ if self.ge is not None:
221
+ yield Ge(self.ge)
222
+ if self.lt is not None:
223
+ yield Lt(self.lt)
224
+ if self.le is not None:
225
+ yield Le(self.le)
226
+
227
+
228
+ @dataclass(frozen=True, **SLOTS)
229
+ class MultipleOf(BaseMetadata):
230
+ """MultipleOf(multiple_of=x) might be interpreted in two ways:
231
+
232
+ 1. Python semantics, implying ``value % multiple_of == 0``, or
233
+ 2. JSONschema semantics, where ``int(value / multiple_of) == value / multiple_of``
234
+
235
+ We encourage users to be aware of these two common interpretations,
236
+ and libraries to carefully document which they implement.
237
+ """
238
+
239
+ multiple_of: Union[SupportsDiv, SupportsMod]
240
+
241
+
242
+ @dataclass(frozen=True, **SLOTS)
243
+ class MinLen(BaseMetadata):
244
+ """
245
+ MinLen() implies minimum inclusive length,
246
+ e.g. ``len(value) >= min_length``.
247
+ """
248
+
249
+ min_length: Annotated[int, Ge(0)]
250
+
251
+
252
+ @dataclass(frozen=True, **SLOTS)
253
+ class MaxLen(BaseMetadata):
254
+ """
255
+ MaxLen() implies maximum inclusive length,
256
+ e.g. ``len(value) <= max_length``.
257
+ """
258
+
259
+ max_length: Annotated[int, Ge(0)]
260
+
261
+
262
+ @dataclass(frozen=True, **SLOTS)
263
+ class Len(GroupedMetadata):
264
+ """
265
+ Len() implies that ``min_length <= len(value) <= max_length``.
266
+
267
+ Upper bound may be omitted or ``None`` to indicate no upper length bound.
268
+ """
269
+
270
+ min_length: Annotated[int, Ge(0)] = 0
271
+ max_length: Optional[Annotated[int, Ge(0)]] = None
272
+
273
+ def __iter__(self) -> Iterator[BaseMetadata]:
274
+ """Unpack a Len into zone or more single-bounds."""
275
+ if self.min_length > 0:
276
+ yield MinLen(self.min_length)
277
+ if self.max_length is not None:
278
+ yield MaxLen(self.max_length)
279
+
280
+
281
+ @dataclass(frozen=True, **SLOTS)
282
+ class Timezone(BaseMetadata):
283
+ """Timezone(tz=...) requires a datetime to be aware (or ``tz=None``, naive).
284
+
285
+ ``Annotated[datetime, Timezone(None)]`` must be a naive datetime.
286
+ ``Timezone[...]`` (the ellipsis literal) expresses that the datetime must be
287
+ tz-aware but any timezone is allowed.
288
+
289
+ You may also pass a specific timezone string or timezone object such as
290
+ ``Timezone(timezone.utc)`` or ``Timezone("Africa/Abidjan")`` to express that
291
+ you only allow a specific timezone, though we note that this is often
292
+ a symptom of poor design.
293
+ """
294
+
295
+ tz: Union[str, timezone, EllipsisType, None]
296
+
297
+
298
+ @dataclass(frozen=True, **SLOTS)
299
+ class Predicate(BaseMetadata):
300
+ """``Predicate(func: Callable)`` implies `func(value)` is truthy for valid values.
301
+
302
+ Users should prefer statically inspectable metadata, but if you need the full
303
+ power and flexibility of arbitrary runtime predicates... here it is.
304
+
305
+ We provide a few predefined predicates for common string constraints:
306
+ ``IsLower = Predicate(str.islower)``, ``IsUpper = Predicate(str.isupper)``, and
307
+ ``IsDigit = Predicate(str.isdigit)``. Users are encouraged to use methods which
308
+ can be given special handling, and avoid indirection like ``lambda s: s.lower()``.
309
+
310
+ Some libraries might have special logic to handle certain predicates, e.g. by
311
+ checking for `str.isdigit` and using its presence to both call custom logic to
312
+ enforce digit-only strings, and customise some generated external schema.
313
+
314
+ We do not specify what behaviour should be expected for predicates that raise
315
+ an exception. For example `Annotated[int, Predicate(str.isdigit)]` might silently
316
+ skip invalid constraints, or statically raise an error; or it might try calling it
317
+ and then propogate or discard the resulting exception.
318
+ """
319
+
320
+ func: Callable[[Any], bool]
321
+
322
+
323
+ @dataclass
324
+ class Not:
325
+ func: Callable[[Any], bool]
326
+
327
+ def __call__(self, __v: Any) -> bool:
328
+ return not self.func(__v)
329
+
330
+
331
+ _StrType = TypeVar("_StrType", bound=str)
332
+
333
+ LowerCase = Annotated[_StrType, Predicate(str.islower)]
334
+ """
335
+ Return True if the string is a lowercase string, False otherwise.
336
+
337
+ A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.
338
+ """ # noqa: E501
339
+ UpperCase = Annotated[_StrType, Predicate(str.isupper)]
340
+ """
341
+ Return True if the string is an uppercase string, False otherwise.
342
+
343
+ A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.
344
+ """ # noqa: E501
345
+ IsDigits = Annotated[_StrType, Predicate(str.isdigit)]
346
+ """
347
+ Return True if the string is a digit string, False otherwise.
348
+
349
+ A string is a digit string if all characters in the string are digits and there is at least one character in the string.
350
+ """ # noqa: E501
351
+ IsAscii = Annotated[_StrType, Predicate(str.isascii)]
352
+ """
353
+ Return True if all characters in the string are ASCII, False otherwise.
354
+
355
+ ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.
356
+ """
357
+
358
+ _NumericType = TypeVar('_NumericType', bound=Union[SupportsFloat, SupportsIndex])
359
+ IsFinite = Annotated[_NumericType, Predicate(math.isfinite)]
360
+ """Return True if x is neither an infinity nor a NaN, and False otherwise."""
361
+ IsNotFinite = Annotated[_NumericType, Predicate(Not(math.isfinite))]
362
+ """Return True if x is one of infinity or NaN, and False otherwise"""
363
+ IsNan = Annotated[_NumericType, Predicate(math.isnan)]
364
+ """Return True if x is a NaN (not a number), and False otherwise."""
365
+ IsNotNan = Annotated[_NumericType, Predicate(Not(math.isnan))]
366
+ """Return True if x is anything but NaN (not a number), and False otherwise."""
367
+ IsInfinite = Annotated[_NumericType, Predicate(math.isinf)]
368
+ """Return True if x is a positive or negative infinity, and False otherwise."""
369
+ IsNotInfinite = Annotated[_NumericType, Predicate(Not(math.isinf))]
370
+ """Return True if x is neither a positive or negative infinity, and False otherwise."""
371
+
372
+ try:
373
+ from typing_extensions import DocInfo, doc # type: ignore [attr-defined]
374
+ except ImportError:
375
+
376
+ @dataclass(frozen=True, **SLOTS)
377
+ class DocInfo: # type: ignore [no-redef]
378
+ """ "
379
+ The return value of doc(), mainly to be used by tools that want to extract the
380
+ Annotated documentation at runtime.
381
+ """
382
+
383
+ documentation: str
384
+ """The documentation string passed to doc()."""
385
+
386
+ def doc(
387
+ documentation: str,
388
+ ) -> DocInfo:
389
+ """
390
+ Add documentation to a type annotation inside of Annotated.
391
+
392
+ For example:
393
+
394
+ >>> def hi(name: Annotated[int, doc("The name of the user")]) -> None: ...
395
+ """
396
+ return DocInfo(documentation)
venv/lib/python3.10/site-packages/annotated_types/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (13.1 kB). View file
 
venv/lib/python3.10/site-packages/annotated_types/__pycache__/test_cases.cpython-310.pyc ADDED
Binary file (5.56 kB). View file
 
venv/lib/python3.10/site-packages/annotated_types/py.typed ADDED
File without changes
venv/lib/python3.10/site-packages/annotated_types/test_cases.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import sys
3
+ from datetime import date, datetime, timedelta, timezone
4
+ from decimal import Decimal
5
+ from typing import Any, Dict, Iterable, Iterator, List, NamedTuple, Set, Tuple
6
+
7
+ if sys.version_info < (3, 9):
8
+ from typing_extensions import Annotated
9
+ else:
10
+ from typing import Annotated
11
+
12
+ import annotated_types as at
13
+
14
+
15
+ class Case(NamedTuple):
16
+ """
17
+ A test case for `annotated_types`.
18
+ """
19
+
20
+ annotation: Any
21
+ valid_cases: Iterable[Any]
22
+ invalid_cases: Iterable[Any]
23
+
24
+
25
+ def cases() -> Iterable[Case]:
26
+ # Gt, Ge, Lt, Le
27
+ yield Case(Annotated[int, at.Gt(4)], (5, 6, 1000), (4, 0, -1))
28
+ yield Case(Annotated[float, at.Gt(0.5)], (0.6, 0.7, 0.8, 0.9), (0.5, 0.0, -0.1))
29
+ yield Case(
30
+ Annotated[datetime, at.Gt(datetime(2000, 1, 1))],
31
+ [datetime(2000, 1, 2), datetime(2000, 1, 3)],
32
+ [datetime(2000, 1, 1), datetime(1999, 12, 31)],
33
+ )
34
+ yield Case(
35
+ Annotated[datetime, at.Gt(date(2000, 1, 1))],
36
+ [date(2000, 1, 2), date(2000, 1, 3)],
37
+ [date(2000, 1, 1), date(1999, 12, 31)],
38
+ )
39
+ yield Case(
40
+ Annotated[datetime, at.Gt(Decimal('1.123'))],
41
+ [Decimal('1.1231'), Decimal('123')],
42
+ [Decimal('1.123'), Decimal('0')],
43
+ )
44
+
45
+ yield Case(Annotated[int, at.Ge(4)], (4, 5, 6, 1000, 4), (0, -1))
46
+ yield Case(Annotated[float, at.Ge(0.5)], (0.5, 0.6, 0.7, 0.8, 0.9), (0.4, 0.0, -0.1))
47
+ yield Case(
48
+ Annotated[datetime, at.Ge(datetime(2000, 1, 1))],
49
+ [datetime(2000, 1, 2), datetime(2000, 1, 3)],
50
+ [datetime(1998, 1, 1), datetime(1999, 12, 31)],
51
+ )
52
+
53
+ yield Case(Annotated[int, at.Lt(4)], (0, -1), (4, 5, 6, 1000, 4))
54
+ yield Case(Annotated[float, at.Lt(0.5)], (0.4, 0.0, -0.1), (0.5, 0.6, 0.7, 0.8, 0.9))
55
+ yield Case(
56
+ Annotated[datetime, at.Lt(datetime(2000, 1, 1))],
57
+ [datetime(1999, 12, 31), datetime(1999, 12, 31)],
58
+ [datetime(2000, 1, 2), datetime(2000, 1, 3)],
59
+ )
60
+
61
+ yield Case(Annotated[int, at.Le(4)], (4, 0, -1), (5, 6, 1000))
62
+ yield Case(Annotated[float, at.Le(0.5)], (0.5, 0.0, -0.1), (0.6, 0.7, 0.8, 0.9))
63
+ yield Case(
64
+ Annotated[datetime, at.Le(datetime(2000, 1, 1))],
65
+ [datetime(2000, 1, 1), datetime(1999, 12, 31)],
66
+ [datetime(2000, 1, 2), datetime(2000, 1, 3)],
67
+ )
68
+
69
+ # Interval
70
+ yield Case(Annotated[int, at.Interval(gt=4)], (5, 6, 1000), (4, 0, -1))
71
+ yield Case(Annotated[int, at.Interval(gt=4, lt=10)], (5, 6), (4, 10, 1000, 0, -1))
72
+ yield Case(Annotated[float, at.Interval(ge=0.5, le=1)], (0.5, 0.9, 1), (0.49, 1.1))
73
+ yield Case(
74
+ Annotated[datetime, at.Interval(gt=datetime(2000, 1, 1), le=datetime(2000, 1, 3))],
75
+ [datetime(2000, 1, 2), datetime(2000, 1, 3)],
76
+ [datetime(2000, 1, 1), datetime(2000, 1, 4)],
77
+ )
78
+
79
+ yield Case(Annotated[int, at.MultipleOf(multiple_of=3)], (0, 3, 9), (1, 2, 4))
80
+ yield Case(Annotated[float, at.MultipleOf(multiple_of=0.5)], (0, 0.5, 1, 1.5), (0.4, 1.1))
81
+
82
+ # lengths
83
+
84
+ yield Case(Annotated[str, at.MinLen(3)], ('123', '1234', 'x' * 10), ('', '1', '12'))
85
+ yield Case(Annotated[str, at.Len(3)], ('123', '1234', 'x' * 10), ('', '1', '12'))
86
+ yield Case(Annotated[List[int], at.MinLen(3)], ([1, 2, 3], [1, 2, 3, 4], [1] * 10), ([], [1], [1, 2]))
87
+ yield Case(Annotated[List[int], at.Len(3)], ([1, 2, 3], [1, 2, 3, 4], [1] * 10), ([], [1], [1, 2]))
88
+
89
+ yield Case(Annotated[str, at.MaxLen(4)], ('', '1234'), ('12345', 'x' * 10))
90
+ yield Case(Annotated[str, at.Len(0, 4)], ('', '1234'), ('12345', 'x' * 10))
91
+ yield Case(Annotated[List[str], at.MaxLen(4)], ([], ['a', 'bcdef'], ['a', 'b', 'c']), (['a'] * 5, ['b'] * 10))
92
+ yield Case(Annotated[List[str], at.Len(0, 4)], ([], ['a', 'bcdef'], ['a', 'b', 'c']), (['a'] * 5, ['b'] * 10))
93
+
94
+ yield Case(Annotated[str, at.Len(3, 5)], ('123', '12345'), ('', '1', '12', '123456', 'x' * 10))
95
+ yield Case(Annotated[str, at.Len(3, 3)], ('123',), ('12', '1234'))
96
+
97
+ yield Case(Annotated[Dict[int, int], at.Len(2, 3)], [{1: 1, 2: 2}], [{}, {1: 1}, {1: 1, 2: 2, 3: 3, 4: 4}])
98
+ yield Case(Annotated[Set[int], at.Len(2, 3)], ({1, 2}, {1, 2, 3}), (set(), {1}, {1, 2, 3, 4}))
99
+ yield Case(Annotated[Tuple[int, ...], at.Len(2, 3)], ((1, 2), (1, 2, 3)), ((), (1,), (1, 2, 3, 4)))
100
+
101
+ # Timezone
102
+
103
+ yield Case(
104
+ Annotated[datetime, at.Timezone(None)], [datetime(2000, 1, 1)], [datetime(2000, 1, 1, tzinfo=timezone.utc)]
105
+ )
106
+ yield Case(
107
+ Annotated[datetime, at.Timezone(...)], [datetime(2000, 1, 1, tzinfo=timezone.utc)], [datetime(2000, 1, 1)]
108
+ )
109
+ yield Case(
110
+ Annotated[datetime, at.Timezone(timezone.utc)],
111
+ [datetime(2000, 1, 1, tzinfo=timezone.utc)],
112
+ [datetime(2000, 1, 1), datetime(2000, 1, 1, tzinfo=timezone(timedelta(hours=6)))],
113
+ )
114
+ yield Case(
115
+ Annotated[datetime, at.Timezone('Europe/London')],
116
+ [datetime(2000, 1, 1, tzinfo=timezone(timedelta(0), name='Europe/London'))],
117
+ [datetime(2000, 1, 1), datetime(2000, 1, 1, tzinfo=timezone(timedelta(hours=6)))],
118
+ )
119
+
120
+ # predicate types
121
+
122
+ yield Case(at.LowerCase[str], ['abc', 'foobar'], ['', 'A', 'Boom'])
123
+ yield Case(at.UpperCase[str], ['ABC', 'DEFO'], ['', 'a', 'abc', 'AbC'])
124
+ yield Case(at.IsDigits[str], ['123'], ['', 'ab', 'a1b2'])
125
+ yield Case(at.IsAscii[str], ['123', 'foo bar'], ['£100', '😊', 'whatever 👀'])
126
+
127
+ yield Case(Annotated[int, at.Predicate(lambda x: x % 2 == 0)], [0, 2, 4], [1, 3, 5])
128
+
129
+ yield Case(at.IsFinite[float], [1.23], [math.nan, math.inf, -math.inf])
130
+ yield Case(at.IsNotFinite[float], [math.nan, math.inf], [1.23])
131
+ yield Case(at.IsNan[float], [math.nan], [1.23, math.inf])
132
+ yield Case(at.IsNotNan[float], [1.23, math.inf], [math.nan])
133
+ yield Case(at.IsInfinite[float], [math.inf], [math.nan, 1.23])
134
+ yield Case(at.IsNotInfinite[float], [math.nan, 1.23], [math.inf])
135
+
136
+ # check stacked predicates
137
+ yield Case(at.IsInfinite[Annotated[float, at.Predicate(lambda x: x > 0)]], [math.inf], [-math.inf, 1.23, math.nan])
138
+
139
+ # doc
140
+ yield Case(Annotated[int, at.doc("A number")], [1, 2], [])
141
+
142
+ # custom GroupedMetadata
143
+ class MyCustomGroupedMetadata(at.GroupedMetadata):
144
+ def __iter__(self) -> Iterator[at.Predicate]:
145
+ yield at.Predicate(lambda x: float(x).is_integer())
146
+
147
+ yield Case(Annotated[float, MyCustomGroupedMetadata()], [0, 2.0], [0.01, 1.5])
venv/lib/python3.10/site-packages/async_timeout-4.0.3.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
venv/lib/python3.10/site-packages/async_timeout-4.0.3.dist-info/LICENSE ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright 2016-2020 aio-libs collaboration.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
venv/lib/python3.10/site-packages/async_timeout-4.0.3.dist-info/METADATA ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: async-timeout
3
+ Version: 4.0.3
4
+ Summary: Timeout context manager for asyncio programs
5
+ Home-page: https://github.com/aio-libs/async-timeout
6
+ Author: Andrew Svetlov <[email protected]>
7
+ Author-email: [email protected]
8
+ License: Apache 2
9
+ Project-URL: Chat: Gitter, https://gitter.im/aio-libs/Lobby
10
+ Project-URL: CI: GitHub Actions, https://github.com/aio-libs/async-timeout/actions
11
+ Project-URL: Coverage: codecov, https://codecov.io/github/aio-libs/async-timeout
12
+ Project-URL: GitHub: issues, https://github.com/aio-libs/async-timeout/issues
13
+ Project-URL: GitHub: repo, https://github.com/aio-libs/async-timeout
14
+ Classifier: Development Status :: 5 - Production/Stable
15
+ Classifier: Topic :: Software Development :: Libraries
16
+ Classifier: Framework :: AsyncIO
17
+ Classifier: Intended Audience :: Developers
18
+ Classifier: License :: OSI Approved :: Apache Software License
19
+ Classifier: Programming Language :: Python
20
+ Classifier: Programming Language :: Python :: 3
21
+ Classifier: Programming Language :: Python :: 3 :: Only
22
+ Classifier: Programming Language :: Python :: 3.7
23
+ Classifier: Programming Language :: Python :: 3.8
24
+ Classifier: Programming Language :: Python :: 3.9
25
+ Classifier: Programming Language :: Python :: 3.10
26
+ Classifier: Programming Language :: Python :: 3.11
27
+ Requires-Python: >=3.7
28
+ Description-Content-Type: text/x-rst
29
+ License-File: LICENSE
30
+ Requires-Dist: typing-extensions >=3.6.5 ; python_version < "3.8"
31
+
32
+ async-timeout
33
+ =============
34
+ .. image:: https://travis-ci.com/aio-libs/async-timeout.svg?branch=master
35
+ :target: https://travis-ci.com/aio-libs/async-timeout
36
+ .. image:: https://codecov.io/gh/aio-libs/async-timeout/branch/master/graph/badge.svg
37
+ :target: https://codecov.io/gh/aio-libs/async-timeout
38
+ .. image:: https://img.shields.io/pypi/v/async-timeout.svg
39
+ :target: https://pypi.python.org/pypi/async-timeout
40
+ .. image:: https://badges.gitter.im/Join%20Chat.svg
41
+ :target: https://gitter.im/aio-libs/Lobby
42
+ :alt: Chat on Gitter
43
+
44
+ asyncio-compatible timeout context manager.
45
+
46
+
47
+ Usage example
48
+ -------------
49
+
50
+
51
+ The context manager is useful in cases when you want to apply timeout
52
+ logic around block of code or in cases when ``asyncio.wait_for()`` is
53
+ not suitable. Also it's much faster than ``asyncio.wait_for()``
54
+ because ``timeout`` doesn't create a new task.
55
+
56
+ The ``timeout(delay, *, loop=None)`` call returns a context manager
57
+ that cancels a block on *timeout* expiring::
58
+
59
+ from async_timeout import timeout
60
+ async with timeout(1.5):
61
+ await inner()
62
+
63
+ 1. If ``inner()`` is executed faster than in ``1.5`` seconds nothing
64
+ happens.
65
+ 2. Otherwise ``inner()`` is cancelled internally by sending
66
+ ``asyncio.CancelledError`` into but ``asyncio.TimeoutError`` is
67
+ raised outside of context manager scope.
68
+
69
+ *timeout* parameter could be ``None`` for skipping timeout functionality.
70
+
71
+
72
+ Alternatively, ``timeout_at(when)`` can be used for scheduling
73
+ at the absolute time::
74
+
75
+ loop = asyncio.get_event_loop()
76
+ now = loop.time()
77
+
78
+ async with timeout_at(now + 1.5):
79
+ await inner()
80
+
81
+
82
+ Please note: it is not POSIX time but a time with
83
+ undefined starting base, e.g. the time of the system power on.
84
+
85
+
86
+ Context manager has ``.expired`` property for check if timeout happens
87
+ exactly in context manager::
88
+
89
+ async with timeout(1.5) as cm:
90
+ await inner()
91
+ print(cm.expired)
92
+
93
+ The property is ``True`` if ``inner()`` execution is cancelled by
94
+ timeout context manager.
95
+
96
+ If ``inner()`` call explicitly raises ``TimeoutError`` ``cm.expired``
97
+ is ``False``.
98
+
99
+ The scheduled deadline time is available as ``.deadline`` property::
100
+
101
+ async with timeout(1.5) as cm:
102
+ cm.deadline
103
+
104
+ Not finished yet timeout can be rescheduled by ``shift_by()``
105
+ or ``shift_to()`` methods::
106
+
107
+ async with timeout(1.5) as cm:
108
+ cm.shift(1) # add another second on waiting
109
+ cm.update(loop.time() + 5) # reschedule to now+5 seconds
110
+
111
+ Rescheduling is forbidden if the timeout is expired or after exit from ``async with``
112
+ code block.
113
+
114
+
115
+ Installation
116
+ ------------
117
+
118
+ ::
119
+
120
+ $ pip install async-timeout
121
+
122
+ The library is Python 3 only!
123
+
124
+
125
+
126
+ Authors and License
127
+ -------------------
128
+
129
+ The module is written by Andrew Svetlov.
130
+
131
+ It's *Apache 2* licensed and freely available.
venv/lib/python3.10/site-packages/async_timeout-4.0.3.dist-info/RECORD ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ async_timeout-4.0.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ async_timeout-4.0.3.dist-info/LICENSE,sha256=4Y17uPUT4sRrtYXJS1hb0wcg3TzLId2weG9y0WZY-Sw,568
3
+ async_timeout-4.0.3.dist-info/METADATA,sha256=WQVcnDIXQ2ntebcm-vYjhNLg_VMeTWw13_ReT-U36J4,4209
4
+ async_timeout-4.0.3.dist-info/RECORD,,
5
+ async_timeout-4.0.3.dist-info/WHEEL,sha256=5sUXSg9e4bi7lTLOHcm6QEYwO5TIF1TNbTSVFVjcJcc,92
6
+ async_timeout-4.0.3.dist-info/top_level.txt,sha256=9oM4e7Twq8iD_7_Q3Mz0E6GPIB6vJvRFo-UBwUQtBDU,14
7
+ async_timeout-4.0.3.dist-info/zip-safe,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
8
+ async_timeout/__init__.py,sha256=A0VOqDGQ3cCPFp0NZJKIbx_VRP1Y2xPtQOZebVIUB88,7242
9
+ async_timeout/__pycache__/__init__.cpython-310.pyc,,
10
+ async_timeout/py.typed,sha256=tyozzRT1fziXETDxokmuyt6jhOmtjUbnVNJdZcG7ik0,12
venv/lib/python3.10/site-packages/async_timeout-4.0.3.dist-info/WHEEL ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.41.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
venv/lib/python3.10/site-packages/async_timeout-4.0.3.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ async_timeout
venv/lib/python3.10/site-packages/async_timeout-4.0.3.dist-info/zip-safe ADDED
@@ -0,0 +1 @@
 
 
1
+
venv/lib/python3.10/site-packages/pyarrow/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (15.2 kB). View file
 
venv/lib/python3.10/site-packages/pyarrow/__pycache__/_compute_docstrings.cpython-310.pyc ADDED
Binary file (1.07 kB). View file
 
venv/lib/python3.10/site-packages/pyarrow/__pycache__/_generated_version.cpython-310.pyc ADDED
Binary file (509 Bytes). View file
 
venv/lib/python3.10/site-packages/pyarrow/__pycache__/acero.cpython-310.pyc ADDED
Binary file (8.9 kB). View file
 
venv/lib/python3.10/site-packages/pyarrow/__pycache__/benchmark.cpython-310.pyc ADDED
Binary file (240 Bytes). View file
 
venv/lib/python3.10/site-packages/pyarrow/__pycache__/cffi.cpython-310.pyc ADDED
Binary file (1.73 kB). View file
 
venv/lib/python3.10/site-packages/pyarrow/__pycache__/compute.cpython-310.pyc ADDED
Binary file (19.2 kB). View file
 
venv/lib/python3.10/site-packages/pyarrow/__pycache__/conftest.cpython-310.pyc ADDED
Binary file (5.45 kB). View file
 
venv/lib/python3.10/site-packages/pyarrow/__pycache__/csv.cpython-310.pyc ADDED
Binary file (435 Bytes). View file
 
venv/lib/python3.10/site-packages/pyarrow/__pycache__/cuda.cpython-310.pyc ADDED
Binary file (437 Bytes). View file
 
venv/lib/python3.10/site-packages/pyarrow/__pycache__/dataset.cpython-310.pyc ADDED
Binary file (33.1 kB). View file
 
venv/lib/python3.10/site-packages/pyarrow/__pycache__/feather.cpython-310.pyc ADDED
Binary file (8.2 kB). View file
 
venv/lib/python3.10/site-packages/pyarrow/__pycache__/flight.cpython-310.pyc ADDED
Binary file (1.59 kB). View file
 
venv/lib/python3.10/site-packages/pyarrow/__pycache__/fs.cpython-310.pyc ADDED
Binary file (11.5 kB). View file
 
venv/lib/python3.10/site-packages/pyarrow/__pycache__/ipc.cpython-310.pyc ADDED
Binary file (9.06 kB). View file
 
venv/lib/python3.10/site-packages/pyarrow/__pycache__/json.cpython-310.pyc ADDED
Binary file (263 Bytes). View file
 
venv/lib/python3.10/site-packages/pyarrow/__pycache__/jvm.cpython-310.pyc ADDED
Binary file (8.08 kB). View file
 
venv/lib/python3.10/site-packages/pyarrow/__pycache__/orc.cpython-310.pyc ADDED
Binary file (11.6 kB). View file
 
venv/lib/python3.10/site-packages/pyarrow/__pycache__/pandas_compat.cpython-310.pyc ADDED
Binary file (26.5 kB). View file
 
venv/lib/python3.10/site-packages/pyarrow/__pycache__/substrait.cpython-310.pyc ADDED
Binary file (523 Bytes). View file
 
venv/lib/python3.10/site-packages/pyarrow/__pycache__/types.cpython-310.pyc ADDED
Binary file (8.78 kB). View file
 
venv/lib/python3.10/site-packages/pyarrow/__pycache__/util.cpython-310.pyc ADDED
Binary file (7.06 kB). View file
 
venv/lib/python3.10/site-packages/pyarrow/include/arrow/array/array_base.h ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #pragma once
19
+
20
+ #include <cstdint>
21
+ #include <iosfwd>
22
+ #include <memory>
23
+ #include <string>
24
+ #include <vector>
25
+
26
+ #include "arrow/array/data.h"
27
+ #include "arrow/buffer.h"
28
+ #include "arrow/compare.h"
29
+ #include "arrow/result.h"
30
+ #include "arrow/status.h"
31
+ #include "arrow/type.h"
32
+ #include "arrow/util/bit_util.h"
33
+ #include "arrow/util/macros.h"
34
+ #include "arrow/util/visibility.h"
35
+ #include "arrow/visitor.h"
36
+
37
+ namespace arrow {
38
+
39
+ // ----------------------------------------------------------------------
40
+ // User array accessor types
41
+
42
+ /// \brief Array base type
43
+ /// Immutable data array with some logical type and some length.
44
+ ///
45
+ /// Any memory is owned by the respective Buffer instance (or its parents).
46
+ ///
47
+ /// The base class is only required to have a null bitmap buffer if the null
48
+ /// count is greater than 0
49
+ ///
50
+ /// If known, the null count can be provided in the base Array constructor. If
51
+ /// the null count is not known, pass -1 to indicate that the null count is to
52
+ /// be computed on the first call to null_count()
53
+ class ARROW_EXPORT Array {
54
+ public:
55
+ virtual ~Array() = default;
56
+
57
+ /// \brief Return true if value at index is null. Does not boundscheck
58
+ bool IsNull(int64_t i) const { return !IsValid(i); }
59
+
60
+ /// \brief Return true if value at index is valid (not null). Does not
61
+ /// boundscheck
62
+ bool IsValid(int64_t i) const {
63
+ if (null_bitmap_data_ != NULLPTR) {
64
+ return bit_util::GetBit(null_bitmap_data_, i + data_->offset);
65
+ }
66
+ // Dispatching with a few conditionals like this makes IsNull more
67
+ // efficient for how it is used in practice. Making IsNull virtual
68
+ // would add a vtable lookup to every call and prevent inlining +
69
+ // a potential inner-branch removal.
70
+ if (type_id() == Type::SPARSE_UNION) {
71
+ return !internal::IsNullSparseUnion(*data_, i);
72
+ }
73
+ if (type_id() == Type::DENSE_UNION) {
74
+ return !internal::IsNullDenseUnion(*data_, i);
75
+ }
76
+ if (type_id() == Type::RUN_END_ENCODED) {
77
+ return !internal::IsNullRunEndEncoded(*data_, i);
78
+ }
79
+ return data_->null_count != data_->length;
80
+ }
81
+
82
+ /// \brief Return a Scalar containing the value of this array at i
83
+ Result<std::shared_ptr<Scalar>> GetScalar(int64_t i) const;
84
+
85
+ /// Size in the number of elements this array contains.
86
+ int64_t length() const { return data_->length; }
87
+
88
+ /// A relative position into another array's data, to enable zero-copy
89
+ /// slicing. This value defaults to zero
90
+ int64_t offset() const { return data_->offset; }
91
+
92
+ /// The number of null entries in the array. If the null count was not known
93
+ /// at time of construction (and set to a negative value), then the null
94
+ /// count will be computed and cached on the first invocation of this
95
+ /// function
96
+ int64_t null_count() const;
97
+
98
+ /// \brief Computes the logical null count for arrays of all types including
99
+ /// those that do not have a validity bitmap like union and run-end encoded
100
+ /// arrays
101
+ ///
102
+ /// If the array has a validity bitmap, this function behaves the same as
103
+ /// null_count(). For types that have no validity bitmap, this function will
104
+ /// recompute the null count every time it is called.
105
+ ///
106
+ /// \see GetNullCount
107
+ int64_t ComputeLogicalNullCount() const;
108
+
109
+ const std::shared_ptr<DataType>& type() const { return data_->type; }
110
+ Type::type type_id() const { return data_->type->id(); }
111
+
112
+ /// Buffer for the validity (null) bitmap, if any. Note that Union types
113
+ /// never have a null bitmap.
114
+ ///
115
+ /// Note that for `null_count == 0` or for null type, this will be null.
116
+ /// This buffer does not account for any slice offset
117
+ const std::shared_ptr<Buffer>& null_bitmap() const { return data_->buffers[0]; }
118
+
119
+ /// Raw pointer to the null bitmap.
120
+ ///
121
+ /// Note that for `null_count == 0` or for null type, this will be null.
122
+ /// This buffer does not account for any slice offset
123
+ const uint8_t* null_bitmap_data() const { return null_bitmap_data_; }
124
+
125
+ /// Equality comparison with another array
126
+ bool Equals(const Array& arr, const EqualOptions& = EqualOptions::Defaults()) const;
127
+ bool Equals(const std::shared_ptr<Array>& arr,
128
+ const EqualOptions& = EqualOptions::Defaults()) const;
129
+
130
+ /// \brief Return the formatted unified diff of arrow::Diff between this
131
+ /// Array and another Array
132
+ std::string Diff(const Array& other) const;
133
+
134
+ /// Approximate equality comparison with another array
135
+ ///
136
+ /// epsilon is only used if this is FloatArray or DoubleArray
137
+ bool ApproxEquals(const std::shared_ptr<Array>& arr,
138
+ const EqualOptions& = EqualOptions::Defaults()) const;
139
+ bool ApproxEquals(const Array& arr,
140
+ const EqualOptions& = EqualOptions::Defaults()) const;
141
+
142
+ /// Compare if the range of slots specified are equal for the given array and
143
+ /// this array. end_idx exclusive. This methods does not bounds check.
144
+ bool RangeEquals(int64_t start_idx, int64_t end_idx, int64_t other_start_idx,
145
+ const Array& other,
146
+ const EqualOptions& = EqualOptions::Defaults()) const;
147
+ bool RangeEquals(int64_t start_idx, int64_t end_idx, int64_t other_start_idx,
148
+ const std::shared_ptr<Array>& other,
149
+ const EqualOptions& = EqualOptions::Defaults()) const;
150
+ bool RangeEquals(const Array& other, int64_t start_idx, int64_t end_idx,
151
+ int64_t other_start_idx,
152
+ const EqualOptions& = EqualOptions::Defaults()) const;
153
+ bool RangeEquals(const std::shared_ptr<Array>& other, int64_t start_idx,
154
+ int64_t end_idx, int64_t other_start_idx,
155
+ const EqualOptions& = EqualOptions::Defaults()) const;
156
+
157
+ /// \brief Apply the ArrayVisitor::Visit() method specialized to the array type
158
+ Status Accept(ArrayVisitor* visitor) const;
159
+
160
+ /// Construct a zero-copy view of this array with the given type.
161
+ ///
162
+ /// This method checks if the types are layout-compatible.
163
+ /// Nested types are traversed in depth-first order. Data buffers must have
164
+ /// the same item sizes, even though the logical types may be different.
165
+ /// An error is returned if the types are not layout-compatible.
166
+ Result<std::shared_ptr<Array>> View(const std::shared_ptr<DataType>& type) const;
167
+
168
+ /// \brief Construct a copy of the array with all buffers on destination
169
+ /// Memory Manager
170
+ ///
171
+ /// This method recursively copies the array's buffers and those of its children
172
+ /// onto the destination MemoryManager device and returns the new Array.
173
+ Result<std::shared_ptr<Array>> CopyTo(const std::shared_ptr<MemoryManager>& to) const;
174
+
175
+ /// \brief Construct a new array attempting to zero-copy view if possible.
176
+ ///
177
+ /// Like CopyTo this method recursively goes through all of the array's buffers
178
+ /// and those of it's children and first attempts to create zero-copy
179
+ /// views on the destination MemoryManager device. If it can't, it falls back
180
+ /// to performing a copy. See Buffer::ViewOrCopy.
181
+ Result<std::shared_ptr<Array>> ViewOrCopyTo(
182
+ const std::shared_ptr<MemoryManager>& to) const;
183
+
184
+ /// Construct a zero-copy slice of the array with the indicated offset and
185
+ /// length
186
+ ///
187
+ /// \param[in] offset the position of the first element in the constructed
188
+ /// slice
189
+ /// \param[in] length the length of the slice. If there are not enough
190
+ /// elements in the array, the length will be adjusted accordingly
191
+ ///
192
+ /// \return a new object wrapped in std::shared_ptr<Array>
193
+ std::shared_ptr<Array> Slice(int64_t offset, int64_t length) const;
194
+
195
+ /// Slice from offset until end of the array
196
+ std::shared_ptr<Array> Slice(int64_t offset) const;
197
+
198
+ /// Input-checking variant of Array::Slice
199
+ Result<std::shared_ptr<Array>> SliceSafe(int64_t offset, int64_t length) const;
200
+ /// Input-checking variant of Array::Slice
201
+ Result<std::shared_ptr<Array>> SliceSafe(int64_t offset) const;
202
+
203
+ const std::shared_ptr<ArrayData>& data() const { return data_; }
204
+
205
+ int num_fields() const { return static_cast<int>(data_->child_data.size()); }
206
+
207
+ /// \return PrettyPrint representation of array suitable for debugging
208
+ std::string ToString() const;
209
+
210
+ /// \brief Perform cheap validation checks to determine obvious inconsistencies
211
+ /// within the array's internal data.
212
+ ///
213
+ /// This is O(k) where k is the number of descendents.
214
+ ///
215
+ /// \return Status
216
+ Status Validate() const;
217
+
218
+ /// \brief Perform extensive validation checks to determine inconsistencies
219
+ /// within the array's internal data.
220
+ ///
221
+ /// This is potentially O(k*n) where k is the number of descendents and n
222
+ /// is the array length.
223
+ ///
224
+ /// \return Status
225
+ Status ValidateFull() const;
226
+
227
+ protected:
228
+ Array() = default;
229
+ ARROW_DEFAULT_MOVE_AND_ASSIGN(Array);
230
+
231
+ std::shared_ptr<ArrayData> data_;
232
+ const uint8_t* null_bitmap_data_ = NULLPTR;
233
+
234
+ /// Protected method for constructors
235
+ void SetData(const std::shared_ptr<ArrayData>& data) {
236
+ if (data->buffers.size() > 0) {
237
+ null_bitmap_data_ = data->GetValuesSafe<uint8_t>(0, /*offset=*/0);
238
+ } else {
239
+ null_bitmap_data_ = NULLPTR;
240
+ }
241
+ data_ = data;
242
+ }
243
+
244
+ private:
245
+ ARROW_DISALLOW_COPY_AND_ASSIGN(Array);
246
+
247
+ ARROW_FRIEND_EXPORT friend void PrintTo(const Array& x, std::ostream* os);
248
+ };
249
+
250
+ static inline std::ostream& operator<<(std::ostream& os, const Array& x) {
251
+ os << x.ToString();
252
+ return os;
253
+ }
254
+
255
+ /// Base class for non-nested arrays
256
+ class ARROW_EXPORT FlatArray : public Array {
257
+ protected:
258
+ using Array::Array;
259
+ };
260
+
261
+ /// Base class for arrays of fixed-size logical types
262
+ class ARROW_EXPORT PrimitiveArray : public FlatArray {
263
+ public:
264
+ PrimitiveArray(const std::shared_ptr<DataType>& type, int64_t length,
265
+ const std::shared_ptr<Buffer>& data,
266
+ const std::shared_ptr<Buffer>& null_bitmap = NULLPTR,
267
+ int64_t null_count = kUnknownNullCount, int64_t offset = 0);
268
+
269
+ /// Does not account for any slice offset
270
+ const std::shared_ptr<Buffer>& values() const { return data_->buffers[1]; }
271
+
272
+ protected:
273
+ PrimitiveArray() : raw_values_(NULLPTR) {}
274
+
275
+ void SetData(const std::shared_ptr<ArrayData>& data) {
276
+ this->Array::SetData(data);
277
+ raw_values_ = data->GetValuesSafe<uint8_t>(1, /*offset=*/0);
278
+ }
279
+
280
+ explicit PrimitiveArray(const std::shared_ptr<ArrayData>& data) { SetData(data); }
281
+
282
+ const uint8_t* raw_values_;
283
+ };
284
+
285
+ /// Degenerate null type Array
286
+ class ARROW_EXPORT NullArray : public FlatArray {
287
+ public:
288
+ using TypeClass = NullType;
289
+
290
+ explicit NullArray(const std::shared_ptr<ArrayData>& data) { SetData(data); }
291
+ explicit NullArray(int64_t length);
292
+
293
+ private:
294
+ void SetData(const std::shared_ptr<ArrayData>& data) {
295
+ null_bitmap_data_ = NULLPTR;
296
+ data->null_count = data->length;
297
+ data_ = data;
298
+ }
299
+ };
300
+
301
+ } // namespace arrow
venv/lib/python3.10/site-packages/pyarrow/include/arrow/array/array_nested.h ADDED
@@ -0,0 +1,863 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ // Array accessor classes for List, LargeList, ListView, LargeListView, FixedSizeList,
19
+ // Map, Struct, and Union
20
+
21
+ #pragma once
22
+
23
+ #include <cstdint>
24
+ #include <memory>
25
+ #include <string>
26
+ #include <utility>
27
+ #include <vector>
28
+
29
+ #include "arrow/array/array_base.h"
30
+ #include "arrow/array/data.h"
31
+ #include "arrow/result.h"
32
+ #include "arrow/status.h"
33
+ #include "arrow/type.h"
34
+ #include "arrow/type_fwd.h"
35
+ #include "arrow/util/checked_cast.h"
36
+ #include "arrow/util/macros.h"
37
+ #include "arrow/util/visibility.h"
38
+
39
+ namespace arrow {
40
+
41
+ /// \addtogroup nested-arrays
42
+ ///
43
+ /// @{
44
+
45
+ // ----------------------------------------------------------------------
46
+ // VarLengthListLikeArray
47
+
48
+ template <typename TYPE>
49
+ class VarLengthListLikeArray;
50
+
51
+ namespace internal {
52
+
53
+ // Private helper for [Large]List[View]Array::SetData.
54
+ // Unfortunately, trying to define VarLengthListLikeArray::SetData outside of this header
55
+ // doesn't play well with MSVC.
56
+ template <typename TYPE>
57
+ void SetListData(VarLengthListLikeArray<TYPE>* self,
58
+ const std::shared_ptr<ArrayData>& data,
59
+ Type::type expected_type_id = TYPE::type_id);
60
+
61
+ } // namespace internal
62
+
63
+ /// Base class for variable-sized list and list-view arrays, regardless of offset size.
64
+ template <typename TYPE>
65
+ class VarLengthListLikeArray : public Array {
66
+ public:
67
+ using TypeClass = TYPE;
68
+ using offset_type = typename TypeClass::offset_type;
69
+
70
+ const TypeClass* var_length_list_like_type() const { return this->list_type_; }
71
+
72
+ /// \brief Return array object containing the list's values
73
+ ///
74
+ /// Note that this buffer does not account for any slice offset or length.
75
+ const std::shared_ptr<Array>& values() const { return values_; }
76
+
77
+ /// Note that this buffer does not account for any slice offset or length.
78
+ const std::shared_ptr<Buffer>& value_offsets() const { return data_->buffers[1]; }
79
+
80
+ const std::shared_ptr<DataType>& value_type() const { return list_type_->value_type(); }
81
+
82
+ /// Return pointer to raw value offsets accounting for any slice offset
83
+ const offset_type* raw_value_offsets() const {
84
+ return raw_value_offsets_ + data_->offset;
85
+ }
86
+
87
+ // The following functions will not perform boundschecking
88
+
89
+ offset_type value_offset(int64_t i) const {
90
+ return raw_value_offsets_[i + data_->offset];
91
+ }
92
+
93
+ /// \brief Return the size of the value at a particular index
94
+ ///
95
+ /// Since non-empty null lists and list-views are possible, avoid calling this
96
+ /// function when the list at slot i is null.
97
+ ///
98
+ /// \pre IsValid(i)
99
+ virtual offset_type value_length(int64_t i) const = 0;
100
+
101
+ /// \pre IsValid(i)
102
+ std::shared_ptr<Array> value_slice(int64_t i) const {
103
+ return values_->Slice(value_offset(i), value_length(i));
104
+ }
105
+
106
+ protected:
107
+ friend void internal::SetListData<TYPE>(VarLengthListLikeArray<TYPE>* self,
108
+ const std::shared_ptr<ArrayData>& data,
109
+ Type::type expected_type_id);
110
+
111
+ const TypeClass* list_type_ = NULLPTR;
112
+ std::shared_ptr<Array> values_;
113
+ const offset_type* raw_value_offsets_ = NULLPTR;
114
+ };
115
+
116
+ // ----------------------------------------------------------------------
117
+ // ListArray / LargeListArray
118
+
119
+ template <typename TYPE>
120
+ class BaseListArray : public VarLengthListLikeArray<TYPE> {
121
+ public:
122
+ using TypeClass = TYPE;
123
+ using offset_type = typename TYPE::offset_type;
124
+
125
+ const TypeClass* list_type() const { return this->var_length_list_like_type(); }
126
+
127
+ /// \brief Return the size of the value at a particular index
128
+ ///
129
+ /// Since non-empty null lists are possible, avoid calling this
130
+ /// function when the list at slot i is null.
131
+ ///
132
+ /// \pre IsValid(i)
133
+ offset_type value_length(int64_t i) const final {
134
+ i += this->data_->offset;
135
+ return this->raw_value_offsets_[i + 1] - this->raw_value_offsets_[i];
136
+ }
137
+ };
138
+
139
+ /// Concrete Array class for list data
140
+ class ARROW_EXPORT ListArray : public BaseListArray<ListType> {
141
+ public:
142
+ explicit ListArray(std::shared_ptr<ArrayData> data);
143
+
144
+ ListArray(std::shared_ptr<DataType> type, int64_t length,
145
+ std::shared_ptr<Buffer> value_offsets, std::shared_ptr<Array> values,
146
+ std::shared_ptr<Buffer> null_bitmap = NULLPTR,
147
+ int64_t null_count = kUnknownNullCount, int64_t offset = 0);
148
+
149
+ /// \brief Construct ListArray from array of offsets and child value array
150
+ ///
151
+ /// This function does the bare minimum of validation of the offsets and
152
+ /// input types, and will allocate a new offsets array if necessary (i.e. if
153
+ /// the offsets contain any nulls). If the offsets do not have nulls, they
154
+ /// are assumed to be well-formed.
155
+ ///
156
+ /// If a null_bitmap is not provided, the nulls will be inferred from the offsets'
157
+ /// null bitmap. But if a null_bitmap is provided, the offsets array can't have nulls.
158
+ ///
159
+ /// And when a null_bitmap is provided, the offsets array cannot be a slice (i.e. an
160
+ /// array with offset() > 0).
161
+ ///
162
+ /// \param[in] offsets Array containing n + 1 offsets encoding length and
163
+ /// size. Must be of int32 type
164
+ /// \param[in] values Array containing list values
165
+ /// \param[in] pool MemoryPool in case new offsets array needs to be
166
+ /// allocated because of null values
167
+ /// \param[in] null_bitmap Optional validity bitmap
168
+ /// \param[in] null_count Optional null count in null_bitmap
169
+ static Result<std::shared_ptr<ListArray>> FromArrays(
170
+ const Array& offsets, const Array& values, MemoryPool* pool = default_memory_pool(),
171
+ std::shared_ptr<Buffer> null_bitmap = NULLPTR,
172
+ int64_t null_count = kUnknownNullCount);
173
+
174
+ static Result<std::shared_ptr<ListArray>> FromArrays(
175
+ std::shared_ptr<DataType> type, const Array& offsets, const Array& values,
176
+ MemoryPool* pool = default_memory_pool(),
177
+ std::shared_ptr<Buffer> null_bitmap = NULLPTR,
178
+ int64_t null_count = kUnknownNullCount);
179
+
180
+ /// \brief Build a ListArray from a ListViewArray
181
+ static Result<std::shared_ptr<ListArray>> FromListView(const ListViewArray& source,
182
+ MemoryPool* pool);
183
+
184
+ /// \brief Return an Array that is a concatenation of the lists in this array.
185
+ ///
186
+ /// Note that it's different from `values()` in that it takes into
187
+ /// consideration of this array's offsets as well as null elements backed
188
+ /// by non-empty lists (they are skipped, thus copying may be needed).
189
+ Result<std::shared_ptr<Array>> Flatten(
190
+ MemoryPool* memory_pool = default_memory_pool()) const;
191
+
192
+ /// \brief Return list offsets as an Int32Array
193
+ ///
194
+ /// The returned array will not have a validity bitmap, so you cannot expect
195
+ /// to pass it to ListArray::FromArrays() and get back the same list array
196
+ /// if the original one has nulls.
197
+ std::shared_ptr<Array> offsets() const;
198
+
199
+ protected:
200
+ // This constructor defers SetData to a derived array class
201
+ ListArray() = default;
202
+
203
+ void SetData(const std::shared_ptr<ArrayData>& data);
204
+ };
205
+
206
+ /// Concrete Array class for large list data (with 64-bit offsets)
207
+ class ARROW_EXPORT LargeListArray : public BaseListArray<LargeListType> {
208
+ public:
209
+ explicit LargeListArray(const std::shared_ptr<ArrayData>& data);
210
+
211
+ LargeListArray(const std::shared_ptr<DataType>& type, int64_t length,
212
+ const std::shared_ptr<Buffer>& value_offsets,
213
+ const std::shared_ptr<Array>& values,
214
+ const std::shared_ptr<Buffer>& null_bitmap = NULLPTR,
215
+ int64_t null_count = kUnknownNullCount, int64_t offset = 0);
216
+
217
+ /// \brief Construct LargeListArray from array of offsets and child value array
218
+ ///
219
+ /// This function does the bare minimum of validation of the offsets and
220
+ /// input types, and will allocate a new offsets array if necessary (i.e. if
221
+ /// the offsets contain any nulls). If the offsets do not have nulls, they
222
+ /// are assumed to be well-formed.
223
+ ///
224
+ /// If a null_bitmap is not provided, the nulls will be inferred from the offsets'
225
+ /// null bitmap. But if a null_bitmap is provided, the offsets array can't have nulls.
226
+ ///
227
+ /// And when a null_bitmap is provided, the offsets array cannot be a slice (i.e. an
228
+ /// array with offset() > 0).
229
+ ///
230
+ /// \param[in] offsets Array containing n + 1 offsets encoding length and
231
+ /// size. Must be of int64 type
232
+ /// \param[in] values Array containing list values
233
+ /// \param[in] pool MemoryPool in case new offsets array needs to be
234
+ /// allocated because of null values
235
+ /// \param[in] null_bitmap Optional validity bitmap
236
+ /// \param[in] null_count Optional null count in null_bitmap
237
+ static Result<std::shared_ptr<LargeListArray>> FromArrays(
238
+ const Array& offsets, const Array& values, MemoryPool* pool = default_memory_pool(),
239
+ std::shared_ptr<Buffer> null_bitmap = NULLPTR,
240
+ int64_t null_count = kUnknownNullCount);
241
+
242
+ static Result<std::shared_ptr<LargeListArray>> FromArrays(
243
+ std::shared_ptr<DataType> type, const Array& offsets, const Array& values,
244
+ MemoryPool* pool = default_memory_pool(),
245
+ std::shared_ptr<Buffer> null_bitmap = NULLPTR,
246
+ int64_t null_count = kUnknownNullCount);
247
+
248
+ /// \brief Build a LargeListArray from a LargeListViewArray
249
+ static Result<std::shared_ptr<LargeListArray>> FromListView(
250
+ const LargeListViewArray& source, MemoryPool* pool);
251
+
252
+ /// \brief Return an Array that is a concatenation of the lists in this array.
253
+ ///
254
+ /// Note that it's different from `values()` in that it takes into
255
+ /// consideration of this array's offsets as well as null elements backed
256
+ /// by non-empty lists (they are skipped, thus copying may be needed).
257
+ Result<std::shared_ptr<Array>> Flatten(
258
+ MemoryPool* memory_pool = default_memory_pool()) const;
259
+
260
+ /// \brief Return list offsets as an Int64Array
261
+ std::shared_ptr<Array> offsets() const;
262
+
263
+ protected:
264
+ void SetData(const std::shared_ptr<ArrayData>& data);
265
+ };
266
+
267
+ // ----------------------------------------------------------------------
268
+ // ListViewArray / LargeListViewArray
269
+
270
+ template <typename TYPE>
271
+ class BaseListViewArray : public VarLengthListLikeArray<TYPE> {
272
+ public:
273
+ using TypeClass = TYPE;
274
+ using offset_type = typename TYPE::offset_type;
275
+
276
+ const TypeClass* list_view_type() const { return this->var_length_list_like_type(); }
277
+
278
+ /// \brief Note that this buffer does not account for any slice offset or length.
279
+ const std::shared_ptr<Buffer>& value_sizes() const { return this->data_->buffers[2]; }
280
+
281
+ /// \brief Return pointer to raw value offsets accounting for any slice offset
282
+ const offset_type* raw_value_sizes() const {
283
+ return raw_value_sizes_ + this->data_->offset;
284
+ }
285
+
286
+ /// \brief Return the size of the value at a particular index
287
+ ///
288
+ /// This should not be called if the list-view at slot i is null.
289
+ /// The returned size in those cases could be any value from 0 to the
290
+ /// length of the child values array.
291
+ ///
292
+ /// \pre IsValid(i)
293
+ offset_type value_length(int64_t i) const final {
294
+ return this->raw_value_sizes_[i + this->data_->offset];
295
+ }
296
+
297
+ protected:
298
+ const offset_type* raw_value_sizes_ = NULLPTR;
299
+ };
300
+
301
+ /// \brief Concrete Array class for list-view data
302
+ class ARROW_EXPORT ListViewArray : public BaseListViewArray<ListViewType> {
303
+ public:
304
+ explicit ListViewArray(std::shared_ptr<ArrayData> data);
305
+
306
+ ListViewArray(std::shared_ptr<DataType> type, int64_t length,
307
+ std::shared_ptr<Buffer> value_offsets,
308
+ std::shared_ptr<Buffer> value_sizes, std::shared_ptr<Array> values,
309
+ std::shared_ptr<Buffer> null_bitmap = NULLPTR,
310
+ int64_t null_count = kUnknownNullCount, int64_t offset = 0);
311
+
312
+ /// \brief Construct ListViewArray from array of offsets, sizes, and child
313
+ /// value array
314
+ ///
315
+ /// Construct a ListViewArray using buffers from offsets and sizes arrays
316
+ /// that project views into the child values array.
317
+ ///
318
+ /// This function does the bare minimum of validation of the offsets/sizes and
319
+ /// input types. The offset and length of the offsets and sizes arrays must
320
+ /// match and that will be checked, but their contents will be assumed to be
321
+ /// well-formed.
322
+ ///
323
+ /// If a null_bitmap is not provided, the nulls will be inferred from the
324
+ /// offsets's null bitmap. But if a null_bitmap is provided, the offsets array
325
+ /// can't have nulls.
326
+ ///
327
+ /// And when a null_bitmap is provided, neither the offsets or sizes array can be a
328
+ /// slice (i.e. an array with offset() > 0).
329
+ ///
330
+ /// \param[in] offsets An array of int32 offsets into the values array. NULL values are
331
+ /// supported if the corresponding values in sizes is NULL or 0.
332
+ /// \param[in] sizes An array containing the int32 sizes of every view. NULL values are
333
+ /// taken to represent a NULL list-view in the array being created.
334
+ /// \param[in] values Array containing list values
335
+ /// \param[in] pool MemoryPool
336
+ /// \param[in] null_bitmap Optional validity bitmap
337
+ /// \param[in] null_count Optional null count in null_bitmap
338
+ static Result<std::shared_ptr<ListViewArray>> FromArrays(
339
+ const Array& offsets, const Array& sizes, const Array& values,
340
+ MemoryPool* pool = default_memory_pool(),
341
+ std::shared_ptr<Buffer> null_bitmap = NULLPTR,
342
+ int64_t null_count = kUnknownNullCount);
343
+
344
+ static Result<std::shared_ptr<ListViewArray>> FromArrays(
345
+ std::shared_ptr<DataType> type, const Array& offsets, const Array& sizes,
346
+ const Array& values, MemoryPool* pool = default_memory_pool(),
347
+ std::shared_ptr<Buffer> null_bitmap = NULLPTR,
348
+ int64_t null_count = kUnknownNullCount);
349
+
350
+ /// \brief Build a ListViewArray from a ListArray
351
+ static Result<std::shared_ptr<ListViewArray>> FromList(const ListArray& list_array,
352
+ MemoryPool* pool);
353
+
354
+ /// \brief Return an Array that is a concatenation of the list-views in this array.
355
+ ///
356
+ /// Note that it's different from `values()` in that it takes into
357
+ /// consideration this array's offsets (which can be in any order)
358
+ /// and sizes. Nulls are skipped.
359
+ ///
360
+ /// This function invokes Concatenate() if list-views are non-contiguous. It
361
+ /// will try to minimize the number of array slices passed to Concatenate() by
362
+ /// maximizing the size of each slice (containing as many contiguous
363
+ /// list-views as possible).
364
+ Result<std::shared_ptr<Array>> Flatten(
365
+ MemoryPool* memory_pool = default_memory_pool()) const;
366
+
367
+ /// \brief Return list-view offsets as an Int32Array
368
+ ///
369
+ /// The returned array will not have a validity bitmap, so you cannot expect
370
+ /// to pass it to ListArray::FromArrays() and get back the same list array
371
+ /// if the original one has nulls.
372
+ std::shared_ptr<Array> offsets() const;
373
+
374
+ /// \brief Return list-view sizes as an Int32Array
375
+ ///
376
+ /// The returned array will not have a validity bitmap, so you cannot expect
377
+ /// to pass it to ListViewArray::FromArrays() and get back the same list
378
+ /// array if the original one has nulls.
379
+ std::shared_ptr<Array> sizes() const;
380
+
381
+ protected:
382
+ // This constructor defers SetData to a derived array class
383
+ ListViewArray() = default;
384
+
385
+ void SetData(const std::shared_ptr<ArrayData>& data);
386
+ };
387
+
388
+ /// \brief Concrete Array class for large list-view data (with 64-bit offsets
389
+ /// and sizes)
390
+ class ARROW_EXPORT LargeListViewArray : public BaseListViewArray<LargeListViewType> {
391
+ public:
392
+ explicit LargeListViewArray(std::shared_ptr<ArrayData> data);
393
+
394
+ LargeListViewArray(std::shared_ptr<DataType> type, int64_t length,
395
+ std::shared_ptr<Buffer> value_offsets,
396
+ std::shared_ptr<Buffer> value_sizes, std::shared_ptr<Array> values,
397
+ std::shared_ptr<Buffer> null_bitmap = NULLPTR,
398
+ int64_t null_count = kUnknownNullCount, int64_t offset = 0);
399
+
400
+ /// \brief Construct LargeListViewArray from array of offsets, sizes, and child
401
+ /// value array
402
+ ///
403
+ /// Construct an LargeListViewArray using buffers from offsets and sizes arrays
404
+ /// that project views into the values array.
405
+ ///
406
+ /// This function does the bare minimum of validation of the offsets/sizes and
407
+ /// input types. The offset and length of the offsets and sizes arrays must
408
+ /// match and that will be checked, but their contents will be assumed to be
409
+ /// well-formed.
410
+ ///
411
+ /// If a null_bitmap is not provided, the nulls will be inferred from the offsets' or
412
+ /// sizes' null bitmap. Only one of these two is allowed to have a null bitmap. But if a
413
+ /// null_bitmap is provided, the offsets array and the sizes array can't have nulls.
414
+ ///
415
+ /// And when a null_bitmap is provided, neither the offsets or sizes array can be a
416
+ /// slice (i.e. an array with offset() > 0).
417
+ ///
418
+ /// \param[in] offsets An array of int64 offsets into the values array. NULL values are
419
+ /// supported if the corresponding values in sizes is NULL or 0.
420
+ /// \param[in] sizes An array containing the int64 sizes of every view. NULL values are
421
+ /// taken to represent a NULL list-view in the array being created.
422
+ /// \param[in] values Array containing list values
423
+ /// \param[in] pool MemoryPool
424
+ /// \param[in] null_bitmap Optional validity bitmap
425
+ /// \param[in] null_count Optional null count in null_bitmap
426
+ static Result<std::shared_ptr<LargeListViewArray>> FromArrays(
427
+ const Array& offsets, const Array& sizes, const Array& values,
428
+ MemoryPool* pool = default_memory_pool(),
429
+ std::shared_ptr<Buffer> null_bitmap = NULLPTR,
430
+ int64_t null_count = kUnknownNullCount);
431
+
432
+ static Result<std::shared_ptr<LargeListViewArray>> FromArrays(
433
+ std::shared_ptr<DataType> type, const Array& offsets, const Array& sizes,
434
+ const Array& values, MemoryPool* pool = default_memory_pool(),
435
+ std::shared_ptr<Buffer> null_bitmap = NULLPTR,
436
+ int64_t null_count = kUnknownNullCount);
437
+
438
+ /// \brief Build a LargeListViewArray from a LargeListArray
439
+ static Result<std::shared_ptr<LargeListViewArray>> FromList(
440
+ const LargeListArray& list_array, MemoryPool* pool);
441
+
442
+ /// \brief Return an Array that is a concatenation of the large list-views in this
443
+ /// array.
444
+ ///
445
+ /// Note that it's different from `values()` in that it takes into
446
+ /// consideration this array's offsets (which can be in any order)
447
+ /// and sizes. Nulls are skipped.
448
+ Result<std::shared_ptr<Array>> Flatten(
449
+ MemoryPool* memory_pool = default_memory_pool()) const;
450
+
451
+ /// \brief Return list-view offsets as an Int64Array
452
+ ///
453
+ /// The returned array will not have a validity bitmap, so you cannot expect
454
+ /// to pass it to LargeListArray::FromArrays() and get back the same list array
455
+ /// if the original one has nulls.
456
+ std::shared_ptr<Array> offsets() const;
457
+
458
+ /// \brief Return list-view sizes as an Int64Array
459
+ ///
460
+ /// The returned array will not have a validity bitmap, so you cannot expect
461
+ /// to pass it to LargeListViewArray::FromArrays() and get back the same list
462
+ /// array if the original one has nulls.
463
+ std::shared_ptr<Array> sizes() const;
464
+
465
+ protected:
466
+ // This constructor defers SetData to a derived array class
467
+ LargeListViewArray() = default;
468
+
469
+ void SetData(const std::shared_ptr<ArrayData>& data);
470
+ };
471
+
472
+ // ----------------------------------------------------------------------
473
+ // MapArray
474
+
475
+ /// Concrete Array class for map data
476
+ ///
477
+ /// NB: "value" in this context refers to a pair of a key and the corresponding item
478
+ class ARROW_EXPORT MapArray : public ListArray {
479
+ public:
480
+ using TypeClass = MapType;
481
+
482
+ explicit MapArray(const std::shared_ptr<ArrayData>& data);
483
+
484
+ MapArray(const std::shared_ptr<DataType>& type, int64_t length,
485
+ const std::shared_ptr<Buffer>& value_offsets,
486
+ const std::shared_ptr<Array>& keys, const std::shared_ptr<Array>& items,
487
+ const std::shared_ptr<Buffer>& null_bitmap = NULLPTR,
488
+ int64_t null_count = kUnknownNullCount, int64_t offset = 0);
489
+
490
+ MapArray(const std::shared_ptr<DataType>& type, int64_t length, BufferVector buffers,
491
+ const std::shared_ptr<Array>& keys, const std::shared_ptr<Array>& items,
492
+ int64_t null_count = kUnknownNullCount, int64_t offset = 0);
493
+
494
+ MapArray(const std::shared_ptr<DataType>& type, int64_t length,
495
+ const std::shared_ptr<Buffer>& value_offsets,
496
+ const std::shared_ptr<Array>& values,
497
+ const std::shared_ptr<Buffer>& null_bitmap = NULLPTR,
498
+ int64_t null_count = kUnknownNullCount, int64_t offset = 0);
499
+
500
+ /// \brief Construct MapArray from array of offsets and child key, item arrays
501
+ ///
502
+ /// This function does the bare minimum of validation of the offsets and
503
+ /// input types, and will allocate a new offsets array if necessary (i.e. if
504
+ /// the offsets contain any nulls). If the offsets do not have nulls, they
505
+ /// are assumed to be well-formed
506
+ ///
507
+ /// \param[in] offsets Array containing n + 1 offsets encoding length and
508
+ /// size. Must be of int32 type
509
+ /// \param[in] keys Array containing key values
510
+ /// \param[in] items Array containing item values
511
+ /// \param[in] pool MemoryPool in case new offsets array needs to be
512
+ /// allocated because of null values
513
+ static Result<std::shared_ptr<Array>> FromArrays(
514
+ const std::shared_ptr<Array>& offsets, const std::shared_ptr<Array>& keys,
515
+ const std::shared_ptr<Array>& items, MemoryPool* pool = default_memory_pool());
516
+
517
+ static Result<std::shared_ptr<Array>> FromArrays(
518
+ std::shared_ptr<DataType> type, const std::shared_ptr<Array>& offsets,
519
+ const std::shared_ptr<Array>& keys, const std::shared_ptr<Array>& items,
520
+ MemoryPool* pool = default_memory_pool());
521
+
522
+ const MapType* map_type() const { return map_type_; }
523
+
524
+ /// \brief Return array object containing all map keys
525
+ const std::shared_ptr<Array>& keys() const { return keys_; }
526
+
527
+ /// \brief Return array object containing all mapped items
528
+ const std::shared_ptr<Array>& items() const { return items_; }
529
+
530
+ /// Validate child data before constructing the actual MapArray.
531
+ static Status ValidateChildData(
532
+ const std::vector<std::shared_ptr<ArrayData>>& child_data);
533
+
534
+ protected:
535
+ void SetData(const std::shared_ptr<ArrayData>& data);
536
+
537
+ static Result<std::shared_ptr<Array>> FromArraysInternal(
538
+ std::shared_ptr<DataType> type, const std::shared_ptr<Array>& offsets,
539
+ const std::shared_ptr<Array>& keys, const std::shared_ptr<Array>& items,
540
+ MemoryPool* pool);
541
+
542
+ private:
543
+ const MapType* map_type_;
544
+ std::shared_ptr<Array> keys_, items_;
545
+ };
546
+
547
+ // ----------------------------------------------------------------------
548
+ // FixedSizeListArray
549
+
550
+ /// Concrete Array class for fixed size list data
551
+ class ARROW_EXPORT FixedSizeListArray : public Array {
552
+ public:
553
+ using TypeClass = FixedSizeListType;
554
+ using offset_type = TypeClass::offset_type;
555
+
556
+ explicit FixedSizeListArray(const std::shared_ptr<ArrayData>& data);
557
+
558
+ FixedSizeListArray(const std::shared_ptr<DataType>& type, int64_t length,
559
+ const std::shared_ptr<Array>& values,
560
+ const std::shared_ptr<Buffer>& null_bitmap = NULLPTR,
561
+ int64_t null_count = kUnknownNullCount, int64_t offset = 0);
562
+
563
+ const FixedSizeListType* list_type() const;
564
+
565
+ /// \brief Return array object containing the list's values
566
+ const std::shared_ptr<Array>& values() const;
567
+
568
+ const std::shared_ptr<DataType>& value_type() const;
569
+
570
+ // The following functions will not perform boundschecking
571
+ int64_t value_offset(int64_t i) const {
572
+ i += data_->offset;
573
+ return list_size_ * i;
574
+ }
575
+ /// \brief Return the fixed-size of the values
576
+ ///
577
+ /// No matter the value of the index parameter, the result is the same.
578
+ /// So even when the value at slot i is null, this function will return a
579
+ /// non-zero size.
580
+ ///
581
+ /// \pre IsValid(i)
582
+ int32_t value_length(int64_t i = 0) const {
583
+ ARROW_UNUSED(i);
584
+ return list_size_;
585
+ }
586
+ /// \pre IsValid(i)
587
+ std::shared_ptr<Array> value_slice(int64_t i) const {
588
+ return values_->Slice(value_offset(i), value_length(i));
589
+ }
590
+
591
+ /// \brief Return an Array that is a concatenation of the lists in this array.
592
+ ///
593
+ /// Note that it's different from `values()` in that it takes into
594
+ /// consideration null elements (they are skipped, thus copying may be needed).
595
+ Result<std::shared_ptr<Array>> Flatten(
596
+ MemoryPool* memory_pool = default_memory_pool()) const;
597
+
598
+ /// \brief Construct FixedSizeListArray from child value array and value_length
599
+ ///
600
+ /// \param[in] values Array containing list values
601
+ /// \param[in] list_size The fixed length of each list
602
+ /// \param[in] null_bitmap Optional validity bitmap
603
+ /// \param[in] null_count Optional null count in null_bitmap
604
+ /// \return Will have length equal to values.length() / list_size
605
+ static Result<std::shared_ptr<Array>> FromArrays(
606
+ const std::shared_ptr<Array>& values, int32_t list_size,
607
+ std::shared_ptr<Buffer> null_bitmap = NULLPTR,
608
+ int64_t null_count = kUnknownNullCount);
609
+
610
+ /// \brief Construct FixedSizeListArray from child value array and type
611
+ ///
612
+ /// \param[in] values Array containing list values
613
+ /// \param[in] type The fixed sized list type
614
+ /// \param[in] null_bitmap Optional validity bitmap
615
+ /// \param[in] null_count Optional null count in null_bitmap
616
+ /// \return Will have length equal to values.length() / type.list_size()
617
+ static Result<std::shared_ptr<Array>> FromArrays(
618
+ const std::shared_ptr<Array>& values, std::shared_ptr<DataType> type,
619
+ std::shared_ptr<Buffer> null_bitmap = NULLPTR,
620
+ int64_t null_count = kUnknownNullCount);
621
+
622
+ protected:
623
+ void SetData(const std::shared_ptr<ArrayData>& data);
624
+ int32_t list_size_;
625
+
626
+ private:
627
+ std::shared_ptr<Array> values_;
628
+ };
629
+
630
+ // ----------------------------------------------------------------------
631
+ // Struct
632
+
633
+ /// Concrete Array class for struct data
634
+ class ARROW_EXPORT StructArray : public Array {
635
+ public:
636
+ using TypeClass = StructType;
637
+
638
+ explicit StructArray(const std::shared_ptr<ArrayData>& data);
639
+
640
+ StructArray(const std::shared_ptr<DataType>& type, int64_t length,
641
+ const std::vector<std::shared_ptr<Array>>& children,
642
+ std::shared_ptr<Buffer> null_bitmap = NULLPTR,
643
+ int64_t null_count = kUnknownNullCount, int64_t offset = 0);
644
+
645
+ /// \brief Return a StructArray from child arrays and field names.
646
+ ///
647
+ /// The length and data type are automatically inferred from the arguments.
648
+ /// There should be at least one child array.
649
+ static Result<std::shared_ptr<StructArray>> Make(
650
+ const ArrayVector& children, const std::vector<std::string>& field_names,
651
+ std::shared_ptr<Buffer> null_bitmap = NULLPTR,
652
+ int64_t null_count = kUnknownNullCount, int64_t offset = 0);
653
+
654
+ /// \brief Return a StructArray from child arrays and fields.
655
+ ///
656
+ /// The length is automatically inferred from the arguments.
657
+ /// There should be at least one child array. This method does not
658
+ /// check that field types and child array types are consistent.
659
+ static Result<std::shared_ptr<StructArray>> Make(
660
+ const ArrayVector& children, const FieldVector& fields,
661
+ std::shared_ptr<Buffer> null_bitmap = NULLPTR,
662
+ int64_t null_count = kUnknownNullCount, int64_t offset = 0);
663
+
664
+ const StructType* struct_type() const;
665
+
666
+ // Return a shared pointer in case the requestor desires to share ownership
667
+ // with this array. The returned array has its offset, length and null
668
+ // count adjusted.
669
+ const std::shared_ptr<Array>& field(int pos) const;
670
+
671
+ const ArrayVector& fields() const;
672
+
673
+ /// Returns null if name not found
674
+ std::shared_ptr<Array> GetFieldByName(const std::string& name) const;
675
+
676
+ /// Indicate if field named `name` can be found unambiguously in the struct.
677
+ Status CanReferenceFieldByName(const std::string& name) const;
678
+
679
+ /// Indicate if fields named `names` can be found unambiguously in the struct.
680
+ Status CanReferenceFieldsByNames(const std::vector<std::string>& names) const;
681
+
682
+ /// \brief Flatten this array as a vector of arrays, one for each field
683
+ ///
684
+ /// \param[in] pool The pool to allocate null bitmaps from, if necessary
685
+ Result<ArrayVector> Flatten(MemoryPool* pool = default_memory_pool()) const;
686
+
687
+ /// \brief Get one of the child arrays, combining its null bitmap
688
+ /// with the parent struct array's bitmap.
689
+ ///
690
+ /// \param[in] index Which child array to get
691
+ /// \param[in] pool The pool to allocate null bitmaps from, if necessary
692
+ Result<std::shared_ptr<Array>> GetFlattenedField(
693
+ int index, MemoryPool* pool = default_memory_pool()) const;
694
+
695
+ private:
696
+ // For caching boxed child data
697
+ // XXX This is not handled in a thread-safe manner.
698
+ mutable ArrayVector boxed_fields_;
699
+ };
700
+
701
+ // ----------------------------------------------------------------------
702
+ // Union
703
+
704
+ /// Base class for SparseUnionArray and DenseUnionArray
705
+ class ARROW_EXPORT UnionArray : public Array {
706
+ public:
707
+ using type_code_t = int8_t;
708
+
709
+ /// Note that this buffer does not account for any slice offset
710
+ const std::shared_ptr<Buffer>& type_codes() const { return data_->buffers[1]; }
711
+
712
+ const type_code_t* raw_type_codes() const { return raw_type_codes_ + data_->offset; }
713
+
714
+ /// The logical type code of the value at index.
715
+ type_code_t type_code(int64_t i) const { return raw_type_codes_[i + data_->offset]; }
716
+
717
+ /// The physical child id containing value at index.
718
+ int child_id(int64_t i) const {
719
+ return union_type_->child_ids()[raw_type_codes_[i + data_->offset]];
720
+ }
721
+
722
+ const UnionType* union_type() const { return union_type_; }
723
+
724
+ UnionMode::type mode() const { return union_type_->mode(); }
725
+
726
+ /// \brief Return the given field as an individual array.
727
+ ///
728
+ /// For sparse unions, the returned array has its offset, length and null
729
+ /// count adjusted.
730
+ std::shared_ptr<Array> field(int pos) const;
731
+
732
+ protected:
733
+ void SetData(std::shared_ptr<ArrayData> data);
734
+
735
+ const type_code_t* raw_type_codes_;
736
+ const UnionType* union_type_;
737
+
738
+ // For caching boxed child data
739
+ mutable std::vector<std::shared_ptr<Array>> boxed_fields_;
740
+ };
741
+
742
+ /// Concrete Array class for sparse union data
743
+ class ARROW_EXPORT SparseUnionArray : public UnionArray {
744
+ public:
745
+ using TypeClass = SparseUnionType;
746
+
747
+ explicit SparseUnionArray(std::shared_ptr<ArrayData> data);
748
+
749
+ SparseUnionArray(std::shared_ptr<DataType> type, int64_t length, ArrayVector children,
750
+ std::shared_ptr<Buffer> type_ids, int64_t offset = 0);
751
+
752
+ /// \brief Construct SparseUnionArray from type_ids and children
753
+ ///
754
+ /// This function does the bare minimum of validation of the input types.
755
+ ///
756
+ /// \param[in] type_ids An array of logical type ids for the union type
757
+ /// \param[in] children Vector of children Arrays containing the data for each type.
758
+ /// \param[in] type_codes Vector of type codes.
759
+ static Result<std::shared_ptr<Array>> Make(const Array& type_ids, ArrayVector children,
760
+ std::vector<type_code_t> type_codes) {
761
+ return Make(std::move(type_ids), std::move(children), std::vector<std::string>{},
762
+ std::move(type_codes));
763
+ }
764
+
765
+ /// \brief Construct SparseUnionArray with custom field names from type_ids and children
766
+ ///
767
+ /// This function does the bare minimum of validation of the input types.
768
+ ///
769
+ /// \param[in] type_ids An array of logical type ids for the union type
770
+ /// \param[in] children Vector of children Arrays containing the data for each type.
771
+ /// \param[in] field_names Vector of strings containing the name of each field.
772
+ /// \param[in] type_codes Vector of type codes.
773
+ static Result<std::shared_ptr<Array>> Make(const Array& type_ids, ArrayVector children,
774
+ std::vector<std::string> field_names = {},
775
+ std::vector<type_code_t> type_codes = {});
776
+
777
+ const SparseUnionType* union_type() const {
778
+ return internal::checked_cast<const SparseUnionType*>(union_type_);
779
+ }
780
+
781
+ /// \brief Get one of the child arrays, adjusting its null bitmap
782
+ /// where the union array type code does not match.
783
+ ///
784
+ /// \param[in] index Which child array to get (i.e. the physical index, not the type
785
+ /// code) \param[in] pool The pool to allocate null bitmaps from, if necessary
786
+ Result<std::shared_ptr<Array>> GetFlattenedField(
787
+ int index, MemoryPool* pool = default_memory_pool()) const;
788
+
789
+ protected:
790
+ void SetData(std::shared_ptr<ArrayData> data);
791
+ };
792
+
793
+ /// \brief Concrete Array class for dense union data
794
+ ///
795
+ /// Note that union types do not have a validity bitmap
796
+ class ARROW_EXPORT DenseUnionArray : public UnionArray {
797
+ public:
798
+ using TypeClass = DenseUnionType;
799
+
800
+ explicit DenseUnionArray(const std::shared_ptr<ArrayData>& data);
801
+
802
+ DenseUnionArray(std::shared_ptr<DataType> type, int64_t length, ArrayVector children,
803
+ std::shared_ptr<Buffer> type_ids,
804
+ std::shared_ptr<Buffer> value_offsets = NULLPTR, int64_t offset = 0);
805
+
806
+ /// \brief Construct DenseUnionArray from type_ids, value_offsets, and children
807
+ ///
808
+ /// This function does the bare minimum of validation of the offsets and
809
+ /// input types.
810
+ ///
811
+ /// \param[in] type_ids An array of logical type ids for the union type
812
+ /// \param[in] value_offsets An array of signed int32 values indicating the
813
+ /// relative offset into the respective child array for the type in a given slot.
814
+ /// The respective offsets for each child value array must be in order / increasing.
815
+ /// \param[in] children Vector of children Arrays containing the data for each type.
816
+ /// \param[in] type_codes Vector of type codes.
817
+ static Result<std::shared_ptr<Array>> Make(const Array& type_ids,
818
+ const Array& value_offsets,
819
+ ArrayVector children,
820
+ std::vector<type_code_t> type_codes) {
821
+ return Make(type_ids, value_offsets, std::move(children), std::vector<std::string>{},
822
+ std::move(type_codes));
823
+ }
824
+
825
+ /// \brief Construct DenseUnionArray with custom field names from type_ids,
826
+ /// value_offsets, and children
827
+ ///
828
+ /// This function does the bare minimum of validation of the offsets and
829
+ /// input types.
830
+ ///
831
+ /// \param[in] type_ids An array of logical type ids for the union type
832
+ /// \param[in] value_offsets An array of signed int32 values indicating the
833
+ /// relative offset into the respective child array for the type in a given slot.
834
+ /// The respective offsets for each child value array must be in order / increasing.
835
+ /// \param[in] children Vector of children Arrays containing the data for each type.
836
+ /// \param[in] field_names Vector of strings containing the name of each field.
837
+ /// \param[in] type_codes Vector of type codes.
838
+ static Result<std::shared_ptr<Array>> Make(const Array& type_ids,
839
+ const Array& value_offsets,
840
+ ArrayVector children,
841
+ std::vector<std::string> field_names = {},
842
+ std::vector<type_code_t> type_codes = {});
843
+
844
+ const DenseUnionType* union_type() const {
845
+ return internal::checked_cast<const DenseUnionType*>(union_type_);
846
+ }
847
+
848
+ /// Note that this buffer does not account for any slice offset
849
+ const std::shared_ptr<Buffer>& value_offsets() const { return data_->buffers[2]; }
850
+
851
+ int32_t value_offset(int64_t i) const { return raw_value_offsets_[i + data_->offset]; }
852
+
853
+ const int32_t* raw_value_offsets() const { return raw_value_offsets_ + data_->offset; }
854
+
855
+ protected:
856
+ const int32_t* raw_value_offsets_;
857
+
858
+ void SetData(const std::shared_ptr<ArrayData>& data);
859
+ };
860
+
861
+ /// @}
862
+
863
+ } // namespace arrow
venv/lib/python3.10/site-packages/pyarrow/include/arrow/array/array_run_end.h ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ // Array accessor classes run-end encoded arrays
19
+
20
+ #pragma once
21
+
22
+ #include <cstdint>
23
+ #include <memory>
24
+ #include <string>
25
+ #include <utility>
26
+ #include <vector>
27
+
28
+ #include "arrow/array/array_base.h"
29
+ #include "arrow/array/data.h"
30
+ #include "arrow/result.h"
31
+ #include "arrow/status.h"
32
+ #include "arrow/type.h"
33
+ #include "arrow/type_fwd.h"
34
+ #include "arrow/util/checked_cast.h"
35
+ #include "arrow/util/macros.h"
36
+ #include "arrow/util/visibility.h"
37
+
38
+ namespace arrow {
39
+
40
+ /// \addtogroup run-end-encoded-arrays
41
+ ///
42
+ /// @{
43
+
44
+ // ----------------------------------------------------------------------
45
+ // RunEndEncoded
46
+
47
+ /// \brief Array type for run-end encoded data
48
+ class ARROW_EXPORT RunEndEncodedArray : public Array {
49
+ private:
50
+ std::shared_ptr<Array> run_ends_array_;
51
+ std::shared_ptr<Array> values_array_;
52
+
53
+ public:
54
+ using TypeClass = RunEndEncodedType;
55
+
56
+ explicit RunEndEncodedArray(const std::shared_ptr<ArrayData>& data);
57
+
58
+ /// \brief Construct a RunEndEncodedArray from all parameters
59
+ ///
60
+ /// The length and offset parameters refer to the dimensions of the logical
61
+ /// array which is the array we would get after expanding all the runs into
62
+ /// repeated values. As such, length can be much greater than the length of
63
+ /// the child run_ends and values arrays.
64
+ RunEndEncodedArray(const std::shared_ptr<DataType>& type, int64_t length,
65
+ const std::shared_ptr<Array>& run_ends,
66
+ const std::shared_ptr<Array>& values, int64_t offset = 0);
67
+
68
+ /// \brief Construct a RunEndEncodedArray from all parameters
69
+ ///
70
+ /// The length and offset parameters refer to the dimensions of the logical
71
+ /// array which is the array we would get after expanding all the runs into
72
+ /// repeated values. As such, length can be much greater than the length of
73
+ /// the child run_ends and values arrays.
74
+ static Result<std::shared_ptr<RunEndEncodedArray>> Make(
75
+ const std::shared_ptr<DataType>& type, int64_t logical_length,
76
+ const std::shared_ptr<Array>& run_ends, const std::shared_ptr<Array>& values,
77
+ int64_t logical_offset = 0);
78
+
79
+ /// \brief Construct a RunEndEncodedArray from values and run ends arrays
80
+ ///
81
+ /// The data type is automatically inferred from the arguments.
82
+ /// The run_ends and values arrays must have the same length.
83
+ static Result<std::shared_ptr<RunEndEncodedArray>> Make(
84
+ int64_t logical_length, const std::shared_ptr<Array>& run_ends,
85
+ const std::shared_ptr<Array>& values, int64_t logical_offset = 0);
86
+
87
+ protected:
88
+ void SetData(const std::shared_ptr<ArrayData>& data);
89
+
90
+ public:
91
+ /// \brief Returns an array holding the logical indexes of each run-end
92
+ ///
93
+ /// The physical offset to the array is applied.
94
+ const std::shared_ptr<Array>& run_ends() const { return run_ends_array_; }
95
+
96
+ /// \brief Returns an array holding the values of each run
97
+ ///
98
+ /// The physical offset to the array is applied.
99
+ const std::shared_ptr<Array>& values() const { return values_array_; }
100
+
101
+ /// \brief Returns an array holding the logical indexes of each run end
102
+ ///
103
+ /// If a non-zero logical offset is set, this function allocates a new
104
+ /// array and rewrites all the run end values to be relative to the logical
105
+ /// offset and cuts the end of the array to the logical length.
106
+ Result<std::shared_ptr<Array>> LogicalRunEnds(MemoryPool* pool) const;
107
+
108
+ /// \brief Returns an array holding the values of each run
109
+ ///
110
+ /// If a non-zero logical offset is set, this function allocates a new
111
+ /// array containing only the values within the logical range.
112
+ std::shared_ptr<Array> LogicalValues() const;
113
+
114
+ /// \brief Find the physical offset of this REE array
115
+ ///
116
+ /// This function uses binary-search, so it has a O(log N) cost.
117
+ int64_t FindPhysicalOffset() const;
118
+
119
+ /// \brief Find the physical length of this REE array
120
+ ///
121
+ /// The physical length of an REE is the number of physical values (and
122
+ /// run-ends) necessary to represent the logical range of values from offset
123
+ /// to length.
124
+ ///
125
+ /// Avoid calling this function if the physical length can be established in
126
+ /// some other way (e.g. when iterating over the runs sequentially until the
127
+ /// end). This function uses binary-search, so it has a O(log N) cost.
128
+ int64_t FindPhysicalLength() const;
129
+ };
130
+
131
+ /// @}
132
+
133
+ } // namespace arrow
venv/lib/python3.10/site-packages/pyarrow/include/arrow/array/builder_base.h ADDED
@@ -0,0 +1,370 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #pragma once
19
+
20
+ #include <algorithm> // IWYU pragma: keep
21
+ #include <cstdint>
22
+ #include <limits>
23
+ #include <memory>
24
+ #include <utility>
25
+ #include <vector>
26
+
27
+ #include "arrow/array/array_base.h"
28
+ #include "arrow/array/array_primitive.h"
29
+ #include "arrow/buffer.h"
30
+ #include "arrow/buffer_builder.h"
31
+ #include "arrow/result.h"
32
+ #include "arrow/status.h"
33
+ #include "arrow/type_fwd.h"
34
+ #include "arrow/util/macros.h"
35
+ #include "arrow/util/visibility.h"
36
+
37
+ namespace arrow {
38
+
39
+ namespace internal {
40
+
41
+ template <class Builder, class V>
42
+ class ArrayBuilderExtraOps {
43
+ public:
44
+ /// \brief Append a value from an optional or null if it has no value.
45
+ Status AppendOrNull(const std::optional<V>& value) {
46
+ auto* self = static_cast<Builder*>(this);
47
+ return value.has_value() ? self->Append(*value) : self->AppendNull();
48
+ }
49
+
50
+ /// \brief Append a value from an optional or null if it has no value.
51
+ ///
52
+ /// Unsafe methods don't check existing size.
53
+ void UnsafeAppendOrNull(const std::optional<V>& value) {
54
+ auto* self = static_cast<Builder*>(this);
55
+ return value.has_value() ? self->UnsafeAppend(*value) : self->UnsafeAppendNull();
56
+ }
57
+ };
58
+
59
+ } // namespace internal
60
+
61
+ /// \defgroup numeric-builders Concrete builder subclasses for numeric types
62
+ /// @{
63
+ /// @}
64
+
65
+ /// \defgroup temporal-builders Concrete builder subclasses for temporal types
66
+ /// @{
67
+ /// @}
68
+
69
+ /// \defgroup binary-builders Concrete builder subclasses for binary types
70
+ /// @{
71
+ /// @}
72
+
73
+ /// \defgroup nested-builders Concrete builder subclasses for nested types
74
+ /// @{
75
+ /// @}
76
+
77
+ /// \defgroup dictionary-builders Concrete builder subclasses for dictionary types
78
+ /// @{
79
+ /// @}
80
+
81
+ /// \defgroup run-end-encoded-builders Concrete builder subclasses for run-end encoded
82
+ /// arrays
83
+ /// @{
84
+ /// @}
85
+
86
+ constexpr int64_t kMinBuilderCapacity = 1 << 5;
87
+ constexpr int64_t kListMaximumElements = std::numeric_limits<int32_t>::max() - 1;
88
+
89
+ /// Base class for all data array builders.
90
+ ///
91
+ /// This class provides a facilities for incrementally building the null bitmap
92
+ /// (see Append methods) and as a side effect the current number of slots and
93
+ /// the null count.
94
+ ///
95
+ /// \note Users are expected to use builders as one of the concrete types below.
96
+ /// For example, ArrayBuilder* pointing to BinaryBuilder should be downcast before use.
97
+ class ARROW_EXPORT ArrayBuilder {
98
+ public:
99
+ explicit ArrayBuilder(MemoryPool* pool, int64_t alignment = kDefaultBufferAlignment)
100
+ : pool_(pool), alignment_(alignment), null_bitmap_builder_(pool, alignment) {}
101
+
102
+ ARROW_DEFAULT_MOVE_AND_ASSIGN(ArrayBuilder);
103
+
104
+ virtual ~ArrayBuilder() = default;
105
+
106
+ /// For nested types. Since the objects are owned by this class instance, we
107
+ /// skip shared pointers and just return a raw pointer
108
+ ArrayBuilder* child(int i) { return children_[i].get(); }
109
+
110
+ const std::shared_ptr<ArrayBuilder>& child_builder(int i) const { return children_[i]; }
111
+
112
+ int num_children() const { return static_cast<int>(children_.size()); }
113
+
114
+ virtual int64_t length() const { return length_; }
115
+ int64_t null_count() const { return null_count_; }
116
+ int64_t capacity() const { return capacity_; }
117
+
118
+ /// \brief Ensure that enough memory has been allocated to fit the indicated
119
+ /// number of total elements in the builder, including any that have already
120
+ /// been appended. Does not account for reallocations that may be due to
121
+ /// variable size data, like binary values. To make space for incremental
122
+ /// appends, use Reserve instead.
123
+ ///
124
+ /// \param[in] capacity the minimum number of total array values to
125
+ /// accommodate. Must be greater than the current capacity.
126
+ /// \return Status
127
+ virtual Status Resize(int64_t capacity);
128
+
129
+ /// \brief Ensure that there is enough space allocated to append the indicated
130
+ /// number of elements without any further reallocation. Overallocation is
131
+ /// used in order to minimize the impact of incremental Reserve() calls.
132
+ /// Note that additional_capacity is relative to the current number of elements
133
+ /// rather than to the current capacity, so calls to Reserve() which are not
134
+ /// interspersed with addition of new elements may not increase the capacity.
135
+ ///
136
+ /// \param[in] additional_capacity the number of additional array values
137
+ /// \return Status
138
+ Status Reserve(int64_t additional_capacity) {
139
+ auto current_capacity = capacity();
140
+ auto min_capacity = length() + additional_capacity;
141
+ if (min_capacity <= current_capacity) return Status::OK();
142
+
143
+ // leave growth factor up to BufferBuilder
144
+ auto new_capacity = BufferBuilder::GrowByFactor(current_capacity, min_capacity);
145
+ return Resize(new_capacity);
146
+ }
147
+
148
+ /// Reset the builder.
149
+ virtual void Reset();
150
+
151
+ /// \brief Append a null value to builder
152
+ virtual Status AppendNull() = 0;
153
+ /// \brief Append a number of null values to builder
154
+ virtual Status AppendNulls(int64_t length) = 0;
155
+
156
+ /// \brief Append a non-null value to builder
157
+ ///
158
+ /// The appended value is an implementation detail, but the corresponding
159
+ /// memory slot is guaranteed to be initialized.
160
+ /// This method is useful when appending a null value to a parent nested type.
161
+ virtual Status AppendEmptyValue() = 0;
162
+
163
+ /// \brief Append a number of non-null values to builder
164
+ ///
165
+ /// The appended values are an implementation detail, but the corresponding
166
+ /// memory slot is guaranteed to be initialized.
167
+ /// This method is useful when appending null values to a parent nested type.
168
+ virtual Status AppendEmptyValues(int64_t length) = 0;
169
+
170
+ /// \brief Append a value from a scalar
171
+ Status AppendScalar(const Scalar& scalar) { return AppendScalar(scalar, 1); }
172
+ virtual Status AppendScalar(const Scalar& scalar, int64_t n_repeats);
173
+ virtual Status AppendScalars(const ScalarVector& scalars);
174
+
175
+ /// \brief Append a range of values from an array.
176
+ ///
177
+ /// The given array must be the same type as the builder.
178
+ virtual Status AppendArraySlice(const ArraySpan& array, int64_t offset,
179
+ int64_t length) {
180
+ return Status::NotImplemented("AppendArraySlice for builder for ", *type());
181
+ }
182
+
183
+ /// \brief Return result of builder as an internal generic ArrayData
184
+ /// object. Resets builder except for dictionary builder
185
+ ///
186
+ /// \param[out] out the finalized ArrayData object
187
+ /// \return Status
188
+ virtual Status FinishInternal(std::shared_ptr<ArrayData>* out) = 0;
189
+
190
+ /// \brief Return result of builder as an Array object.
191
+ ///
192
+ /// The builder is reset except for DictionaryBuilder.
193
+ ///
194
+ /// \param[out] out the finalized Array object
195
+ /// \return Status
196
+ Status Finish(std::shared_ptr<Array>* out);
197
+
198
+ /// \brief Return result of builder as an Array object.
199
+ ///
200
+ /// The builder is reset except for DictionaryBuilder.
201
+ ///
202
+ /// \return The finalized Array object
203
+ Result<std::shared_ptr<Array>> Finish();
204
+
205
+ /// \brief Return the type of the built Array
206
+ virtual std::shared_ptr<DataType> type() const = 0;
207
+
208
+ protected:
209
+ /// Append to null bitmap
210
+ Status AppendToBitmap(bool is_valid);
211
+
212
+ /// Vector append. Treat each zero byte as a null. If valid_bytes is null
213
+ /// assume all of length bits are valid.
214
+ Status AppendToBitmap(const uint8_t* valid_bytes, int64_t length);
215
+
216
+ /// Uniform append. Append N times the same validity bit.
217
+ Status AppendToBitmap(int64_t num_bits, bool value);
218
+
219
+ /// Set the next length bits to not null (i.e. valid).
220
+ Status SetNotNull(int64_t length);
221
+
222
+ // Unsafe operations (don't check capacity/don't resize)
223
+
224
+ void UnsafeAppendNull() { UnsafeAppendToBitmap(false); }
225
+
226
+ // Append to null bitmap, update the length
227
+ void UnsafeAppendToBitmap(bool is_valid) {
228
+ null_bitmap_builder_.UnsafeAppend(is_valid);
229
+ ++length_;
230
+ if (!is_valid) ++null_count_;
231
+ }
232
+
233
+ // Vector append. Treat each zero byte as a nullzero. If valid_bytes is null
234
+ // assume all of length bits are valid.
235
+ void UnsafeAppendToBitmap(const uint8_t* valid_bytes, int64_t length) {
236
+ if (valid_bytes == NULLPTR) {
237
+ return UnsafeSetNotNull(length);
238
+ }
239
+ null_bitmap_builder_.UnsafeAppend(valid_bytes, length);
240
+ length_ += length;
241
+ null_count_ = null_bitmap_builder_.false_count();
242
+ }
243
+
244
+ // Vector append. Copy from a given bitmap. If bitmap is null assume
245
+ // all of length bits are valid.
246
+ void UnsafeAppendToBitmap(const uint8_t* bitmap, int64_t offset, int64_t length) {
247
+ if (bitmap == NULLPTR) {
248
+ return UnsafeSetNotNull(length);
249
+ }
250
+ null_bitmap_builder_.UnsafeAppend(bitmap, offset, length);
251
+ length_ += length;
252
+ null_count_ = null_bitmap_builder_.false_count();
253
+ }
254
+
255
+ // Append the same validity value a given number of times.
256
+ void UnsafeAppendToBitmap(const int64_t num_bits, bool value) {
257
+ if (value) {
258
+ UnsafeSetNotNull(num_bits);
259
+ } else {
260
+ UnsafeSetNull(num_bits);
261
+ }
262
+ }
263
+
264
+ void UnsafeAppendToBitmap(const std::vector<bool>& is_valid);
265
+
266
+ // Set the next validity bits to not null (i.e. valid).
267
+ void UnsafeSetNotNull(int64_t length);
268
+
269
+ // Set the next validity bits to null (i.e. invalid).
270
+ void UnsafeSetNull(int64_t length);
271
+
272
+ static Status TrimBuffer(const int64_t bytes_filled, ResizableBuffer* buffer);
273
+
274
+ /// \brief Finish to an array of the specified ArrayType
275
+ template <typename ArrayType>
276
+ Status FinishTyped(std::shared_ptr<ArrayType>* out) {
277
+ std::shared_ptr<Array> out_untyped;
278
+ ARROW_RETURN_NOT_OK(Finish(&out_untyped));
279
+ *out = std::static_pointer_cast<ArrayType>(std::move(out_untyped));
280
+ return Status::OK();
281
+ }
282
+
283
+ // Check the requested capacity for validity
284
+ Status CheckCapacity(int64_t new_capacity) {
285
+ if (ARROW_PREDICT_FALSE(new_capacity < 0)) {
286
+ return Status::Invalid(
287
+ "Resize capacity must be positive (requested: ", new_capacity, ")");
288
+ }
289
+
290
+ if (ARROW_PREDICT_FALSE(new_capacity < length_)) {
291
+ return Status::Invalid("Resize cannot downsize (requested: ", new_capacity,
292
+ ", current length: ", length_, ")");
293
+ }
294
+
295
+ return Status::OK();
296
+ }
297
+
298
+ // Check for array type
299
+ Status CheckArrayType(const std::shared_ptr<DataType>& expected_type,
300
+ const Array& array, const char* message);
301
+ Status CheckArrayType(Type::type expected_type, const Array& array,
302
+ const char* message);
303
+
304
+ MemoryPool* pool_;
305
+ int64_t alignment_;
306
+
307
+ TypedBufferBuilder<bool> null_bitmap_builder_;
308
+ int64_t null_count_ = 0;
309
+
310
+ // Array length, so far. Also, the index of the next element to be added
311
+ int64_t length_ = 0;
312
+ int64_t capacity_ = 0;
313
+
314
+ // Child value array builders. These are owned by this class
315
+ std::vector<std::shared_ptr<ArrayBuilder>> children_;
316
+
317
+ private:
318
+ ARROW_DISALLOW_COPY_AND_ASSIGN(ArrayBuilder);
319
+ };
320
+
321
+ /// \brief Construct an empty ArrayBuilder corresponding to the data
322
+ /// type
323
+ /// \param[in] pool the MemoryPool to use for allocations
324
+ /// \param[in] type the data type to create the builder for
325
+ /// \param[out] out the created ArrayBuilder
326
+ ARROW_EXPORT
327
+ Status MakeBuilder(MemoryPool* pool, const std::shared_ptr<DataType>& type,
328
+ std::unique_ptr<ArrayBuilder>* out);
329
+
330
+ inline Result<std::unique_ptr<ArrayBuilder>> MakeBuilder(
331
+ const std::shared_ptr<DataType>& type, MemoryPool* pool = default_memory_pool()) {
332
+ std::unique_ptr<ArrayBuilder> out;
333
+ ARROW_RETURN_NOT_OK(MakeBuilder(pool, type, &out));
334
+ return std::move(out);
335
+ }
336
+
337
+ /// \brief Construct an empty ArrayBuilder corresponding to the data
338
+ /// type, where any top-level or nested dictionary builders return the
339
+ /// exact index type specified by the type.
340
+ ARROW_EXPORT
341
+ Status MakeBuilderExactIndex(MemoryPool* pool, const std::shared_ptr<DataType>& type,
342
+ std::unique_ptr<ArrayBuilder>* out);
343
+
344
+ inline Result<std::unique_ptr<ArrayBuilder>> MakeBuilderExactIndex(
345
+ const std::shared_ptr<DataType>& type, MemoryPool* pool = default_memory_pool()) {
346
+ std::unique_ptr<ArrayBuilder> out;
347
+ ARROW_RETURN_NOT_OK(MakeBuilderExactIndex(pool, type, &out));
348
+ return std::move(out);
349
+ }
350
+
351
+ /// \brief Construct an empty DictionaryBuilder initialized optionally
352
+ /// with a preexisting dictionary
353
+ /// \param[in] pool the MemoryPool to use for allocations
354
+ /// \param[in] type the dictionary type to create the builder for
355
+ /// \param[in] dictionary the initial dictionary, if any. May be nullptr
356
+ /// \param[out] out the created ArrayBuilder
357
+ ARROW_EXPORT
358
+ Status MakeDictionaryBuilder(MemoryPool* pool, const std::shared_ptr<DataType>& type,
359
+ const std::shared_ptr<Array>& dictionary,
360
+ std::unique_ptr<ArrayBuilder>* out);
361
+
362
+ inline Result<std::unique_ptr<ArrayBuilder>> MakeDictionaryBuilder(
363
+ const std::shared_ptr<DataType>& type, const std::shared_ptr<Array>& dictionary,
364
+ MemoryPool* pool = default_memory_pool()) {
365
+ std::unique_ptr<ArrayBuilder> out;
366
+ ARROW_RETURN_NOT_OK(MakeDictionaryBuilder(pool, type, dictionary, &out));
367
+ return std::move(out);
368
+ }
369
+
370
+ } // namespace arrow
venv/lib/python3.10/site-packages/pyarrow/include/arrow/array/builder_dict.h ADDED
@@ -0,0 +1,737 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #pragma once
19
+
20
+ #include <algorithm>
21
+ #include <cstdint>
22
+ #include <memory>
23
+ #include <type_traits>
24
+
25
+ #include "arrow/array/array_base.h"
26
+ #include "arrow/array/array_binary.h"
27
+ #include "arrow/array/builder_adaptive.h" // IWYU pragma: export
28
+ #include "arrow/array/builder_base.h" // IWYU pragma: export
29
+ #include "arrow/array/builder_primitive.h" // IWYU pragma: export
30
+ #include "arrow/array/data.h"
31
+ #include "arrow/array/util.h"
32
+ #include "arrow/scalar.h"
33
+ #include "arrow/status.h"
34
+ #include "arrow/type.h"
35
+ #include "arrow/type_traits.h"
36
+ #include "arrow/util/bit_block_counter.h"
37
+ #include "arrow/util/checked_cast.h"
38
+ #include "arrow/util/decimal.h"
39
+ #include "arrow/util/macros.h"
40
+ #include "arrow/util/visibility.h"
41
+
42
+ namespace arrow {
43
+
44
+ // ----------------------------------------------------------------------
45
+ // Dictionary builder
46
+
47
+ namespace internal {
48
+
49
+ template <typename T, typename Enable = void>
50
+ struct DictionaryValue {
51
+ using type = typename T::c_type;
52
+ using PhysicalType = T;
53
+ };
54
+
55
+ template <typename T>
56
+ struct DictionaryValue<T, enable_if_base_binary<T>> {
57
+ using type = std::string_view;
58
+ using PhysicalType =
59
+ typename std::conditional<std::is_same<typename T::offset_type, int32_t>::value,
60
+ BinaryType, LargeBinaryType>::type;
61
+ };
62
+
63
+ template <typename T>
64
+ struct DictionaryValue<T, enable_if_binary_view_like<T>> {
65
+ using type = std::string_view;
66
+ using PhysicalType = BinaryViewType;
67
+ };
68
+
69
+ template <typename T>
70
+ struct DictionaryValue<T, enable_if_fixed_size_binary<T>> {
71
+ using type = std::string_view;
72
+ using PhysicalType = BinaryType;
73
+ };
74
+
75
+ class ARROW_EXPORT DictionaryMemoTable {
76
+ public:
77
+ DictionaryMemoTable(MemoryPool* pool, const std::shared_ptr<DataType>& type);
78
+ DictionaryMemoTable(MemoryPool* pool, const std::shared_ptr<Array>& dictionary);
79
+ ~DictionaryMemoTable();
80
+
81
+ Status GetArrayData(int64_t start_offset, std::shared_ptr<ArrayData>* out);
82
+
83
+ /// \brief Insert new memo values
84
+ Status InsertValues(const Array& values);
85
+
86
+ int32_t size() const;
87
+
88
+ template <typename T>
89
+ Status GetOrInsert(typename DictionaryValue<T>::type value, int32_t* out) {
90
+ // We want to keep the DictionaryMemoTable implementation private, also we can't
91
+ // use extern template classes because of compiler issues (MinGW?). Instead,
92
+ // we expose explicit function overrides for each supported physical type.
93
+ const typename DictionaryValue<T>::PhysicalType* physical_type = NULLPTR;
94
+ return GetOrInsert(physical_type, value, out);
95
+ }
96
+
97
+ private:
98
+ Status GetOrInsert(const BooleanType*, bool value, int32_t* out);
99
+ Status GetOrInsert(const Int8Type*, int8_t value, int32_t* out);
100
+ Status GetOrInsert(const Int16Type*, int16_t value, int32_t* out);
101
+ Status GetOrInsert(const Int32Type*, int32_t value, int32_t* out);
102
+ Status GetOrInsert(const Int64Type*, int64_t value, int32_t* out);
103
+ Status GetOrInsert(const UInt8Type*, uint8_t value, int32_t* out);
104
+ Status GetOrInsert(const UInt16Type*, uint16_t value, int32_t* out);
105
+ Status GetOrInsert(const UInt32Type*, uint32_t value, int32_t* out);
106
+ Status GetOrInsert(const UInt64Type*, uint64_t value, int32_t* out);
107
+ Status GetOrInsert(const DurationType*, int64_t value, int32_t* out);
108
+ Status GetOrInsert(const TimestampType*, int64_t value, int32_t* out);
109
+ Status GetOrInsert(const Date32Type*, int32_t value, int32_t* out);
110
+ Status GetOrInsert(const Date64Type*, int64_t value, int32_t* out);
111
+ Status GetOrInsert(const Time32Type*, int32_t value, int32_t* out);
112
+ Status GetOrInsert(const Time64Type*, int64_t value, int32_t* out);
113
+ Status GetOrInsert(const MonthDayNanoIntervalType*,
114
+ MonthDayNanoIntervalType::MonthDayNanos value, int32_t* out);
115
+ Status GetOrInsert(const DayTimeIntervalType*,
116
+ DayTimeIntervalType::DayMilliseconds value, int32_t* out);
117
+ Status GetOrInsert(const MonthIntervalType*, int32_t value, int32_t* out);
118
+ Status GetOrInsert(const FloatType*, float value, int32_t* out);
119
+ Status GetOrInsert(const DoubleType*, double value, int32_t* out);
120
+
121
+ Status GetOrInsert(const BinaryType*, std::string_view value, int32_t* out);
122
+ Status GetOrInsert(const LargeBinaryType*, std::string_view value, int32_t* out);
123
+ Status GetOrInsert(const BinaryViewType*, std::string_view value, int32_t* out);
124
+
125
+ class DictionaryMemoTableImpl;
126
+ std::unique_ptr<DictionaryMemoTableImpl> impl_;
127
+ };
128
+
129
+ } // namespace internal
130
+
131
+ /// \addtogroup dictionary-builders
132
+ ///
133
+ /// @{
134
+
135
+ namespace internal {
136
+
137
+ /// \brief Array builder for created encoded DictionaryArray from
138
+ /// dense array
139
+ ///
140
+ /// Unlike other builders, dictionary builder does not completely
141
+ /// reset the state on Finish calls.
142
+ template <typename BuilderType, typename T>
143
+ class DictionaryBuilderBase : public ArrayBuilder {
144
+ public:
145
+ using TypeClass = DictionaryType;
146
+ using Value = typename DictionaryValue<T>::type;
147
+
148
+ // WARNING: the type given below is the value type, not the DictionaryType.
149
+ // The DictionaryType is instantiated on the Finish() call.
150
+ template <typename B = BuilderType, typename T1 = T>
151
+ DictionaryBuilderBase(uint8_t start_int_size,
152
+ enable_if_t<std::is_base_of<AdaptiveIntBuilderBase, B>::value &&
153
+ !is_fixed_size_binary_type<T1>::value,
154
+ const std::shared_ptr<DataType>&>
155
+ value_type,
156
+ MemoryPool* pool = default_memory_pool(),
157
+ int64_t alignment = kDefaultBufferAlignment)
158
+ : ArrayBuilder(pool, alignment),
159
+ memo_table_(new internal::DictionaryMemoTable(pool, value_type)),
160
+ delta_offset_(0),
161
+ byte_width_(-1),
162
+ indices_builder_(start_int_size, pool, alignment),
163
+ value_type_(value_type) {}
164
+
165
+ template <typename T1 = T>
166
+ explicit DictionaryBuilderBase(
167
+ enable_if_t<!is_fixed_size_binary_type<T1>::value, const std::shared_ptr<DataType>&>
168
+ value_type,
169
+ MemoryPool* pool = default_memory_pool(),
170
+ int64_t alignment = kDefaultBufferAlignment)
171
+ : ArrayBuilder(pool, alignment),
172
+ memo_table_(new internal::DictionaryMemoTable(pool, value_type)),
173
+ delta_offset_(0),
174
+ byte_width_(-1),
175
+ indices_builder_(pool, alignment),
176
+ value_type_(value_type) {}
177
+
178
+ template <typename T1 = T>
179
+ explicit DictionaryBuilderBase(
180
+ const std::shared_ptr<DataType>& index_type,
181
+ enable_if_t<!is_fixed_size_binary_type<T1>::value, const std::shared_ptr<DataType>&>
182
+ value_type,
183
+ MemoryPool* pool = default_memory_pool(),
184
+ int64_t alignment = kDefaultBufferAlignment)
185
+ : ArrayBuilder(pool, alignment),
186
+ memo_table_(new internal::DictionaryMemoTable(pool, value_type)),
187
+ delta_offset_(0),
188
+ byte_width_(-1),
189
+ indices_builder_(index_type, pool, alignment),
190
+ value_type_(value_type) {}
191
+
192
+ template <typename B = BuilderType, typename T1 = T>
193
+ DictionaryBuilderBase(uint8_t start_int_size,
194
+ enable_if_t<std::is_base_of<AdaptiveIntBuilderBase, B>::value &&
195
+ is_fixed_size_binary_type<T1>::value,
196
+ const std::shared_ptr<DataType>&>
197
+ value_type,
198
+ MemoryPool* pool = default_memory_pool(),
199
+ int64_t alignment = kDefaultBufferAlignment)
200
+ : ArrayBuilder(pool, alignment),
201
+ memo_table_(new internal::DictionaryMemoTable(pool, value_type)),
202
+ delta_offset_(0),
203
+ byte_width_(static_cast<const T1&>(*value_type).byte_width()),
204
+ indices_builder_(start_int_size, pool, alignment),
205
+ value_type_(value_type) {}
206
+
207
+ template <typename T1 = T>
208
+ explicit DictionaryBuilderBase(
209
+ enable_if_fixed_size_binary<T1, const std::shared_ptr<DataType>&> value_type,
210
+ MemoryPool* pool = default_memory_pool(),
211
+ int64_t alignment = kDefaultBufferAlignment)
212
+ : ArrayBuilder(pool, alignment),
213
+ memo_table_(new internal::DictionaryMemoTable(pool, value_type)),
214
+ delta_offset_(0),
215
+ byte_width_(static_cast<const T1&>(*value_type).byte_width()),
216
+ indices_builder_(pool, alignment),
217
+ value_type_(value_type) {}
218
+
219
+ template <typename T1 = T>
220
+ explicit DictionaryBuilderBase(
221
+ const std::shared_ptr<DataType>& index_type,
222
+ enable_if_fixed_size_binary<T1, const std::shared_ptr<DataType>&> value_type,
223
+ MemoryPool* pool = default_memory_pool(),
224
+ int64_t alignment = kDefaultBufferAlignment)
225
+ : ArrayBuilder(pool, alignment),
226
+ memo_table_(new internal::DictionaryMemoTable(pool, value_type)),
227
+ delta_offset_(0),
228
+ byte_width_(static_cast<const T1&>(*value_type).byte_width()),
229
+ indices_builder_(index_type, pool, alignment),
230
+ value_type_(value_type) {}
231
+
232
+ template <typename T1 = T>
233
+ explicit DictionaryBuilderBase(
234
+ enable_if_parameter_free<T1, MemoryPool*> pool = default_memory_pool())
235
+ : DictionaryBuilderBase<BuilderType, T1>(TypeTraits<T1>::type_singleton(), pool) {}
236
+
237
+ // This constructor doesn't check for errors. Use InsertMemoValues instead.
238
+ explicit DictionaryBuilderBase(const std::shared_ptr<Array>& dictionary,
239
+ MemoryPool* pool = default_memory_pool(),
240
+ int64_t alignment = kDefaultBufferAlignment)
241
+ : ArrayBuilder(pool, alignment),
242
+ memo_table_(new internal::DictionaryMemoTable(pool, dictionary)),
243
+ delta_offset_(0),
244
+ byte_width_(-1),
245
+ indices_builder_(pool, alignment),
246
+ value_type_(dictionary->type()) {}
247
+
248
+ ~DictionaryBuilderBase() override = default;
249
+
250
+ /// \brief The current number of entries in the dictionary
251
+ int64_t dictionary_length() const { return memo_table_->size(); }
252
+
253
+ /// \brief The value byte width (for FixedSizeBinaryType)
254
+ template <typename T1 = T>
255
+ enable_if_fixed_size_binary<T1, int32_t> byte_width() const {
256
+ return byte_width_;
257
+ }
258
+
259
+ /// \brief Append a scalar value
260
+ Status Append(Value value) {
261
+ ARROW_RETURN_NOT_OK(Reserve(1));
262
+
263
+ int32_t memo_index;
264
+ ARROW_RETURN_NOT_OK(memo_table_->GetOrInsert<T>(value, &memo_index));
265
+ ARROW_RETURN_NOT_OK(indices_builder_.Append(memo_index));
266
+ length_ += 1;
267
+
268
+ return Status::OK();
269
+ }
270
+
271
+ /// \brief Append a fixed-width string (only for FixedSizeBinaryType)
272
+ template <typename T1 = T>
273
+ enable_if_fixed_size_binary<T1, Status> Append(const uint8_t* value) {
274
+ return Append(std::string_view(reinterpret_cast<const char*>(value), byte_width_));
275
+ }
276
+
277
+ /// \brief Append a fixed-width string (only for FixedSizeBinaryType)
278
+ template <typename T1 = T>
279
+ enable_if_fixed_size_binary<T1, Status> Append(const char* value) {
280
+ return Append(std::string_view(value, byte_width_));
281
+ }
282
+
283
+ /// \brief Append a string (only for binary types)
284
+ template <typename T1 = T>
285
+ enable_if_binary_like<T1, Status> Append(const uint8_t* value, int32_t length) {
286
+ return Append(reinterpret_cast<const char*>(value), length);
287
+ }
288
+
289
+ /// \brief Append a string (only for binary types)
290
+ template <typename T1 = T>
291
+ enable_if_binary_like<T1, Status> Append(const char* value, int32_t length) {
292
+ return Append(std::string_view(value, length));
293
+ }
294
+
295
+ /// \brief Append a string (only for string types)
296
+ template <typename T1 = T>
297
+ enable_if_string_like<T1, Status> Append(const char* value, int32_t length) {
298
+ return Append(std::string_view(value, length));
299
+ }
300
+
301
+ /// \brief Append a decimal (only for Decimal128Type)
302
+ template <typename T1 = T>
303
+ enable_if_decimal128<T1, Status> Append(const Decimal128& value) {
304
+ uint8_t data[16];
305
+ value.ToBytes(data);
306
+ return Append(data, 16);
307
+ }
308
+
309
+ /// \brief Append a decimal (only for Decimal128Type)
310
+ template <typename T1 = T>
311
+ enable_if_decimal256<T1, Status> Append(const Decimal256& value) {
312
+ uint8_t data[32];
313
+ value.ToBytes(data);
314
+ return Append(data, 32);
315
+ }
316
+
317
+ /// \brief Append a scalar null value
318
+ Status AppendNull() final {
319
+ length_ += 1;
320
+ null_count_ += 1;
321
+
322
+ return indices_builder_.AppendNull();
323
+ }
324
+
325
+ Status AppendNulls(int64_t length) final {
326
+ length_ += length;
327
+ null_count_ += length;
328
+
329
+ return indices_builder_.AppendNulls(length);
330
+ }
331
+
332
+ Status AppendEmptyValue() final {
333
+ length_ += 1;
334
+
335
+ return indices_builder_.AppendEmptyValue();
336
+ }
337
+
338
+ Status AppendEmptyValues(int64_t length) final {
339
+ length_ += length;
340
+
341
+ return indices_builder_.AppendEmptyValues(length);
342
+ }
343
+
344
+ Status AppendScalar(const Scalar& scalar, int64_t n_repeats) override {
345
+ if (!scalar.is_valid) return AppendNulls(n_repeats);
346
+
347
+ const auto& dict_ty = internal::checked_cast<const DictionaryType&>(*scalar.type);
348
+ const DictionaryScalar& dict_scalar =
349
+ internal::checked_cast<const DictionaryScalar&>(scalar);
350
+ const auto& dict = internal::checked_cast<const typename TypeTraits<T>::ArrayType&>(
351
+ *dict_scalar.value.dictionary);
352
+ ARROW_RETURN_NOT_OK(Reserve(n_repeats));
353
+ switch (dict_ty.index_type()->id()) {
354
+ case Type::UINT8:
355
+ return AppendScalarImpl<UInt8Type>(dict, *dict_scalar.value.index, n_repeats);
356
+ case Type::INT8:
357
+ return AppendScalarImpl<Int8Type>(dict, *dict_scalar.value.index, n_repeats);
358
+ case Type::UINT16:
359
+ return AppendScalarImpl<UInt16Type>(dict, *dict_scalar.value.index, n_repeats);
360
+ case Type::INT16:
361
+ return AppendScalarImpl<Int16Type>(dict, *dict_scalar.value.index, n_repeats);
362
+ case Type::UINT32:
363
+ return AppendScalarImpl<UInt32Type>(dict, *dict_scalar.value.index, n_repeats);
364
+ case Type::INT32:
365
+ return AppendScalarImpl<Int32Type>(dict, *dict_scalar.value.index, n_repeats);
366
+ case Type::UINT64:
367
+ return AppendScalarImpl<UInt64Type>(dict, *dict_scalar.value.index, n_repeats);
368
+ case Type::INT64:
369
+ return AppendScalarImpl<Int64Type>(dict, *dict_scalar.value.index, n_repeats);
370
+ default:
371
+ return Status::TypeError("Invalid index type: ", dict_ty);
372
+ }
373
+ return Status::OK();
374
+ }
375
+
376
+ Status AppendScalars(const ScalarVector& scalars) override {
377
+ for (const auto& scalar : scalars) {
378
+ ARROW_RETURN_NOT_OK(AppendScalar(*scalar, /*n_repeats=*/1));
379
+ }
380
+ return Status::OK();
381
+ }
382
+
383
+ Status AppendArraySlice(const ArraySpan& array, int64_t offset, int64_t length) final {
384
+ // Visit the indices and insert the unpacked values.
385
+ const auto& dict_ty = internal::checked_cast<const DictionaryType&>(*array.type);
386
+ // See if possible to avoid using ToArrayData here
387
+ const typename TypeTraits<T>::ArrayType dict(array.dictionary().ToArrayData());
388
+ ARROW_RETURN_NOT_OK(Reserve(length));
389
+ switch (dict_ty.index_type()->id()) {
390
+ case Type::UINT8:
391
+ return AppendArraySliceImpl<uint8_t>(dict, array, offset, length);
392
+ case Type::INT8:
393
+ return AppendArraySliceImpl<int8_t>(dict, array, offset, length);
394
+ case Type::UINT16:
395
+ return AppendArraySliceImpl<uint16_t>(dict, array, offset, length);
396
+ case Type::INT16:
397
+ return AppendArraySliceImpl<int16_t>(dict, array, offset, length);
398
+ case Type::UINT32:
399
+ return AppendArraySliceImpl<uint32_t>(dict, array, offset, length);
400
+ case Type::INT32:
401
+ return AppendArraySliceImpl<int32_t>(dict, array, offset, length);
402
+ case Type::UINT64:
403
+ return AppendArraySliceImpl<uint64_t>(dict, array, offset, length);
404
+ case Type::INT64:
405
+ return AppendArraySliceImpl<int64_t>(dict, array, offset, length);
406
+ default:
407
+ return Status::TypeError("Invalid index type: ", dict_ty);
408
+ }
409
+ return Status::OK();
410
+ }
411
+
412
+ /// \brief Insert values into the dictionary's memo, but do not append any
413
+ /// indices. Can be used to initialize a new builder with known dictionary
414
+ /// values
415
+ /// \param[in] values dictionary values to add to memo. Type must match
416
+ /// builder type
417
+ Status InsertMemoValues(const Array& values) {
418
+ return memo_table_->InsertValues(values);
419
+ }
420
+
421
+ /// \brief Append a whole dense array to the builder
422
+ template <typename T1 = T>
423
+ enable_if_t<!is_fixed_size_binary_type<T1>::value, Status> AppendArray(
424
+ const Array& array) {
425
+ using ArrayType = typename TypeTraits<T>::ArrayType;
426
+
427
+ #ifndef NDEBUG
428
+ ARROW_RETURN_NOT_OK(ArrayBuilder::CheckArrayType(
429
+ value_type_, array, "Wrong value type of array to be appended"));
430
+ #endif
431
+
432
+ const auto& concrete_array = static_cast<const ArrayType&>(array);
433
+ for (int64_t i = 0; i < array.length(); i++) {
434
+ if (array.IsNull(i)) {
435
+ ARROW_RETURN_NOT_OK(AppendNull());
436
+ } else {
437
+ ARROW_RETURN_NOT_OK(Append(concrete_array.GetView(i)));
438
+ }
439
+ }
440
+ return Status::OK();
441
+ }
442
+
443
+ template <typename T1 = T>
444
+ enable_if_fixed_size_binary<T1, Status> AppendArray(const Array& array) {
445
+ #ifndef NDEBUG
446
+ ARROW_RETURN_NOT_OK(ArrayBuilder::CheckArrayType(
447
+ value_type_, array, "Wrong value type of array to be appended"));
448
+ #endif
449
+
450
+ const auto& concrete_array = static_cast<const FixedSizeBinaryArray&>(array);
451
+ for (int64_t i = 0; i < array.length(); i++) {
452
+ if (array.IsNull(i)) {
453
+ ARROW_RETURN_NOT_OK(AppendNull());
454
+ } else {
455
+ ARROW_RETURN_NOT_OK(Append(concrete_array.GetValue(i)));
456
+ }
457
+ }
458
+ return Status::OK();
459
+ }
460
+
461
+ void Reset() override {
462
+ // Perform a partial reset. Call ResetFull to also reset the accumulated
463
+ // dictionary values
464
+ ArrayBuilder::Reset();
465
+ indices_builder_.Reset();
466
+ }
467
+
468
+ /// \brief Reset and also clear accumulated dictionary values in memo table
469
+ void ResetFull() {
470
+ Reset();
471
+ memo_table_.reset(new internal::DictionaryMemoTable(pool_, value_type_));
472
+ }
473
+
474
+ Status Resize(int64_t capacity) override {
475
+ ARROW_RETURN_NOT_OK(CheckCapacity(capacity));
476
+ capacity = std::max(capacity, kMinBuilderCapacity);
477
+ ARROW_RETURN_NOT_OK(indices_builder_.Resize(capacity));
478
+ capacity_ = indices_builder_.capacity();
479
+ return Status::OK();
480
+ }
481
+
482
+ /// \brief Return dictionary indices and a delta dictionary since the last
483
+ /// time that Finish or FinishDelta were called, and reset state of builder
484
+ /// (except the memo table)
485
+ Status FinishDelta(std::shared_ptr<Array>* out_indices,
486
+ std::shared_ptr<Array>* out_delta) {
487
+ std::shared_ptr<ArrayData> indices_data;
488
+ std::shared_ptr<ArrayData> delta_data;
489
+ ARROW_RETURN_NOT_OK(FinishWithDictOffset(delta_offset_, &indices_data, &delta_data));
490
+ *out_indices = MakeArray(indices_data);
491
+ *out_delta = MakeArray(delta_data);
492
+ return Status::OK();
493
+ }
494
+
495
+ /// \cond FALSE
496
+ using ArrayBuilder::Finish;
497
+ /// \endcond
498
+
499
+ Status Finish(std::shared_ptr<DictionaryArray>* out) { return FinishTyped(out); }
500
+
501
+ std::shared_ptr<DataType> type() const override {
502
+ return ::arrow::dictionary(indices_builder_.type(), value_type_);
503
+ }
504
+
505
+ protected:
506
+ template <typename c_type>
507
+ Status AppendArraySliceImpl(const typename TypeTraits<T>::ArrayType& dict,
508
+ const ArraySpan& array, int64_t offset, int64_t length) {
509
+ const c_type* values = array.GetValues<c_type>(1) + offset;
510
+ return VisitBitBlocks(
511
+ array.buffers[0].data, array.offset + offset, length,
512
+ [&](const int64_t position) {
513
+ const int64_t index = static_cast<int64_t>(values[position]);
514
+ if (dict.IsValid(index)) {
515
+ return Append(dict.GetView(index));
516
+ }
517
+ return AppendNull();
518
+ },
519
+ [&]() { return AppendNull(); });
520
+ }
521
+
522
+ template <typename IndexType>
523
+ Status AppendScalarImpl(const typename TypeTraits<T>::ArrayType& dict,
524
+ const Scalar& index_scalar, int64_t n_repeats) {
525
+ using ScalarType = typename TypeTraits<IndexType>::ScalarType;
526
+ const auto index = internal::checked_cast<const ScalarType&>(index_scalar).value;
527
+ if (index_scalar.is_valid && dict.IsValid(index)) {
528
+ const auto& value = dict.GetView(index);
529
+ for (int64_t i = 0; i < n_repeats; i++) {
530
+ ARROW_RETURN_NOT_OK(Append(value));
531
+ }
532
+ return Status::OK();
533
+ }
534
+ return AppendNulls(n_repeats);
535
+ }
536
+
537
+ Status FinishInternal(std::shared_ptr<ArrayData>* out) override {
538
+ std::shared_ptr<ArrayData> dictionary;
539
+ ARROW_RETURN_NOT_OK(FinishWithDictOffset(/*offset=*/0, out, &dictionary));
540
+
541
+ // Set type of array data to the right dictionary type
542
+ (*out)->type = type();
543
+ (*out)->dictionary = dictionary;
544
+ return Status::OK();
545
+ }
546
+
547
+ Status FinishWithDictOffset(int64_t dict_offset,
548
+ std::shared_ptr<ArrayData>* out_indices,
549
+ std::shared_ptr<ArrayData>* out_dictionary) {
550
+ // Finalize indices array
551
+ ARROW_RETURN_NOT_OK(indices_builder_.FinishInternal(out_indices));
552
+
553
+ // Generate dictionary array from hash table contents
554
+ ARROW_RETURN_NOT_OK(memo_table_->GetArrayData(dict_offset, out_dictionary));
555
+ delta_offset_ = memo_table_->size();
556
+
557
+ // Update internals for further uses of this DictionaryBuilder
558
+ ArrayBuilder::Reset();
559
+ return Status::OK();
560
+ }
561
+
562
+ std::unique_ptr<DictionaryMemoTable> memo_table_;
563
+
564
+ // The size of the dictionary memo at last invocation of Finish, to use in
565
+ // FinishDelta for computing dictionary deltas
566
+ int32_t delta_offset_;
567
+
568
+ // Only used for FixedSizeBinaryType
569
+ int32_t byte_width_;
570
+
571
+ BuilderType indices_builder_;
572
+ std::shared_ptr<DataType> value_type_;
573
+ };
574
+
575
+ template <typename BuilderType>
576
+ class DictionaryBuilderBase<BuilderType, NullType> : public ArrayBuilder {
577
+ public:
578
+ template <typename B = BuilderType>
579
+ DictionaryBuilderBase(
580
+ enable_if_t<std::is_base_of<AdaptiveIntBuilderBase, B>::value, uint8_t>
581
+ start_int_size,
582
+ const std::shared_ptr<DataType>& value_type,
583
+ MemoryPool* pool = default_memory_pool())
584
+ : ArrayBuilder(pool), indices_builder_(start_int_size, pool) {}
585
+
586
+ explicit DictionaryBuilderBase(const std::shared_ptr<DataType>& value_type,
587
+ MemoryPool* pool = default_memory_pool())
588
+ : ArrayBuilder(pool), indices_builder_(pool) {}
589
+
590
+ explicit DictionaryBuilderBase(const std::shared_ptr<DataType>& index_type,
591
+ const std::shared_ptr<DataType>& value_type,
592
+ MemoryPool* pool = default_memory_pool())
593
+ : ArrayBuilder(pool), indices_builder_(index_type, pool) {}
594
+
595
+ template <typename B = BuilderType>
596
+ explicit DictionaryBuilderBase(
597
+ enable_if_t<std::is_base_of<AdaptiveIntBuilderBase, B>::value, uint8_t>
598
+ start_int_size,
599
+ MemoryPool* pool = default_memory_pool())
600
+ : ArrayBuilder(pool), indices_builder_(start_int_size, pool) {}
601
+
602
+ explicit DictionaryBuilderBase(MemoryPool* pool = default_memory_pool())
603
+ : ArrayBuilder(pool), indices_builder_(pool) {}
604
+
605
+ explicit DictionaryBuilderBase(const std::shared_ptr<Array>& dictionary,
606
+ MemoryPool* pool = default_memory_pool())
607
+ : ArrayBuilder(pool), indices_builder_(pool) {}
608
+
609
+ /// \brief Append a scalar null value
610
+ Status AppendNull() final {
611
+ length_ += 1;
612
+ null_count_ += 1;
613
+
614
+ return indices_builder_.AppendNull();
615
+ }
616
+
617
+ Status AppendNulls(int64_t length) final {
618
+ length_ += length;
619
+ null_count_ += length;
620
+
621
+ return indices_builder_.AppendNulls(length);
622
+ }
623
+
624
+ Status AppendEmptyValue() final {
625
+ length_ += 1;
626
+
627
+ return indices_builder_.AppendEmptyValue();
628
+ }
629
+
630
+ Status AppendEmptyValues(int64_t length) final {
631
+ length_ += length;
632
+
633
+ return indices_builder_.AppendEmptyValues(length);
634
+ }
635
+
636
+ /// \brief Append a whole dense array to the builder
637
+ Status AppendArray(const Array& array) {
638
+ #ifndef NDEBUG
639
+ ARROW_RETURN_NOT_OK(ArrayBuilder::CheckArrayType(
640
+ Type::NA, array, "Wrong value type of array to be appended"));
641
+ #endif
642
+ for (int64_t i = 0; i < array.length(); i++) {
643
+ ARROW_RETURN_NOT_OK(AppendNull());
644
+ }
645
+ return Status::OK();
646
+ }
647
+
648
+ Status Resize(int64_t capacity) override {
649
+ ARROW_RETURN_NOT_OK(CheckCapacity(capacity));
650
+ capacity = std::max(capacity, kMinBuilderCapacity);
651
+
652
+ ARROW_RETURN_NOT_OK(indices_builder_.Resize(capacity));
653
+ capacity_ = indices_builder_.capacity();
654
+ return Status::OK();
655
+ }
656
+
657
+ Status FinishInternal(std::shared_ptr<ArrayData>* out) override {
658
+ ARROW_RETURN_NOT_OK(indices_builder_.FinishInternal(out));
659
+ (*out)->type = dictionary((*out)->type, null());
660
+ (*out)->dictionary = NullArray(0).data();
661
+ return Status::OK();
662
+ }
663
+
664
+ /// \cond FALSE
665
+ using ArrayBuilder::Finish;
666
+ /// \endcond
667
+
668
+ Status Finish(std::shared_ptr<DictionaryArray>* out) { return FinishTyped(out); }
669
+
670
+ std::shared_ptr<DataType> type() const override {
671
+ return ::arrow::dictionary(indices_builder_.type(), null());
672
+ }
673
+
674
+ protected:
675
+ BuilderType indices_builder_;
676
+ };
677
+
678
+ } // namespace internal
679
+
680
+ /// \brief A DictionaryArray builder that uses AdaptiveIntBuilder to return the
681
+ /// smallest index size that can accommodate the dictionary indices
682
+ template <typename T>
683
+ class DictionaryBuilder : public internal::DictionaryBuilderBase<AdaptiveIntBuilder, T> {
684
+ public:
685
+ using BASE = internal::DictionaryBuilderBase<AdaptiveIntBuilder, T>;
686
+ using BASE::BASE;
687
+
688
+ /// \brief Append dictionary indices directly without modifying memo
689
+ ///
690
+ /// NOTE: Experimental API
691
+ Status AppendIndices(const int64_t* values, int64_t length,
692
+ const uint8_t* valid_bytes = NULLPTR) {
693
+ int64_t null_count_before = this->indices_builder_.null_count();
694
+ ARROW_RETURN_NOT_OK(this->indices_builder_.AppendValues(values, length, valid_bytes));
695
+ this->capacity_ = this->indices_builder_.capacity();
696
+ this->length_ += length;
697
+ this->null_count_ += this->indices_builder_.null_count() - null_count_before;
698
+ return Status::OK();
699
+ }
700
+ };
701
+
702
+ /// \brief A DictionaryArray builder that always returns int32 dictionary
703
+ /// indices so that data cast to dictionary form will have a consistent index
704
+ /// type, e.g. for creating a ChunkedArray
705
+ template <typename T>
706
+ class Dictionary32Builder : public internal::DictionaryBuilderBase<Int32Builder, T> {
707
+ public:
708
+ using BASE = internal::DictionaryBuilderBase<Int32Builder, T>;
709
+ using BASE::BASE;
710
+
711
+ /// \brief Append dictionary indices directly without modifying memo
712
+ ///
713
+ /// NOTE: Experimental API
714
+ Status AppendIndices(const int32_t* values, int64_t length,
715
+ const uint8_t* valid_bytes = NULLPTR) {
716
+ int64_t null_count_before = this->indices_builder_.null_count();
717
+ ARROW_RETURN_NOT_OK(this->indices_builder_.AppendValues(values, length, valid_bytes));
718
+ this->capacity_ = this->indices_builder_.capacity();
719
+ this->length_ += length;
720
+ this->null_count_ += this->indices_builder_.null_count() - null_count_before;
721
+ return Status::OK();
722
+ }
723
+ };
724
+
725
+ // ----------------------------------------------------------------------
726
+ // Binary / Unicode builders
727
+ // (compatibility aliases; those used to be derived classes with additional
728
+ // Append() overloads, but they have been folded into DictionaryBuilderBase)
729
+
730
+ using BinaryDictionaryBuilder = DictionaryBuilder<BinaryType>;
731
+ using StringDictionaryBuilder = DictionaryBuilder<StringType>;
732
+ using BinaryDictionary32Builder = Dictionary32Builder<BinaryType>;
733
+ using StringDictionary32Builder = Dictionary32Builder<StringType>;
734
+
735
+ /// @}
736
+
737
+ } // namespace arrow
venv/lib/python3.10/site-packages/pyarrow/include/arrow/array/builder_nested.h ADDED
@@ -0,0 +1,838 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #pragma once
19
+
20
+ #include <cstdint>
21
+ #include <limits>
22
+ #include <memory>
23
+ #include <utility>
24
+ #include <vector>
25
+
26
+ #include "arrow/array/array_nested.h"
27
+ #include "arrow/array/builder_base.h"
28
+ #include "arrow/array/data.h"
29
+ #include "arrow/buffer.h"
30
+ #include "arrow/buffer_builder.h"
31
+ #include "arrow/status.h"
32
+ #include "arrow/type.h"
33
+ #include "arrow/util/macros.h"
34
+ #include "arrow/util/visibility.h"
35
+
36
+ namespace arrow {
37
+
38
+ /// \addtogroup nested-builders
39
+ ///
40
+ /// @{
41
+
42
+ // ----------------------------------------------------------------------
43
+ // VarLengthListLikeBuilder
44
+
45
+ template <typename TYPE>
46
+ class ARROW_EXPORT VarLengthListLikeBuilder : public ArrayBuilder {
47
+ public:
48
+ using TypeClass = TYPE;
49
+ using offset_type = typename TypeClass::offset_type;
50
+
51
+ /// Use this constructor to incrementally build the value array along with offsets and
52
+ /// null bitmap.
53
+ VarLengthListLikeBuilder(MemoryPool* pool,
54
+ std::shared_ptr<ArrayBuilder> const& value_builder,
55
+ const std::shared_ptr<DataType>& type,
56
+ int64_t alignment = kDefaultBufferAlignment)
57
+ : ArrayBuilder(pool, alignment),
58
+ offsets_builder_(pool, alignment),
59
+ value_builder_(value_builder),
60
+ value_field_(type->field(0)->WithType(NULLPTR)) {}
61
+
62
+ VarLengthListLikeBuilder(MemoryPool* pool,
63
+ std::shared_ptr<ArrayBuilder> const& value_builder,
64
+ int64_t alignment = kDefaultBufferAlignment)
65
+ : VarLengthListLikeBuilder(pool, value_builder,
66
+ std::make_shared<TYPE>(value_builder->type()),
67
+ alignment) {}
68
+
69
+ ~VarLengthListLikeBuilder() override = default;
70
+
71
+ Status Resize(int64_t capacity) override {
72
+ if (ARROW_PREDICT_FALSE(capacity > maximum_elements())) {
73
+ return Status::CapacityError(type_name(),
74
+ " array cannot reserve space for more than ",
75
+ maximum_elements(), " got ", capacity);
76
+ }
77
+ ARROW_RETURN_NOT_OK(CheckCapacity(capacity));
78
+
79
+ // One more than requested for list offsets
80
+ const int64_t offsets_capacity =
81
+ is_list_view(TYPE::type_id) ? capacity : capacity + 1;
82
+ ARROW_RETURN_NOT_OK(offsets_builder_.Resize(offsets_capacity));
83
+ return ArrayBuilder::Resize(capacity);
84
+ }
85
+
86
+ void Reset() override {
87
+ ArrayBuilder::Reset();
88
+ offsets_builder_.Reset();
89
+ value_builder_->Reset();
90
+ }
91
+
92
+ /// \brief Start a new variable-length list slot
93
+ ///
94
+ /// This function should be called before appending elements to the
95
+ /// value builder. Elements appended to the value builder before this function
96
+ /// is called for the first time, will not be members of any list value.
97
+ ///
98
+ /// After this function is called, list_length elements SHOULD be appended to
99
+ /// the values builder. If this contract is violated, the behavior is defined by
100
+ /// the concrete builder implementation and SHOULD NOT be relied upon unless
101
+ /// the caller is specifically building a [Large]List or [Large]ListView array.
102
+ ///
103
+ /// For [Large]List arrays, the list slot length will be the number of elements
104
+ /// appended to the values builder before the next call to Append* or Finish. For
105
+ /// [Large]ListView arrays, the list slot length will be exactly list_length, but if
106
+ /// Append* is called before at least list_length elements are appended to the values
107
+ /// builder, the current list slot will share elements with the next list
108
+ /// slots or an invalid [Large]ListView array will be generated because there
109
+ /// aren't enough elements in the values builder to fill the list slots.
110
+ ///
111
+ /// If you're building a [Large]List and don't need to be compatible
112
+ /// with [Large]ListView, then `BaseListBuilder::Append(bool is_valid)`
113
+ /// is a simpler API.
114
+ ///
115
+ /// \pre if is_valid is false, list_length MUST be 0
116
+ /// \param is_valid Whether the new list slot is valid
117
+ /// \param list_length The number of elements in the list
118
+ Status Append(bool is_valid, int64_t list_length) {
119
+ ARROW_RETURN_NOT_OK(Reserve(1));
120
+ assert(is_valid || list_length == 0);
121
+ UnsafeAppendToBitmap(is_valid);
122
+ UnsafeAppendDimensions(/*offset=*/value_builder_->length(), /*size=*/list_length);
123
+ return Status::OK();
124
+ }
125
+
126
+ Status AppendNull() final {
127
+ // Append() a null list slot with list_length=0.
128
+ //
129
+ // When building [Large]List arrays, elements being appended to the values builder
130
+ // before the next call to Append* or Finish will extend the list slot length, but
131
+ // that is totally fine because list arrays admit non-empty null list slots.
132
+ //
133
+ // In the case of [Large]ListViews that's not a problem either because the
134
+ // list slot length remains zero.
135
+ return Append(false, 0);
136
+ }
137
+
138
+ Status AppendNulls(int64_t length) final {
139
+ ARROW_RETURN_NOT_OK(Reserve(length));
140
+ UnsafeAppendToBitmap(length, false);
141
+ UnsafeAppendEmptyDimensions(/*num_values=*/length);
142
+ return Status::OK();
143
+ }
144
+
145
+ /// \brief Append an empty list slot
146
+ ///
147
+ /// \post Another call to Append* or Finish should be made before appending to
148
+ /// the values builder to ensure list slot remains empty
149
+ Status AppendEmptyValue() final { return Append(true, 0); }
150
+
151
+ /// \brief Append an empty list slot
152
+ ///
153
+ /// \post Another call to Append* or Finish should be made before appending to
154
+ /// the values builder to ensure the last list slot remains empty
155
+ Status AppendEmptyValues(int64_t length) final {
156
+ ARROW_RETURN_NOT_OK(Reserve(length));
157
+ UnsafeAppendToBitmap(length, true);
158
+ UnsafeAppendEmptyDimensions(/*num_values=*/length);
159
+ return Status::OK();
160
+ }
161
+
162
+ /// \brief Vector append
163
+ ///
164
+ /// For list-array builders, the sizes are inferred from the offsets.
165
+ /// BaseListBuilder<T> provides an implementation that doesn't take sizes, but
166
+ /// this virtual function allows dispatching calls to both list-array and
167
+ /// list-view-array builders (which need the sizes)
168
+ ///
169
+ /// \param offsets The offsets of the variable-length lists
170
+ /// \param sizes The sizes of the variable-length lists
171
+ /// \param length The number of offsets, sizes, and validity bits to append
172
+ /// \param valid_bytes If passed, valid_bytes is of equal length to values,
173
+ /// and any zero byte will be considered as a null for that slot
174
+ virtual Status AppendValues(const offset_type* offsets, const offset_type* sizes,
175
+ int64_t length, const uint8_t* valid_bytes) = 0;
176
+
177
+ Status AppendArraySlice(const ArraySpan& array, int64_t offset,
178
+ int64_t length) override {
179
+ const offset_type* offsets = array.GetValues<offset_type>(1);
180
+ [[maybe_unused]] const offset_type* sizes = NULLPTR;
181
+ if constexpr (is_list_view(TYPE::type_id)) {
182
+ sizes = array.GetValues<offset_type>(2);
183
+ }
184
+ const bool all_valid = !array.MayHaveLogicalNulls();
185
+ const uint8_t* validity = array.HasValidityBitmap() ? array.buffers[0].data : NULLPTR;
186
+ ARROW_RETURN_NOT_OK(Reserve(length));
187
+ for (int64_t row = offset; row < offset + length; row++) {
188
+ const bool is_valid =
189
+ all_valid || (validity && bit_util::GetBit(validity, array.offset + row)) ||
190
+ array.IsValid(row);
191
+ int64_t size = 0;
192
+ if (is_valid) {
193
+ if constexpr (is_list_view(TYPE::type_id)) {
194
+ size = sizes[row];
195
+ } else {
196
+ size = offsets[row + 1] - offsets[row];
197
+ }
198
+ }
199
+ UnsafeAppendToBitmap(is_valid);
200
+ UnsafeAppendDimensions(/*offset=*/value_builder_->length(), size);
201
+ if (is_valid) {
202
+ ARROW_RETURN_NOT_OK(
203
+ value_builder_->AppendArraySlice(array.child_data[0], offsets[row], size));
204
+ }
205
+ }
206
+ return Status::OK();
207
+ }
208
+
209
+ Status ValidateOverflow(int64_t new_elements) const {
210
+ auto new_length = value_builder_->length() + new_elements;
211
+ if (ARROW_PREDICT_FALSE(new_length > maximum_elements())) {
212
+ return Status::CapacityError(type_name(), " array cannot contain more than ",
213
+ maximum_elements(), " elements, have ", new_elements);
214
+ } else {
215
+ return Status::OK();
216
+ }
217
+ }
218
+
219
+ ArrayBuilder* value_builder() const { return value_builder_.get(); }
220
+
221
+ // Cannot make this a static attribute because of linking issues
222
+ static constexpr int64_t maximum_elements() {
223
+ return std::numeric_limits<offset_type>::max() - 1;
224
+ }
225
+
226
+ std::shared_ptr<DataType> type() const override {
227
+ return std::make_shared<TYPE>(value_field_->WithType(value_builder_->type()));
228
+ }
229
+
230
+ private:
231
+ static constexpr const char* type_name() {
232
+ if constexpr (is_list_view(TYPE::type_id)) {
233
+ return "ListView";
234
+ } else {
235
+ return "List";
236
+ }
237
+ }
238
+
239
+ protected:
240
+ /// \brief Append dimensions for num_values empty list slots.
241
+ ///
242
+ /// ListViewBuilder overrides this to also append the sizes.
243
+ virtual void UnsafeAppendEmptyDimensions(int64_t num_values) {
244
+ const int64_t offset = value_builder_->length();
245
+ for (int64_t i = 0; i < num_values; ++i) {
246
+ offsets_builder_.UnsafeAppend(static_cast<offset_type>(offset));
247
+ }
248
+ }
249
+
250
+ /// \brief Append dimensions for a single list slot.
251
+ ///
252
+ /// ListViewBuilder overrides this to also append the size.
253
+ virtual void UnsafeAppendDimensions(int64_t offset, int64_t size) {
254
+ offsets_builder_.UnsafeAppend(static_cast<offset_type>(offset));
255
+ }
256
+
257
+ TypedBufferBuilder<offset_type> offsets_builder_;
258
+ std::shared_ptr<ArrayBuilder> value_builder_;
259
+ std::shared_ptr<Field> value_field_;
260
+ };
261
+
262
+ // ----------------------------------------------------------------------
263
+ // ListBuilder / LargeListBuilder
264
+
265
+ template <typename TYPE>
266
+ class ARROW_EXPORT BaseListBuilder : public VarLengthListLikeBuilder<TYPE> {
267
+ private:
268
+ using BASE = VarLengthListLikeBuilder<TYPE>;
269
+
270
+ public:
271
+ using TypeClass = TYPE;
272
+ using offset_type = typename BASE::offset_type;
273
+
274
+ using BASE::BASE;
275
+
276
+ using BASE::Append;
277
+
278
+ ~BaseListBuilder() override = default;
279
+
280
+ /// \brief Start a new variable-length list slot
281
+ ///
282
+ /// This function should be called before beginning to append elements to the
283
+ /// value builder
284
+ Status Append(bool is_valid = true) {
285
+ // The value_length parameter to BASE::Append(bool, int64_t) is ignored when
286
+ // building a list array, so we can pass 0 here.
287
+ return BASE::Append(is_valid, 0);
288
+ }
289
+
290
+ /// \brief Vector append
291
+ ///
292
+ /// If passed, valid_bytes is of equal length to values, and any zero byte
293
+ /// will be considered as a null for that slot
294
+ Status AppendValues(const offset_type* offsets, int64_t length,
295
+ const uint8_t* valid_bytes = NULLPTR) {
296
+ ARROW_RETURN_NOT_OK(this->Reserve(length));
297
+ this->UnsafeAppendToBitmap(valid_bytes, length);
298
+ this->offsets_builder_.UnsafeAppend(offsets, length);
299
+ return Status::OK();
300
+ }
301
+
302
+ Status AppendValues(const offset_type* offsets, const offset_type* sizes,
303
+ int64_t length, const uint8_t* valid_bytes) final {
304
+ // Offsets are assumed to be valid, but the first length-1 sizes have to be
305
+ // consistent with the offsets to partially rule out the possibility that the
306
+ // caller is passing sizes that could work if building a list-view, but don't
307
+ // work on building a list that requires offsets to be non-decreasing.
308
+ //
309
+ // CAUTION: the last size element (`sizes[length - 1]`) is not
310
+ // validated and could be inconsistent with the offsets given in a
311
+ // subsequent call to AppendValues.
312
+ #ifndef NDEBUG
313
+ if (sizes) {
314
+ for (int64_t i = 0; i < length - 1; ++i) {
315
+ if (ARROW_PREDICT_FALSE(offsets[i] != offsets[i + 1] - sizes[i])) {
316
+ if (!valid_bytes || valid_bytes[i]) {
317
+ return Status::Invalid(
318
+ "BaseListBuilder: sizes are inconsistent with offsets provided");
319
+ }
320
+ }
321
+ }
322
+ }
323
+ #endif
324
+ return AppendValues(offsets, length, valid_bytes);
325
+ }
326
+
327
+ Status AppendValues(const offset_type* offsets, const offset_type* sizes,
328
+ int64_t length) {
329
+ return AppendValues(offsets, sizes, length, /*valid_bytes=*/NULLPTR);
330
+ }
331
+
332
+ Status AppendNextOffset() {
333
+ ARROW_RETURN_NOT_OK(this->ValidateOverflow(0));
334
+ const int64_t num_values = this->value_builder_->length();
335
+ return this->offsets_builder_.Append(static_cast<offset_type>(num_values));
336
+ }
337
+
338
+ Status FinishInternal(std::shared_ptr<ArrayData>* out) override {
339
+ ARROW_RETURN_NOT_OK(AppendNextOffset());
340
+
341
+ // Offset padding zeroed by BufferBuilder
342
+ std::shared_ptr<Buffer> offsets;
343
+ std::shared_ptr<Buffer> null_bitmap;
344
+ ARROW_RETURN_NOT_OK(this->offsets_builder_.Finish(&offsets));
345
+ ARROW_RETURN_NOT_OK(this->null_bitmap_builder_.Finish(&null_bitmap));
346
+
347
+ if (this->value_builder_->length() == 0) {
348
+ // Try to make sure we get a non-null values buffer (ARROW-2744)
349
+ ARROW_RETURN_NOT_OK(this->value_builder_->Resize(0));
350
+ }
351
+
352
+ std::shared_ptr<ArrayData> items;
353
+ ARROW_RETURN_NOT_OK(this->value_builder_->FinishInternal(&items));
354
+
355
+ *out = ArrayData::Make(this->type(), this->length_,
356
+ {std::move(null_bitmap), std::move(offsets)},
357
+ {std::move(items)}, this->null_count_);
358
+ this->Reset();
359
+ return Status::OK();
360
+ }
361
+ };
362
+
363
+ /// \class ListBuilder
364
+ /// \brief Builder class for variable-length list array value types
365
+ ///
366
+ /// To use this class, you must append values to the child array builder and use
367
+ /// the Append function to delimit each distinct list value (once the values
368
+ /// have been appended to the child array) or use the bulk API to append
369
+ /// a sequence of offsets and null values.
370
+ ///
371
+ /// A note on types. Per arrow/type.h all types in the c++ implementation are
372
+ /// logical so even though this class always builds list array, this can
373
+ /// represent multiple different logical types. If no logical type is provided
374
+ /// at construction time, the class defaults to List<T> where t is taken from the
375
+ /// value_builder/values that the object is constructed with.
376
+ class ARROW_EXPORT ListBuilder : public BaseListBuilder<ListType> {
377
+ public:
378
+ using BaseListBuilder::BaseListBuilder;
379
+
380
+ /// \cond FALSE
381
+ using ArrayBuilder::Finish;
382
+ /// \endcond
383
+
384
+ Status Finish(std::shared_ptr<ListArray>* out) { return FinishTyped(out); }
385
+ };
386
+
387
+ /// \class LargeListBuilder
388
+ /// \brief Builder class for large variable-length list array value types
389
+ ///
390
+ /// Like ListBuilder, but to create large list arrays (with 64-bit offsets).
391
+ class ARROW_EXPORT LargeListBuilder : public BaseListBuilder<LargeListType> {
392
+ public:
393
+ using BaseListBuilder::BaseListBuilder;
394
+
395
+ /// \cond FALSE
396
+ using ArrayBuilder::Finish;
397
+ /// \endcond
398
+
399
+ Status Finish(std::shared_ptr<LargeListArray>* out) { return FinishTyped(out); }
400
+ };
401
+
402
+ // ----------------------------------------------------------------------
403
+ // ListViewBuilder / LargeListViewBuilder
404
+
405
+ template <typename TYPE>
406
+ class ARROW_EXPORT BaseListViewBuilder : public VarLengthListLikeBuilder<TYPE> {
407
+ private:
408
+ using BASE = VarLengthListLikeBuilder<TYPE>;
409
+
410
+ public:
411
+ using TypeClass = TYPE;
412
+ using offset_type = typename BASE::offset_type;
413
+
414
+ using BASE::BASE;
415
+
416
+ ~BaseListViewBuilder() override = default;
417
+
418
+ Status Resize(int64_t capacity) override {
419
+ ARROW_RETURN_NOT_OK(BASE::Resize(capacity));
420
+ return sizes_builder_.Resize(capacity);
421
+ }
422
+
423
+ void Reset() override {
424
+ BASE::Reset();
425
+ sizes_builder_.Reset();
426
+ }
427
+
428
+ /// \brief Vector append
429
+ ///
430
+ /// If passed, valid_bytes is of equal length to values, and any zero byte
431
+ /// will be considered as a null for that slot
432
+ Status AppendValues(const offset_type* offsets, const offset_type* sizes,
433
+ int64_t length, const uint8_t* valid_bytes) final {
434
+ ARROW_RETURN_NOT_OK(this->Reserve(length));
435
+ this->UnsafeAppendToBitmap(valid_bytes, length);
436
+ this->offsets_builder_.UnsafeAppend(offsets, length);
437
+ this->sizes_builder_.UnsafeAppend(sizes, length);
438
+ return Status::OK();
439
+ }
440
+
441
+ Status AppendValues(const offset_type* offsets, const offset_type* sizes,
442
+ int64_t length) {
443
+ return AppendValues(offsets, sizes, length, /*valid_bytes=*/NULLPTR);
444
+ }
445
+
446
+ Status FinishInternal(std::shared_ptr<ArrayData>* out) override {
447
+ // Offset and sizes padding zeroed by BufferBuilder
448
+ std::shared_ptr<Buffer> null_bitmap;
449
+ std::shared_ptr<Buffer> offsets;
450
+ std::shared_ptr<Buffer> sizes;
451
+ ARROW_RETURN_NOT_OK(this->null_bitmap_builder_.Finish(&null_bitmap));
452
+ ARROW_RETURN_NOT_OK(this->offsets_builder_.Finish(&offsets));
453
+ ARROW_RETURN_NOT_OK(this->sizes_builder_.Finish(&sizes));
454
+
455
+ if (this->value_builder_->length() == 0) {
456
+ // Try to make sure we get a non-null values buffer (ARROW-2744)
457
+ ARROW_RETURN_NOT_OK(this->value_builder_->Resize(0));
458
+ }
459
+
460
+ std::shared_ptr<ArrayData> items;
461
+ ARROW_RETURN_NOT_OK(this->value_builder_->FinishInternal(&items));
462
+
463
+ *out = ArrayData::Make(this->type(), this->length_,
464
+ {std::move(null_bitmap), std::move(offsets), std::move(sizes)},
465
+ {std::move(items)}, this->null_count_);
466
+ this->Reset();
467
+ return Status::OK();
468
+ }
469
+
470
+ protected:
471
+ void UnsafeAppendEmptyDimensions(int64_t num_values) override {
472
+ for (int64_t i = 0; i < num_values; ++i) {
473
+ this->offsets_builder_.UnsafeAppend(0);
474
+ }
475
+ for (int64_t i = 0; i < num_values; ++i) {
476
+ this->sizes_builder_.UnsafeAppend(0);
477
+ }
478
+ }
479
+
480
+ void UnsafeAppendDimensions(int64_t offset, int64_t size) override {
481
+ this->offsets_builder_.UnsafeAppend(static_cast<offset_type>(offset));
482
+ this->sizes_builder_.UnsafeAppend(static_cast<offset_type>(size));
483
+ }
484
+
485
+ private:
486
+ TypedBufferBuilder<offset_type> sizes_builder_;
487
+ };
488
+
489
+ class ARROW_EXPORT ListViewBuilder final : public BaseListViewBuilder<ListViewType> {
490
+ public:
491
+ using BaseListViewBuilder::BaseListViewBuilder;
492
+
493
+ /// \cond FALSE
494
+ using ArrayBuilder::Finish;
495
+ /// \endcond
496
+
497
+ Status Finish(std::shared_ptr<ListViewArray>* out) { return FinishTyped(out); }
498
+ };
499
+
500
+ class ARROW_EXPORT LargeListViewBuilder final
501
+ : public BaseListViewBuilder<LargeListViewType> {
502
+ public:
503
+ using BaseListViewBuilder::BaseListViewBuilder;
504
+
505
+ /// \cond FALSE
506
+ using ArrayBuilder::Finish;
507
+ /// \endcond
508
+
509
+ Status Finish(std::shared_ptr<LargeListViewArray>* out) { return FinishTyped(out); }
510
+ };
511
+
512
+ // ----------------------------------------------------------------------
513
+ // Map builder
514
+
515
+ /// \class MapBuilder
516
+ /// \brief Builder class for arrays of variable-size maps
517
+ ///
518
+ /// To use this class, you must use the Append function to delimit each distinct
519
+ /// map before appending values to the key and item array builders, or use the
520
+ /// bulk API to append a sequence of offsets and null maps.
521
+ ///
522
+ /// Key uniqueness and ordering are not validated.
523
+ class ARROW_EXPORT MapBuilder : public ArrayBuilder {
524
+ public:
525
+ /// Use this constructor to define the built array's type explicitly. If key_builder
526
+ /// or item_builder has indeterminate type, this builder will also.
527
+ MapBuilder(MemoryPool* pool, const std::shared_ptr<ArrayBuilder>& key_builder,
528
+ const std::shared_ptr<ArrayBuilder>& item_builder,
529
+ const std::shared_ptr<DataType>& type);
530
+
531
+ /// Use this constructor to infer the built array's type. If key_builder or
532
+ /// item_builder has indeterminate type, this builder will also.
533
+ MapBuilder(MemoryPool* pool, const std::shared_ptr<ArrayBuilder>& key_builder,
534
+ const std::shared_ptr<ArrayBuilder>& item_builder, bool keys_sorted = false);
535
+
536
+ MapBuilder(MemoryPool* pool, const std::shared_ptr<ArrayBuilder>& item_builder,
537
+ const std::shared_ptr<DataType>& type);
538
+
539
+ Status Resize(int64_t capacity) override;
540
+ void Reset() override;
541
+ Status FinishInternal(std::shared_ptr<ArrayData>* out) override;
542
+
543
+ /// \cond FALSE
544
+ using ArrayBuilder::Finish;
545
+ /// \endcond
546
+
547
+ Status Finish(std::shared_ptr<MapArray>* out) { return FinishTyped(out); }
548
+
549
+ /// \brief Vector append
550
+ ///
551
+ /// If passed, valid_bytes is of equal length to values, and any zero byte
552
+ /// will be considered as a null for that slot
553
+ Status AppendValues(const int32_t* offsets, int64_t length,
554
+ const uint8_t* valid_bytes = NULLPTR);
555
+
556
+ /// \brief Start a new variable-length map slot
557
+ ///
558
+ /// This function should be called before beginning to append elements to the
559
+ /// key and item builders
560
+ Status Append();
561
+
562
+ Status AppendNull() final;
563
+
564
+ Status AppendNulls(int64_t length) final;
565
+
566
+ Status AppendEmptyValue() final;
567
+
568
+ Status AppendEmptyValues(int64_t length) final;
569
+
570
+ Status AppendArraySlice(const ArraySpan& array, int64_t offset,
571
+ int64_t length) override {
572
+ const int32_t* offsets = array.GetValues<int32_t>(1);
573
+ const bool all_valid = !array.MayHaveLogicalNulls();
574
+ const uint8_t* validity = array.HasValidityBitmap() ? array.buffers[0].data : NULLPTR;
575
+ for (int64_t row = offset; row < offset + length; row++) {
576
+ const bool is_valid =
577
+ all_valid || (validity && bit_util::GetBit(validity, array.offset + row)) ||
578
+ array.IsValid(row);
579
+ if (is_valid) {
580
+ ARROW_RETURN_NOT_OK(Append());
581
+ const int64_t slot_length = offsets[row + 1] - offsets[row];
582
+ // Add together the inner StructArray offset to the Map/List offset
583
+ int64_t key_value_offset = array.child_data[0].offset + offsets[row];
584
+ ARROW_RETURN_NOT_OK(key_builder_->AppendArraySlice(
585
+ array.child_data[0].child_data[0], key_value_offset, slot_length));
586
+ ARROW_RETURN_NOT_OK(item_builder_->AppendArraySlice(
587
+ array.child_data[0].child_data[1], key_value_offset, slot_length));
588
+ } else {
589
+ ARROW_RETURN_NOT_OK(AppendNull());
590
+ }
591
+ }
592
+ return Status::OK();
593
+ }
594
+
595
+ /// \brief Get builder to append keys.
596
+ ///
597
+ /// Append a key with this builder should be followed by appending
598
+ /// an item or null value with item_builder().
599
+ ArrayBuilder* key_builder() const { return key_builder_.get(); }
600
+
601
+ /// \brief Get builder to append items
602
+ ///
603
+ /// Appending an item with this builder should have been preceded
604
+ /// by appending a key with key_builder().
605
+ ArrayBuilder* item_builder() const { return item_builder_.get(); }
606
+
607
+ /// \brief Get builder to add Map entries as struct values.
608
+ ///
609
+ /// This is used instead of key_builder()/item_builder() and allows
610
+ /// the Map to be built as a list of struct values.
611
+ ArrayBuilder* value_builder() const { return list_builder_->value_builder(); }
612
+
613
+ std::shared_ptr<DataType> type() const override {
614
+ // Key and Item builder may update types, but they don't contain the field names,
615
+ // so we need to reconstruct the type. (See ARROW-13735.)
616
+ return std::make_shared<MapType>(
617
+ field(entries_name_,
618
+ struct_({field(key_name_, key_builder_->type(), false),
619
+ field(item_name_, item_builder_->type(), item_nullable_)}),
620
+ false),
621
+ keys_sorted_);
622
+ }
623
+
624
+ Status ValidateOverflow(int64_t new_elements) {
625
+ return list_builder_->ValidateOverflow(new_elements);
626
+ }
627
+
628
+ protected:
629
+ inline Status AdjustStructBuilderLength();
630
+
631
+ protected:
632
+ bool keys_sorted_ = false;
633
+ bool item_nullable_ = false;
634
+ std::string entries_name_;
635
+ std::string key_name_;
636
+ std::string item_name_;
637
+ std::shared_ptr<ListBuilder> list_builder_;
638
+ std::shared_ptr<ArrayBuilder> key_builder_;
639
+ std::shared_ptr<ArrayBuilder> item_builder_;
640
+ };
641
+
642
+ // ----------------------------------------------------------------------
643
+ // FixedSizeList builder
644
+
645
+ /// \class FixedSizeListBuilder
646
+ /// \brief Builder class for fixed-length list array value types
647
+ class ARROW_EXPORT FixedSizeListBuilder : public ArrayBuilder {
648
+ public:
649
+ /// Use this constructor to define the built array's type explicitly. If value_builder
650
+ /// has indeterminate type, this builder will also.
651
+ FixedSizeListBuilder(MemoryPool* pool,
652
+ std::shared_ptr<ArrayBuilder> const& value_builder,
653
+ int32_t list_size);
654
+
655
+ /// Use this constructor to infer the built array's type. If value_builder has
656
+ /// indeterminate type, this builder will also.
657
+ FixedSizeListBuilder(MemoryPool* pool,
658
+ std::shared_ptr<ArrayBuilder> const& value_builder,
659
+ const std::shared_ptr<DataType>& type);
660
+
661
+ Status Resize(int64_t capacity) override;
662
+ void Reset() override;
663
+ Status FinishInternal(std::shared_ptr<ArrayData>* out) override;
664
+
665
+ /// \cond FALSE
666
+ using ArrayBuilder::Finish;
667
+ /// \endcond
668
+
669
+ Status Finish(std::shared_ptr<FixedSizeListArray>* out) { return FinishTyped(out); }
670
+
671
+ /// \brief Append a valid fixed length list.
672
+ ///
673
+ /// This function affects only the validity bitmap; the child values must be appended
674
+ /// using the child array builder.
675
+ Status Append();
676
+
677
+ /// \brief Vector append
678
+ ///
679
+ /// If passed, valid_bytes will be read and any zero byte
680
+ /// will cause the corresponding slot to be null
681
+ ///
682
+ /// This function affects only the validity bitmap; the child values must be appended
683
+ /// using the child array builder. This includes appending nulls for null lists.
684
+ /// XXX this restriction is confusing, should this method be omitted?
685
+ Status AppendValues(int64_t length, const uint8_t* valid_bytes = NULLPTR);
686
+
687
+ /// \brief Append a null fixed length list.
688
+ ///
689
+ /// The child array builder will have the appropriate number of nulls appended
690
+ /// automatically.
691
+ Status AppendNull() final;
692
+
693
+ /// \brief Append length null fixed length lists.
694
+ ///
695
+ /// The child array builder will have the appropriate number of nulls appended
696
+ /// automatically.
697
+ Status AppendNulls(int64_t length) final;
698
+
699
+ Status ValidateOverflow(int64_t new_elements);
700
+
701
+ Status AppendEmptyValue() final;
702
+
703
+ Status AppendEmptyValues(int64_t length) final;
704
+
705
+ Status AppendArraySlice(const ArraySpan& array, int64_t offset, int64_t length) final {
706
+ const uint8_t* validity = array.MayHaveNulls() ? array.buffers[0].data : NULLPTR;
707
+ for (int64_t row = offset; row < offset + length; row++) {
708
+ if (!validity || bit_util::GetBit(validity, array.offset + row)) {
709
+ ARROW_RETURN_NOT_OK(value_builder_->AppendArraySlice(
710
+ array.child_data[0], list_size_ * (array.offset + row), list_size_));
711
+ ARROW_RETURN_NOT_OK(Append());
712
+ } else {
713
+ ARROW_RETURN_NOT_OK(AppendNull());
714
+ }
715
+ }
716
+ return Status::OK();
717
+ }
718
+
719
+ ArrayBuilder* value_builder() const { return value_builder_.get(); }
720
+
721
+ std::shared_ptr<DataType> type() const override {
722
+ return fixed_size_list(value_field_->WithType(value_builder_->type()), list_size_);
723
+ }
724
+
725
+ // Cannot make this a static attribute because of linking issues
726
+ static constexpr int64_t maximum_elements() {
727
+ return std::numeric_limits<FixedSizeListType::offset_type>::max() - 1;
728
+ }
729
+
730
+ protected:
731
+ std::shared_ptr<Field> value_field_;
732
+ const int32_t list_size_;
733
+ std::shared_ptr<ArrayBuilder> value_builder_;
734
+ };
735
+
736
+ // ----------------------------------------------------------------------
737
+ // Struct
738
+
739
+ // ---------------------------------------------------------------------------------
740
+ // StructArray builder
741
+ /// Append, Resize and Reserve methods are acting on StructBuilder.
742
+ /// Please make sure all these methods of all child-builders' are consistently
743
+ /// called to maintain data-structure consistency.
744
+ class ARROW_EXPORT StructBuilder : public ArrayBuilder {
745
+ public:
746
+ /// If any of field_builders has indeterminate type, this builder will also
747
+ StructBuilder(const std::shared_ptr<DataType>& type, MemoryPool* pool,
748
+ std::vector<std::shared_ptr<ArrayBuilder>> field_builders);
749
+
750
+ Status FinishInternal(std::shared_ptr<ArrayData>* out) override;
751
+
752
+ /// \cond FALSE
753
+ using ArrayBuilder::Finish;
754
+ /// \endcond
755
+
756
+ Status Finish(std::shared_ptr<StructArray>* out) { return FinishTyped(out); }
757
+
758
+ /// Null bitmap is of equal length to every child field, and any zero byte
759
+ /// will be considered as a null for that field, but users must using app-
760
+ /// end methods or advance methods of the child builders' independently to
761
+ /// insert data.
762
+ Status AppendValues(int64_t length, const uint8_t* valid_bytes) {
763
+ ARROW_RETURN_NOT_OK(Reserve(length));
764
+ UnsafeAppendToBitmap(valid_bytes, length);
765
+ return Status::OK();
766
+ }
767
+
768
+ /// Append an element to the Struct. All child-builders' Append method must
769
+ /// be called independently to maintain data-structure consistency.
770
+ Status Append(bool is_valid = true) {
771
+ ARROW_RETURN_NOT_OK(Reserve(1));
772
+ UnsafeAppendToBitmap(is_valid);
773
+ return Status::OK();
774
+ }
775
+
776
+ /// \brief Append a null value. Automatically appends an empty value to each child
777
+ /// builder.
778
+ Status AppendNull() final {
779
+ for (const auto& field : children_) {
780
+ ARROW_RETURN_NOT_OK(field->AppendEmptyValue());
781
+ }
782
+ return Append(false);
783
+ }
784
+
785
+ /// \brief Append multiple null values. Automatically appends empty values to each
786
+ /// child builder.
787
+ Status AppendNulls(int64_t length) final {
788
+ for (const auto& field : children_) {
789
+ ARROW_RETURN_NOT_OK(field->AppendEmptyValues(length));
790
+ }
791
+ ARROW_RETURN_NOT_OK(Reserve(length));
792
+ UnsafeAppendToBitmap(length, false);
793
+ return Status::OK();
794
+ }
795
+
796
+ Status AppendEmptyValue() final {
797
+ for (const auto& field : children_) {
798
+ ARROW_RETURN_NOT_OK(field->AppendEmptyValue());
799
+ }
800
+ return Append(true);
801
+ }
802
+
803
+ Status AppendEmptyValues(int64_t length) final {
804
+ for (const auto& field : children_) {
805
+ ARROW_RETURN_NOT_OK(field->AppendEmptyValues(length));
806
+ }
807
+ ARROW_RETURN_NOT_OK(Reserve(length));
808
+ UnsafeAppendToBitmap(length, true);
809
+ return Status::OK();
810
+ }
811
+
812
+ Status AppendArraySlice(const ArraySpan& array, int64_t offset,
813
+ int64_t length) override {
814
+ for (int i = 0; static_cast<size_t>(i) < children_.size(); i++) {
815
+ ARROW_RETURN_NOT_OK(children_[i]->AppendArraySlice(array.child_data[i],
816
+ array.offset + offset, length));
817
+ }
818
+ const uint8_t* validity = array.MayHaveNulls() ? array.buffers[0].data : NULLPTR;
819
+ ARROW_RETURN_NOT_OK(Reserve(length));
820
+ UnsafeAppendToBitmap(validity, array.offset + offset, length);
821
+ return Status::OK();
822
+ }
823
+
824
+ void Reset() override;
825
+
826
+ ArrayBuilder* field_builder(int i) const { return children_[i].get(); }
827
+
828
+ int num_fields() const { return static_cast<int>(children_.size()); }
829
+
830
+ std::shared_ptr<DataType> type() const override;
831
+
832
+ private:
833
+ std::shared_ptr<DataType> type_;
834
+ };
835
+
836
+ /// @}
837
+
838
+ } // namespace arrow
venv/lib/python3.10/site-packages/pyarrow/include/arrow/array/builder_run_end.h ADDED
@@ -0,0 +1,303 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #pragma once
19
+
20
+ #include <cstdint>
21
+ #include <limits>
22
+ #include <memory>
23
+ #include <utility>
24
+ #include <vector>
25
+
26
+ #include "arrow/array.h"
27
+ #include "arrow/array/builder_base.h"
28
+
29
+ namespace arrow {
30
+
31
+ /// \addtogroup run-end-encoded-builders
32
+ ///
33
+ /// @{
34
+
35
+ namespace internal {
36
+
37
+ /// \brief An ArrayBuilder that deduplicates repeated values as they are
38
+ /// appended to the inner-ArrayBuilder and reports the length of the current run
39
+ /// of identical values.
40
+ ///
41
+ /// The following sequence of calls
42
+ ///
43
+ /// Append(2)
44
+ /// Append(2)
45
+ /// Append(2)
46
+ /// Append(7)
47
+ /// Append(7)
48
+ /// Append(2)
49
+ /// FinishInternal()
50
+ ///
51
+ /// will cause the inner-builder to receive only 3 Append calls
52
+ ///
53
+ /// Append(2)
54
+ /// Append(7)
55
+ /// Append(2)
56
+ /// FinishInternal()
57
+ ///
58
+ /// Note that values returned by length(), null_count() and capacity() are
59
+ /// related to the compressed array built by the inner-ArrayBuilder.
60
+ class RunCompressorBuilder : public ArrayBuilder {
61
+ public:
62
+ RunCompressorBuilder(MemoryPool* pool, std::shared_ptr<ArrayBuilder> inner_builder,
63
+ std::shared_ptr<DataType> type);
64
+
65
+ ~RunCompressorBuilder() override;
66
+
67
+ ARROW_DISALLOW_COPY_AND_ASSIGN(RunCompressorBuilder);
68
+
69
+ /// \brief Called right before a run is being closed
70
+ ///
71
+ /// Subclasses can override this function to perform an additional action when
72
+ /// a run is closed (i.e. run-length is known and value is appended to the
73
+ /// inner builder).
74
+ ///
75
+ /// \param value can be NULLPTR if closing a run of NULLs
76
+ /// \param length the greater than 0 length of the value run being closed
77
+ virtual Status WillCloseRun(const std::shared_ptr<const Scalar>& value,
78
+ int64_t length) {
79
+ return Status::OK();
80
+ }
81
+
82
+ /// \brief Called right before a run of empty values is being closed
83
+ ///
84
+ /// Subclasses can override this function to perform an additional action when
85
+ /// a run of empty values is appended (i.e. run-length is known and a single
86
+ /// empty value is appended to the inner builder).
87
+ ///
88
+ /// \param length the greater than 0 length of the value run being closed
89
+ virtual Status WillCloseRunOfEmptyValues(int64_t length) { return Status::OK(); }
90
+
91
+ /// \brief Allocate enough memory for a given number of array elements.
92
+ ///
93
+ /// NOTE: Conservatively resizing a run-length compressed array for a given
94
+ /// number of logical elements is not possible, since the physical length will
95
+ /// vary depending on the values to be appended in the future. But we can
96
+ /// pessimistically assume that each run will contain a single value and
97
+ /// allocate that number of runs.
98
+ Status Resize(int64_t capacity) override { return ResizePhysical(capacity); }
99
+
100
+ /// \brief Allocate enough memory for a given number of runs.
101
+ ///
102
+ /// Like Resize on non-encoded builders, it does not account for variable size
103
+ /// data.
104
+ Status ResizePhysical(int64_t capacity);
105
+
106
+ Status ReservePhysical(int64_t additional_capacity) {
107
+ return Reserve(additional_capacity);
108
+ }
109
+
110
+ void Reset() override;
111
+
112
+ Status AppendNull() final { return AppendNulls(1); }
113
+ Status AppendNulls(int64_t length) override;
114
+
115
+ Status AppendEmptyValue() final { return AppendEmptyValues(1); }
116
+ Status AppendEmptyValues(int64_t length) override;
117
+
118
+ Status AppendScalar(const Scalar& scalar, int64_t n_repeats) override;
119
+ Status AppendScalars(const ScalarVector& scalars) override;
120
+
121
+ // AppendArraySlice() is not implemented.
122
+
123
+ /// \brief Append a slice of an array containing values from already
124
+ /// compressed runs.
125
+ ///
126
+ /// NOTE: WillCloseRun() is not called as the length of each run cannot be
127
+ /// determined at this point. Caller should ensure that !has_open_run() by
128
+ /// calling FinishCurrentRun() before calling this.
129
+ ///
130
+ /// Pre-condition: !has_open_run()
131
+ Status AppendRunCompressedArraySlice(const ArraySpan& array, int64_t offset,
132
+ int64_t length);
133
+
134
+ /// \brief Forces the closing of the current run if one is currently open.
135
+ ///
136
+ /// This can be called when one wants to ensure the current run will not be
137
+ /// extended. This may cause identical values to appear close to each other in
138
+ /// the underlying array (i.e. two runs that could be a single run) if more
139
+ /// values are appended after this is called.
140
+ ///
141
+ /// Finish() and FinishInternal() call this automatically.
142
+ virtual Status FinishCurrentRun();
143
+
144
+ Status FinishInternal(std::shared_ptr<ArrayData>* out) override;
145
+
146
+ ArrayBuilder& inner_builder() const { return *inner_builder_; }
147
+
148
+ std::shared_ptr<DataType> type() const override { return inner_builder_->type(); }
149
+
150
+ bool has_open_run() const { return current_run_length_ > 0; }
151
+ int64_t open_run_length() const { return current_run_length_; }
152
+
153
+ private:
154
+ inline void UpdateDimensions() {
155
+ capacity_ = inner_builder_->capacity();
156
+ length_ = inner_builder_->length();
157
+ null_count_ = inner_builder_->null_count();
158
+ }
159
+
160
+ private:
161
+ std::shared_ptr<ArrayBuilder> inner_builder_;
162
+ std::shared_ptr<const Scalar> current_value_ = NULLPTR;
163
+ int64_t current_run_length_ = 0;
164
+ };
165
+
166
+ } // namespace internal
167
+
168
+ // ----------------------------------------------------------------------
169
+ // RunEndEncoded builder
170
+
171
+ /// \brief Run-end encoded array builder.
172
+ ///
173
+ /// NOTE: the value returned by and capacity() is related to the
174
+ /// compressed array (physical) and not the decoded array (logical) that is
175
+ /// run-end encoded. null_count() always returns 0. length(), on the other hand,
176
+ /// returns the logical length of the run-end encoded array.
177
+ class ARROW_EXPORT RunEndEncodedBuilder : public ArrayBuilder {
178
+ private:
179
+ // An internal::RunCompressorBuilder that produces a run-end in the
180
+ // RunEndEncodedBuilder every time a value-run is closed.
181
+ class ValueRunBuilder : public internal::RunCompressorBuilder {
182
+ public:
183
+ ValueRunBuilder(MemoryPool* pool, const std::shared_ptr<ArrayBuilder>& value_builder,
184
+ const std::shared_ptr<DataType>& value_type,
185
+ RunEndEncodedBuilder& ree_builder);
186
+
187
+ ~ValueRunBuilder() override = default;
188
+
189
+ Status WillCloseRun(const std::shared_ptr<const Scalar>&, int64_t length) override {
190
+ return ree_builder_.CloseRun(length);
191
+ }
192
+
193
+ Status WillCloseRunOfEmptyValues(int64_t length) override {
194
+ return ree_builder_.CloseRun(length);
195
+ }
196
+
197
+ private:
198
+ RunEndEncodedBuilder& ree_builder_;
199
+ };
200
+
201
+ public:
202
+ RunEndEncodedBuilder(MemoryPool* pool,
203
+ const std::shared_ptr<ArrayBuilder>& run_end_builder,
204
+ const std::shared_ptr<ArrayBuilder>& value_builder,
205
+ std::shared_ptr<DataType> type);
206
+
207
+ /// \brief Allocate enough memory for a given number of array elements.
208
+ ///
209
+ /// NOTE: Conservatively resizing an REE for a given number of logical
210
+ /// elements is not possible, since the physical length will vary depending on
211
+ /// the values to be appended in the future. But we can pessimistically assume
212
+ /// that each run will contain a single value and allocate that number of
213
+ /// runs.
214
+ Status Resize(int64_t capacity) override { return ResizePhysical(capacity); }
215
+
216
+ /// \brief Allocate enough memory for a given number of runs.
217
+ Status ResizePhysical(int64_t capacity);
218
+
219
+ /// \brief Ensure that there is enough space allocated to append the indicated
220
+ /// number of run without any further reallocation. Overallocation is
221
+ /// used in order to minimize the impact of incremental ReservePhysical() calls.
222
+ /// Note that additional_capacity is relative to the current number of elements
223
+ /// rather than to the current capacity, so calls to Reserve() which are not
224
+ /// interspersed with addition of new elements may not increase the capacity.
225
+ ///
226
+ /// \param[in] additional_capacity the number of additional runs
227
+ /// \return Status
228
+ Status ReservePhysical(int64_t additional_capacity) {
229
+ return Reserve(additional_capacity);
230
+ }
231
+
232
+ void Reset() override;
233
+
234
+ Status AppendNull() final { return AppendNulls(1); }
235
+ Status AppendNulls(int64_t length) override;
236
+
237
+ Status AppendEmptyValue() final { return AppendEmptyValues(1); }
238
+ Status AppendEmptyValues(int64_t length) override;
239
+ Status AppendScalar(const Scalar& scalar, int64_t n_repeats) override;
240
+ Status AppendScalars(const ScalarVector& scalars) override;
241
+ Status AppendArraySlice(const ArraySpan& array, int64_t offset,
242
+ int64_t length) override;
243
+ Status FinishInternal(std::shared_ptr<ArrayData>* out) override;
244
+
245
+ /// \cond FALSE
246
+ using ArrayBuilder::Finish;
247
+ /// \endcond
248
+
249
+ Status Finish(std::shared_ptr<RunEndEncodedArray>* out) { return FinishTyped(out); }
250
+
251
+ /// \brief Forces the closing of the current run if one is currently open.
252
+ ///
253
+ /// This can be called when one wants to ensure the current run will not be
254
+ /// extended. This may cause identical values to appear close to each other in
255
+ /// the values array (i.e. two runs that could be a single run) if more
256
+ /// values are appended after this is called.
257
+ Status FinishCurrentRun();
258
+
259
+ std::shared_ptr<DataType> type() const override;
260
+
261
+ private:
262
+ /// \brief Update physical capacity and logical length
263
+ ///
264
+ /// \param committed_logical_length number of logical values that have been
265
+ /// committed to the values array
266
+ /// \param open_run_length number of logical values in the currently open run if any
267
+ inline void UpdateDimensions(int64_t committed_logical_length,
268
+ int64_t open_run_length) {
269
+ capacity_ = run_end_builder().capacity();
270
+ length_ = committed_logical_length + open_run_length;
271
+ committed_logical_length_ = committed_logical_length;
272
+ }
273
+
274
+ // Pre-condition: !value_run_builder_.has_open_run()
275
+ template <typename RunEndCType>
276
+ Status DoAppendArraySlice(const ArraySpan& array, int64_t offset, int64_t length);
277
+
278
+ template <typename RunEndCType>
279
+ Status DoAppendRunEnd(int64_t run_end);
280
+
281
+ /// \brief Cast run_end to the appropriate type and appends it to the run_ends
282
+ /// array.
283
+ Status AppendRunEnd(int64_t run_end);
284
+
285
+ /// \brief Close a run by appending a value to the run_ends array and updating
286
+ /// length_ to reflect the new run.
287
+ ///
288
+ /// Pre-condition: run_length > 0.
289
+ [[nodiscard]] Status CloseRun(int64_t run_length);
290
+
291
+ ArrayBuilder& run_end_builder();
292
+ ArrayBuilder& value_builder();
293
+
294
+ private:
295
+ std::shared_ptr<RunEndEncodedType> type_;
296
+ ValueRunBuilder* value_run_builder_;
297
+ // The length not counting the current open run in the value_run_builder_
298
+ int64_t committed_logical_length_ = 0;
299
+ };
300
+
301
+ /// @}
302
+
303
+ } // namespace arrow
venv/lib/python3.10/site-packages/pyarrow/include/arrow/array/concatenate.h ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #pragma once
19
+
20
+ #include <memory>
21
+
22
+ #include "arrow/type_fwd.h"
23
+ #include "arrow/util/macros.h"
24
+ #include "arrow/util/visibility.h"
25
+
26
+ namespace arrow {
27
+
28
+ /// \brief Concatenate arrays
29
+ ///
30
+ /// \param[in] arrays a vector of arrays to be concatenated
31
+ /// \param[in] pool memory to store the result will be allocated from this memory pool
32
+ /// \return the concatenated array
33
+ ARROW_EXPORT
34
+ Result<std::shared_ptr<Array>> Concatenate(const ArrayVector& arrays,
35
+ MemoryPool* pool = default_memory_pool());
36
+
37
+ } // namespace arrow
venv/lib/python3.10/site-packages/pyarrow/include/arrow/array/util.h ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #pragma once
19
+
20
+ #include <cstdint>
21
+ #include <memory>
22
+ #include <vector>
23
+
24
+ #include "arrow/array/data.h"
25
+ #include "arrow/compare.h"
26
+ #include "arrow/result.h"
27
+ #include "arrow/status.h"
28
+ #include "arrow/type.h"
29
+ #include "arrow/util/macros.h"
30
+ #include "arrow/util/visibility.h"
31
+
32
+ namespace arrow {
33
+
34
+ /// \defgroup array-factories Array factory functions
35
+ ///
36
+ /// @{
37
+
38
+ /// \brief Create a strongly-typed Array instance from generic ArrayData
39
+ /// \param[in] data the array contents
40
+ /// \return the resulting Array instance
41
+ ARROW_EXPORT
42
+ std::shared_ptr<Array> MakeArray(const std::shared_ptr<ArrayData>& data);
43
+
44
+ /// \brief Create a strongly-typed Array instance with all elements null
45
+ /// \param[in] type the array type
46
+ /// \param[in] length the array length
47
+ /// \param[in] pool the memory pool to allocate memory from
48
+ ARROW_EXPORT
49
+ Result<std::shared_ptr<Array>> MakeArrayOfNull(const std::shared_ptr<DataType>& type,
50
+ int64_t length,
51
+ MemoryPool* pool = default_memory_pool());
52
+
53
+ /// \brief Create an Array instance whose slots are the given scalar
54
+ /// \param[in] scalar the value with which to fill the array
55
+ /// \param[in] length the array length
56
+ /// \param[in] pool the memory pool to allocate memory from
57
+ ARROW_EXPORT
58
+ Result<std::shared_ptr<Array>> MakeArrayFromScalar(
59
+ const Scalar& scalar, int64_t length, MemoryPool* pool = default_memory_pool());
60
+
61
+ /// \brief Create an empty Array of a given type
62
+ ///
63
+ /// The output Array will be of the given type.
64
+ ///
65
+ /// \param[in] type the data type of the empty Array
66
+ /// \param[in] pool the memory pool to allocate memory from
67
+ /// \return the resulting Array
68
+ ARROW_EXPORT
69
+ Result<std::shared_ptr<Array>> MakeEmptyArray(std::shared_ptr<DataType> type,
70
+ MemoryPool* pool = default_memory_pool());
71
+
72
+ /// @}
73
+
74
+ namespace internal {
75
+
76
+ /// \brief Swap endian of each element in a generic ArrayData
77
+ ///
78
+ /// As dictionaries are often shared between different arrays, dictionaries
79
+ /// are not swapped by this function and should be handled separately.
80
+ ///
81
+ /// \param[in] data the array contents
82
+ /// \param[in] pool the memory pool to allocate memory from
83
+ /// \return the resulting ArrayData whose elements were swapped
84
+ ARROW_EXPORT
85
+ Result<std::shared_ptr<ArrayData>> SwapEndianArrayData(
86
+ const std::shared_ptr<ArrayData>& data, MemoryPool* pool = default_memory_pool());
87
+
88
+ /// Given a number of ArrayVectors, treat each ArrayVector as the
89
+ /// chunks of a chunked array. Then rechunk each ArrayVector such that
90
+ /// all ArrayVectors are chunked identically. It is mandatory that
91
+ /// all ArrayVectors contain the same total number of elements.
92
+ ARROW_EXPORT
93
+ std::vector<ArrayVector> RechunkArraysConsistently(const std::vector<ArrayVector>&);
94
+
95
+ } // namespace internal
96
+ } // namespace arrow
venv/lib/python3.10/site-packages/pyarrow/include/arrow/compute/row/grouper.h ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #pragma once
19
+
20
+ #include <memory>
21
+ #include <vector>
22
+
23
+ #include "arrow/compute/kernel.h"
24
+ #include "arrow/datum.h"
25
+ #include "arrow/result.h"
26
+ #include "arrow/util/visibility.h"
27
+
28
+ namespace arrow {
29
+ namespace compute {
30
+
31
+ /// \brief A segment
32
+ /// A segment group is a chunk of continuous rows that have the same segment key. (For
33
+ /// example, in ordered time series processing, segment key can be "date", and a segment
34
+ /// group can be all the rows that belong to the same date.) A segment group can span
35
+ /// across multiple exec batches. A segment is a chunk of continuous rows that has the
36
+ /// same segment key within a given batch. When a segment group span cross batches, it
37
+ /// will have multiple segments. A segment never spans cross batches. The segment data
38
+ /// structure only makes sense when used along with a exec batch.
39
+ struct ARROW_EXPORT Segment {
40
+ /// \brief the offset into the batch where the segment starts
41
+ int64_t offset;
42
+ /// \brief the length of the segment
43
+ int64_t length;
44
+ /// \brief whether the segment may be extended by a next one
45
+ bool is_open;
46
+ /// \brief whether the segment extends a preceeding one
47
+ bool extends;
48
+ };
49
+
50
+ inline bool operator==(const Segment& segment1, const Segment& segment2) {
51
+ return segment1.offset == segment2.offset && segment1.length == segment2.length &&
52
+ segment1.is_open == segment2.is_open && segment1.extends == segment2.extends;
53
+ }
54
+ inline bool operator!=(const Segment& segment1, const Segment& segment2) {
55
+ return !(segment1 == segment2);
56
+ }
57
+
58
+ /// \brief a helper class to divide a batch into segments of equal values
59
+ ///
60
+ /// For example, given a batch with two rows:
61
+ ///
62
+ /// A A
63
+ /// A A
64
+ /// A B
65
+ /// A B
66
+ /// A A
67
+ ///
68
+ /// Then the batch could be divided into 3 segments. The first would be rows 0 & 1,
69
+ /// the second would be rows 2 & 3, and the third would be row 4.
70
+ ///
71
+ /// Further, a segmenter keeps track of the last value seen. This allows it to calculate
72
+ /// segments which span batches. In our above example the last batch we emit would set
73
+ /// the "open" flag, which indicates whether the segment may extend into the next batch.
74
+ ///
75
+ /// If the next call to the segmenter starts with `A A` then that segment would set the
76
+ /// "extends" flag, which indicates whether the segment continues the last open batch.
77
+ class ARROW_EXPORT RowSegmenter {
78
+ public:
79
+ virtual ~RowSegmenter() = default;
80
+
81
+ /// \brief Construct a Segmenter which segments on the specified key types
82
+ ///
83
+ /// \param[in] key_types the specified key types
84
+ /// \param[in] nullable_keys whether values of the specified keys may be null
85
+ /// \param[in] ctx the execution context to use
86
+ static Result<std::unique_ptr<RowSegmenter>> Make(
87
+ const std::vector<TypeHolder>& key_types, bool nullable_keys, ExecContext* ctx);
88
+
89
+ /// \brief Return the key types of this segmenter
90
+ virtual const std::vector<TypeHolder>& key_types() const = 0;
91
+
92
+ /// \brief Reset this segmenter
93
+ ///
94
+ /// A segmenter normally extends (see `Segment`) a segment from one batch to the next.
95
+ /// If segment-extension is undesirable, for example when each batch is processed
96
+ /// independently, then `Reset` should be invoked before processing the next batch.
97
+ virtual Status Reset() = 0;
98
+
99
+ /// \brief Get the next segment for the given batch starting from the given offset
100
+ virtual Result<Segment> GetNextSegment(const ExecSpan& batch, int64_t offset) = 0;
101
+ };
102
+
103
+ /// Consumes batches of keys and yields batches of the group ids.
104
+ class ARROW_EXPORT Grouper {
105
+ public:
106
+ virtual ~Grouper() = default;
107
+
108
+ /// Construct a Grouper which receives the specified key types
109
+ static Result<std::unique_ptr<Grouper>> Make(const std::vector<TypeHolder>& key_types,
110
+ ExecContext* ctx = default_exec_context());
111
+
112
+ /// Consume a batch of keys, producing the corresponding group ids as an integer array,
113
+ /// over a slice defined by an offset and length, which defaults to the batch length.
114
+ /// Currently only uint32 indices will be produced, eventually the bit width will only
115
+ /// be as wide as necessary.
116
+ virtual Result<Datum> Consume(const ExecSpan& batch, int64_t offset = 0,
117
+ int64_t length = -1) = 0;
118
+
119
+ /// Get current unique keys. May be called multiple times.
120
+ virtual Result<ExecBatch> GetUniques() = 0;
121
+
122
+ /// Get the current number of groups.
123
+ virtual uint32_t num_groups() const = 0;
124
+
125
+ /// \brief Assemble lists of indices of identical elements.
126
+ ///
127
+ /// \param[in] ids An unsigned, all-valid integral array which will be
128
+ /// used as grouping criteria.
129
+ /// \param[in] num_groups An upper bound for the elements of ids
130
+ /// \param[in] ctx Execution context to use during the operation
131
+ /// \return A num_groups-long ListArray where the slot at i contains a
132
+ /// list of indices where i appears in ids.
133
+ ///
134
+ /// MakeGroupings([
135
+ /// 2,
136
+ /// 2,
137
+ /// 5,
138
+ /// 5,
139
+ /// 2,
140
+ /// 3
141
+ /// ], 8) == [
142
+ /// [],
143
+ /// [],
144
+ /// [0, 1, 4],
145
+ /// [5],
146
+ /// [],
147
+ /// [2, 3],
148
+ /// [],
149
+ /// []
150
+ /// ]
151
+ static Result<std::shared_ptr<ListArray>> MakeGroupings(
152
+ const UInt32Array& ids, uint32_t num_groups,
153
+ ExecContext* ctx = default_exec_context());
154
+
155
+ /// \brief Produce a ListArray whose slots are selections of `array` which correspond to
156
+ /// the provided groupings.
157
+ ///
158
+ /// For example,
159
+ /// ApplyGroupings([
160
+ /// [],
161
+ /// [],
162
+ /// [0, 1, 4],
163
+ /// [5],
164
+ /// [],
165
+ /// [2, 3],
166
+ /// [],
167
+ /// []
168
+ /// ], [2, 2, 5, 5, 2, 3]) == [
169
+ /// [],
170
+ /// [],
171
+ /// [2, 2, 2],
172
+ /// [3],
173
+ /// [],
174
+ /// [5, 5],
175
+ /// [],
176
+ /// []
177
+ /// ]
178
+ static Result<std::shared_ptr<ListArray>> ApplyGroupings(
179
+ const ListArray& groupings, const Array& array,
180
+ ExecContext* ctx = default_exec_context());
181
+ };
182
+
183
+ } // namespace compute
184
+ } // namespace arrow
venv/lib/python3.10/site-packages/pyarrow/include/arrow/json/api.h ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #pragma once
19
+
20
+ #include "arrow/json/options.h"
21
+ #include "arrow/json/reader.h"
venv/lib/python3.10/site-packages/pyarrow/include/arrow/testing/extension_type.h ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #pragma once
19
+
20
+ #include <memory>
21
+ #include <string>
22
+ #include <vector>
23
+
24
+ #include "arrow/extension_type.h"
25
+ #include "arrow/testing/visibility.h"
26
+ #include "arrow/util/macros.h"
27
+
28
+ namespace arrow {
29
+
30
+ class ARROW_TESTING_EXPORT UuidArray : public ExtensionArray {
31
+ public:
32
+ using ExtensionArray::ExtensionArray;
33
+ };
34
+
35
+ class ARROW_TESTING_EXPORT UuidType : public ExtensionType {
36
+ public:
37
+ UuidType() : ExtensionType(fixed_size_binary(16)) {}
38
+
39
+ std::string extension_name() const override { return "uuid"; }
40
+
41
+ bool ExtensionEquals(const ExtensionType& other) const override;
42
+
43
+ std::shared_ptr<Array> MakeArray(std::shared_ptr<ArrayData> data) const override;
44
+
45
+ Result<std::shared_ptr<DataType>> Deserialize(
46
+ std::shared_ptr<DataType> storage_type,
47
+ const std::string& serialized) const override;
48
+
49
+ std::string Serialize() const override { return "uuid-serialized"; }
50
+ };
51
+
52
+ class ARROW_TESTING_EXPORT SmallintArray : public ExtensionArray {
53
+ public:
54
+ using ExtensionArray::ExtensionArray;
55
+ };
56
+
57
+ class ARROW_TESTING_EXPORT TinyintArray : public ExtensionArray {
58
+ public:
59
+ using ExtensionArray::ExtensionArray;
60
+ };
61
+
62
+ class ARROW_TESTING_EXPORT ListExtensionArray : public ExtensionArray {
63
+ public:
64
+ using ExtensionArray::ExtensionArray;
65
+ };
66
+
67
+ class ARROW_TESTING_EXPORT SmallintType : public ExtensionType {
68
+ public:
69
+ SmallintType() : ExtensionType(int16()) {}
70
+
71
+ std::string extension_name() const override { return "smallint"; }
72
+
73
+ bool ExtensionEquals(const ExtensionType& other) const override;
74
+
75
+ std::shared_ptr<Array> MakeArray(std::shared_ptr<ArrayData> data) const override;
76
+
77
+ Result<std::shared_ptr<DataType>> Deserialize(
78
+ std::shared_ptr<DataType> storage_type,
79
+ const std::string& serialized) const override;
80
+
81
+ std::string Serialize() const override { return "smallint"; }
82
+ };
83
+
84
+ class ARROW_TESTING_EXPORT TinyintType : public ExtensionType {
85
+ public:
86
+ TinyintType() : ExtensionType(int8()) {}
87
+
88
+ std::string extension_name() const override { return "tinyint"; }
89
+
90
+ bool ExtensionEquals(const ExtensionType& other) const override;
91
+
92
+ std::shared_ptr<Array> MakeArray(std::shared_ptr<ArrayData> data) const override;
93
+
94
+ Result<std::shared_ptr<DataType>> Deserialize(
95
+ std::shared_ptr<DataType> storage_type,
96
+ const std::string& serialized) const override;
97
+
98
+ std::string Serialize() const override { return "tinyint"; }
99
+ };
100
+
101
+ class ARROW_TESTING_EXPORT ListExtensionType : public ExtensionType {
102
+ public:
103
+ ListExtensionType() : ExtensionType(list(int32())) {}
104
+
105
+ std::string extension_name() const override { return "list-ext"; }
106
+
107
+ bool ExtensionEquals(const ExtensionType& other) const override;
108
+
109
+ std::shared_ptr<Array> MakeArray(std::shared_ptr<ArrayData> data) const override;
110
+
111
+ Result<std::shared_ptr<DataType>> Deserialize(
112
+ std::shared_ptr<DataType> storage_type,
113
+ const std::string& serialized) const override;
114
+
115
+ std::string Serialize() const override { return "list-ext"; }
116
+ };
117
+
118
+ class ARROW_TESTING_EXPORT DictExtensionType : public ExtensionType {
119
+ public:
120
+ DictExtensionType() : ExtensionType(dictionary(int8(), utf8())) {}
121
+
122
+ std::string extension_name() const override { return "dict-extension"; }
123
+
124
+ bool ExtensionEquals(const ExtensionType& other) const override;
125
+
126
+ std::shared_ptr<Array> MakeArray(std::shared_ptr<ArrayData> data) const override;
127
+
128
+ Result<std::shared_ptr<DataType>> Deserialize(
129
+ std::shared_ptr<DataType> storage_type,
130
+ const std::string& serialized) const override;
131
+
132
+ std::string Serialize() const override { return "dict-extension-serialized"; }
133
+ };
134
+
135
+ class ARROW_TESTING_EXPORT Complex128Array : public ExtensionArray {
136
+ public:
137
+ using ExtensionArray::ExtensionArray;
138
+ };
139
+
140
+ class ARROW_TESTING_EXPORT Complex128Type : public ExtensionType {
141
+ public:
142
+ Complex128Type()
143
+ : ExtensionType(struct_({::arrow::field("real", float64(), /*nullable=*/false),
144
+ ::arrow::field("imag", float64(), /*nullable=*/false)})) {}
145
+
146
+ std::string extension_name() const override { return "complex128"; }
147
+
148
+ bool ExtensionEquals(const ExtensionType& other) const override;
149
+
150
+ std::shared_ptr<Array> MakeArray(std::shared_ptr<ArrayData> data) const override;
151
+
152
+ Result<std::shared_ptr<DataType>> Deserialize(
153
+ std::shared_ptr<DataType> storage_type,
154
+ const std::string& serialized) const override;
155
+
156
+ std::string Serialize() const override { return "complex128-serialized"; }
157
+ };
158
+
159
+ ARROW_TESTING_EXPORT
160
+ std::shared_ptr<DataType> uuid();
161
+
162
+ ARROW_TESTING_EXPORT
163
+ std::shared_ptr<DataType> smallint();
164
+
165
+ ARROW_TESTING_EXPORT
166
+ std::shared_ptr<DataType> tinyint();
167
+
168
+ ARROW_TESTING_EXPORT
169
+ std::shared_ptr<DataType> list_extension_type();
170
+
171
+ ARROW_TESTING_EXPORT
172
+ std::shared_ptr<DataType> dict_extension_type();
173
+
174
+ ARROW_TESTING_EXPORT
175
+ std::shared_ptr<DataType> complex128();
176
+
177
+ ARROW_TESTING_EXPORT
178
+ std::shared_ptr<Array> ExampleUuid();
179
+
180
+ ARROW_TESTING_EXPORT
181
+ std::shared_ptr<Array> ExampleSmallint();
182
+
183
+ ARROW_TESTING_EXPORT
184
+ std::shared_ptr<Array> ExampleTinyint();
185
+
186
+ ARROW_TESTING_EXPORT
187
+ std::shared_ptr<Array> ExampleDictExtension();
188
+
189
+ ARROW_TESTING_EXPORT
190
+ std::shared_ptr<Array> ExampleComplex128();
191
+
192
+ ARROW_TESTING_EXPORT
193
+ std::shared_ptr<Array> MakeComplex128(const std::shared_ptr<Array>& real,
194
+ const std::shared_ptr<Array>& imag);
195
+
196
+ // A RAII class that registers an extension type on construction
197
+ // and unregisters it on destruction.
198
+ class ARROW_TESTING_EXPORT ExtensionTypeGuard {
199
+ public:
200
+ explicit ExtensionTypeGuard(const std::shared_ptr<DataType>& type);
201
+ explicit ExtensionTypeGuard(const DataTypeVector& types);
202
+ ~ExtensionTypeGuard();
203
+ ARROW_DEFAULT_MOVE_AND_ASSIGN(ExtensionTypeGuard);
204
+
205
+ protected:
206
+ ARROW_DISALLOW_COPY_AND_ASSIGN(ExtensionTypeGuard);
207
+
208
+ std::vector<std::string> extension_names_;
209
+ };
210
+
211
+ } // namespace arrow