-
Notifications
You must be signed in to change notification settings - Fork 524
/
Copy path_cord.py
49 lines (39 loc) · 1.64 KB
/
_cord.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import io
from typing import List, Optional, Union
class Cord:
"""A `bytes`-like sequence of bytes, stored non-contiguously.
Users can use a Cord to assemble large files and data blobs using references
to and slices of other data, instead of copying and appending that data to a
`bytes` or `bytearray` object.
"""
def __init__(self, data: Optional[Union[bytes, "Cord"]] = None) -> None:
"""Initialize Cord data structure."""
self._buffers: List[bytes] = []
self._byte_size: int = 0
if data is not None:
self.append(data)
def __len__(self):
"""Number of bytes in the Cord."""
return self._byte_size
def __bytes__(self) -> bytes:
"""Return the contents of the Cord as a single `bytes` object."""
return b"".join(self._buffers)
def append(self, data: Union[bytes, "Cord"]) -> None:
"""Append a bytes or Cord to the current Cord."""
if isinstance(data, bytes):
self._buffers.append(data)
self._byte_size += len(data)
elif isinstance(data, Cord):
self._buffers.extend(data._buffers)
self._byte_size += len(data)
else:
raise TypeError(f"Can only append bytes or Cords, received {type(data)}")
def write_to_file(self, outfile: io.BufferedIOBase) -> None:
"""Write the Cord to a file."""
for item in self._buffers:
outfile.write(item)