-
Notifications
You must be signed in to change notification settings - Fork 523
/
Copy pathpadding.py
39 lines (31 loc) · 1.23 KB
/
padding.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
# 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
# pyre-strict
def pad_to(data: bytes, length: int) -> bytes:
"""Returns the input followed by enough zero bytes to become the requested length.
Args:
data: The data to pad.
length: The length of the returned data.
Returns:
The padded data.
Raises:
ValueError: If the requested length is less than the input length.
"""
if length < len(data):
raise ValueError(f"Data length {len(data)} > padded length {length}")
if length > len(data):
data = data + b"\x00" * (length - len(data))
assert len(data) == length
return data
def padding_required(offset: int, alignment: int) -> int:
"""Returns the padding required to align `offset` to `alignment`."""
remainder: int = offset % alignment
if remainder != 0:
return alignment - remainder
return 0
def aligned_size(input_size: int, alignment: int) -> int:
"""Returns input_size padded up to the next whole multiple of alignment."""
return input_size + padding_required(input_size, alignment)