|
1 |
| -def flip_bits(data: bytes) -> bytes: |
2 |
| - flipped_bits = bytearray(len(data)) |
| 1 | +from typing import Iterable |
| 2 | + |
3 | 3 |
|
4 |
| - for i, byte in enumerate(data): |
5 |
| - # TODO: The function call to flip_bits_in_single_byte() adds significant |
6 |
| - # overhead. While python is supposed to "inline" function calls |
7 |
| - # like this, I've yet to see any changes in runtime that indicate |
8 |
| - # this optimization is actually happening. |
9 |
| - # |
10 |
| - # The value of breaking this into separate functions is the unit |
11 |
| - # test that tests all possible bytes (0-255). This gives us |
12 |
| - # confidence that our bit-flip operation is correct. |
13 |
| - # |
14 |
| - # Remove the flip_bits_in_single_byte() function and rework the |
15 |
| - # unit tests so that we still have a high-degree of confidence |
16 |
| - # that this code is correct. |
17 |
| - # |
18 |
| - # EDIT: I believe PyPy will attempt to inline functions |
19 |
| - # automatically. I don't know that CPython makes any such |
20 |
| - # optimizations. |
21 |
| - flipped_bits[i] = flip_bits_in_single_byte(byte) |
| 4 | +def generate_flipped_bits(data: bytes) -> Iterable[int]: |
| 5 | + """ |
| 6 | + Yield bytes with the bits flipped |
22 | 7 |
|
23 |
| - return bytes(flipped_bits) |
| 8 | + :param data: The data whose bits to flip |
| 9 | + """ |
| 10 | + for byte in data: |
| 11 | + yield 255 - byte |
24 | 12 |
|
25 | 13 |
|
26 |
| -def flip_bits_in_single_byte(byte) -> int: |
27 |
| - # TODO: The operation `255 - byte` appears to be 12% faster than 255 ^ byte. |
28 |
| - # Switch the operator and thoroughly test the ransomware payload to |
29 |
| - # ensure this doesn't introduce any defects. |
30 |
| - return 255 ^ byte |
| 14 | +def flip_bits(data: bytes) -> bytes: |
| 15 | + """ |
| 16 | + Flip all bits in the given bytes |
| 17 | +
|
| 18 | + :param data: The bytes whose bits to flip |
| 19 | + :return: Bytes with the bits flipped |
| 20 | + """ |
| 21 | + return bytes(generate_flipped_bits(data)) |
0 commit comments