vcdiff-decoder 0.1.0a1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
LICENSE ADDED
@@ -0,0 +1,204 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity granting the License.
13
+
14
+ "Legal Entity" shall mean the union of the acting entity and all
15
+ other entities that control, are controlled by, or are under common
16
+ control with that entity. For the purposes of this definition,
17
+ "control" means (i) the power, direct or indirect, to cause the
18
+ direction or management of such entity, whether by contract or
19
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
20
+ outstanding shares, or (iii) beneficial ownership of such entity.
21
+
22
+ "You" (or "Your") shall mean an individual or Legal Entity
23
+ exercising permissions granted by this License.
24
+
25
+ "Source" form shall mean the preferred form for making modifications,
26
+ including but not limited to software source code, documentation
27
+ source, and configuration files.
28
+
29
+ "Object" form shall mean any form resulting from mechanical
30
+ transformation or translation of a Source form, including but
31
+ not limited to compiled object code, generated documentation,
32
+ and conversions to other media types.
33
+
34
+ "Work" shall mean the work of authorship, whether in Source or
35
+ Object form, made available under the License, as indicated by a
36
+ copyright notice that is included in or attached to the work
37
+ (which shall not include the Communication Networks class of works).
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based upon (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other modifications
42
+ represent, as a whole, an original work of authorship. For the purposes
43
+ of this License, Derivative Works shall not include works that remain
44
+ separable from, or merely link (or bind by name) to the interfaces of,
45
+ the Work and derivative works thereof.
46
+
47
+ "Contribution" shall mean any work of authorship, including
48
+ the original version of the Work and any modifications or additions
49
+ to that Work or Derivative Works thereof, that is intentionally
50
+ submitted to Licensor for inclusion in the Work by the copyright owner
51
+ or by an individual or Legal Entity authorized to submit on behalf of
52
+ the copyright owner. For the purposes of this definition, "submitted"
53
+ means any form of electronic, verbal, or written communication sent
54
+ to the Licensor or its representatives, including but not limited to
55
+ communication on electronic mailing lists, source code control
56
+ systems, and issue tracking systems that are managed by, or on behalf
57
+ of, the Licensor for the purpose of discussing and improving the Work,
58
+ but excluding communication that is conspicuously marked or otherwise
59
+ designated in writing by the copyright owner as "Not a Contribution."
60
+
61
+ "Contributor" shall mean Licensor and any individual or Legal Entity
62
+ on behalf of whom a Contribution has been received by Licensor and
63
+ subsequently incorporated within the Work.
64
+
65
+ 2. Grant of Copyright License. Subject to the terms and conditions of
66
+ this License, each Contributor hereby grants to You a perpetual,
67
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
68
+ copyright license to use, reproduce, modify, publish, distribute,
69
+ sublicense, and/or sell copies of the Work, and to permit persons
70
+ to whom the Work is furnished to do so, subject to the following
71
+ conditions:
72
+
73
+ The above copyright notice and this permission notice shall be
74
+ included in all copies or substantial portions of the Work.
75
+
76
+ 3. Grant of Patent License. Subject to the terms and conditions of
77
+ this License, each Contributor hereby grants to You a perpetual,
78
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
79
+ (except as stated in this section) patent license to make, have made,
80
+ use, offer to sell, sell, import, and otherwise transfer the Work,
81
+ where such license applies only to those patent claims licensable
82
+ by such Contributor that are necessarily infringed by their
83
+ Contribution(s) alone or by combination of their Contribution(s)
84
+ with the Work to which such Contribution(s) was submitted. If You
85
+ institute patent litigation against any entity (including a
86
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
87
+ or a Contribution incorporated within the Work constitutes direct
88
+ or contributory patent infringement, then any patent licenses
89
+ granted to You under this License for that Work shall terminate
90
+ as of the date such litigation is filed.
91
+
92
+ 4. Redistribution. You may reproduce and distribute copies of the
93
+ Work or Derivative Works thereof in any medium, with or without
94
+ modifications, and in Source or Object form, provided that You
95
+ meet the following conditions:
96
+
97
+ (a) You must give any other recipients of the Work or
98
+ Derivative Works a copy of this License; and
99
+
100
+ (b) You must cause any modified files to carry prominent notices
101
+ stating that You changed the files; and
102
+
103
+ (c) You must retain, in the Source form of any Derivative Works
104
+ that You distribute, all copyright, trademark, patent,
105
+ attribution and other notices from the Source form of the Work,
106
+ excluding those notices that do not pertain to any part of
107
+ the Derivative Works; and
108
+
109
+ (d) If the Work includes a "NOTICE" text file as part of its
110
+ distribution, then any Derivative Works that You distribute must
111
+ include a readable copy of the attribution notices contained
112
+ within such NOTICE file, excluding those notices that do not
113
+ pertain to any part of the Derivative Works, in at least one
114
+ of the following places: within a NOTICE text file distributed
115
+ as part of the Derivative Works; within the Source form or
116
+ documentation, if provided along with the Derivative Works; or,
117
+ within a display generated by the Derivative Works, if and
118
+ wherever such third-party notices normally appear. The contents
119
+ of the NOTICE file are for informational purposes only and
120
+ do not modify the License. You may add Your own attribution
121
+ notices within Derivative Works that You distribute, alongside
122
+ or as an addendum to the NOTICE text from the Work, provided
123
+ that such additional attribution notices cannot be construed
124
+ as modifying the License.
125
+
126
+ You may add Your own copyright notice to Your modifications and
127
+ may provide additional or different license terms and conditions
128
+ for use, reproduction, or distribution of Your modifications, or
129
+ for any such Derivative Works as a whole, provided Your use,
130
+ reproduction, and distribution of the Work otherwise complies with
131
+ the conditions stated in this License.
132
+
133
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
134
+ any Contribution intentionally submitted for inclusion in the Work
135
+ by You to the Licensor shall be under the terms and conditions of
136
+ this License, without any additional terms or conditions.
137
+ Notwithstanding the above, nothing herein shall supersede or modify
138
+ the terms of any separate license agreement you may have executed
139
+ with Licensor regarding such Contributions.
140
+
141
+ 6. Trademarks. This License does not grant permission to use the trade
142
+ names, trademarks, service marks, or product names of the Licensor,
143
+ except as required for reasonable and customary use in describing the
144
+ origin of the Work and reproducing the content of the NOTICE file.
145
+
146
+ 7. Disclaimer of Warranty. Unless required by applicable law or
147
+ agreed to in writing, Licensor provides the Work (and each
148
+ Contributor provides its Contributions) on an "AS IS" BASIS,
149
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
150
+ implied, including, without limitation, any warranties or conditions
151
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
152
+ PARTICULAR PURPOSE. You are solely responsible for determining the
153
+ appropriateness of using or redistributing the Work and assume any
154
+ risks associated with Your exercise of permissions under this License.
155
+
156
+ 8. Limitation of Liability. In no event and under no legal theory,
157
+ whether in tort (including negligence), contract, or otherwise,
158
+ unless required by applicable law (such as deliberate and grossly
159
+ negligent acts) or agreed to in writing, shall any Contributor be
160
+ liable to You for damages, including any direct, indirect, special,
161
+ incidental, or consequential damages of any character arising as a
162
+ result of this License or out of the use or inability to use the
163
+ Work (including but not limited to damages for loss of goodwill,
164
+ work stoppage, computer failure or malfunction, or any and all
165
+ other commercial damages or losses), even if such Contributor
166
+ has been advised of the possibility of such damages.
167
+
168
+ 9. Accepting Warranty or Additional Liability. When redistributing
169
+ the Work or Derivative Works thereof, You may choose to offer,
170
+ and charge a fee for, acceptance of support, warranty, indemnity,
171
+ or other liability obligations and/or rights consistent with this
172
+ License. However, in accepting such obligations, You may act only
173
+ on Your own behalf and on Your sole responsibility, not on behalf
174
+ of any other Contributor, and only if You agree to indemnify,
175
+ defend, and hold each Contributor harmless for any liability
176
+ incurred by, or claims asserted against, such Contributor by reason
177
+ of your accepting any such warranty or additional liability.
178
+
179
+ END OF TERMS AND CONDITIONS
180
+
181
+ APPENDIX: How to apply the Apache License to your work.
182
+
183
+ To apply the Apache License to your work, attach the following
184
+ boilerplate notice, with the fields enclosed by brackets "[]"
185
+ replaced with your own identifying information. (Don't include
186
+ the brackets!) The text should be enclosed in the appropriate
187
+ comment syntax for the file format. We also recommend that a
188
+ file or class name and description of purpose be included on the
189
+ same page as the copyright notice for easier identification within
190
+ third-party archives.
191
+
192
+ Copyright 2025 Ably Realtime Limited
193
+
194
+ Licensed under the Apache License, Version 2.0 (the "License");
195
+ you may not use this file except in compliance with the License.
196
+ You may obtain a copy of the License at
197
+
198
+ http://www.apache.org/licenses/LICENSE-2.0
199
+
200
+ Unless required by applicable law or agreed to in writing, software
201
+ distributed under the License is distributed on an "AS IS" BASIS,
202
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
203
+ See the License for the specific language governing permissions and
204
+ limitations under the License.
README.md ADDED
@@ -0,0 +1,260 @@
1
+ # VCDIFF Python Decoder
2
+
3
+ A Python implementation of a VCDIFF (RFC 3284) decoder library and command-line tool for efficient binary differencing and compression.
4
+
5
+ ## Overview
6
+
7
+ The library provides a VCDIFF decoder that can decode delta files created according to RFC 3284 - The VCDIFF Generic Differencing and Compression Data Format. VCDIFF is a format for expressing one data stream as a variant of another data stream, commonly used for binary differencing, compression, and patch applications.
8
+
9
+ ## Features
10
+
11
+ - **Python Library**: RFC 3284 compliant VCDIFF decoding with clean, Pythonic API
12
+ - **Command-Line Tool**: Apply deltas and inspect VCDIFF file structure
13
+ - **Comprehensive Validation**: Support for all VCDIFF instruction types (ADD, COPY, RUN)
14
+ - **Address Caching**: Efficient decoding with proper address cache implementation
15
+ - **Checksum Validation**: Full Adler-32 checksum validation support
16
+ - **Robust Error Handling**: Detailed error messages for debugging malformed files
17
+ - **Extensive Testing**: 85 test cases with reference implementation validation
18
+ - **Type Safety**: Full type hints for better development experience
19
+
20
+ ## Limitations
21
+
22
+ - **Application Headers**: This implementation does not handle application header information
23
+ - **Secondary Compression**: This decoder does not support secondary compression (e.g., gzip, bzip2)
24
+ - **Compatibility**: Works with VCDIFF deltas created using `xdelta3 -e -S -A` (no secondary compression, no application header)
25
+
26
+ ## Checksum Support
27
+
28
+ - **VCD_ADLER32**: This implementation detects and parses the VCD_ADLER32 extension (bit 0x04 in window indicator)
29
+ - **Non-standard Extension**: The Adler-32 checksum is not part of RFC 3284 but is supported by some implementations
30
+ - **Validation**: Full Adler-32 checksum validation is implemented and performed during decoding
31
+ - **Display**: Checksums are displayed in the CLI output as `Adler32: 0x########`
32
+
33
+ ## Installation
34
+
35
+ ```bash
36
+ pip install vcdiff
37
+ ```
38
+
39
+ ### Development Installation
40
+
41
+ ```bash
42
+ poetry install
43
+ ```
44
+
45
+ ### Cloning with Test Suite
46
+
47
+ This repository includes the VCDIFF test suite as a git submodule. To clone the repository with all test cases:
48
+
49
+ ```bash
50
+ git clone --recursive https://github.com/ably/vcdiff-py.git
51
+ ```
52
+
53
+ If you've already cloned the repository without the submodule, initialize it:
54
+
55
+ ```bash
56
+ git submodule update --init --recursive
57
+ ```
58
+
59
+ To update the test suite submodule to the latest version:
60
+
61
+ ```bash
62
+ git submodule update --remote
63
+ ```
64
+
65
+ ## Quick Start
66
+
67
+ ### Library Usage
68
+
69
+ ```python
70
+ import vcdiff
71
+
72
+ # Read the source file
73
+ with open("original.txt", "rb") as f:
74
+ source = f.read()
75
+
76
+ # Read the VCDIFF delta file
77
+ with open("changes.vcdiff", "rb") as f:
78
+ delta_data = f.read()
79
+
80
+ # Apply the delta to reconstruct the target
81
+ try:
82
+ result = vcdiff.decode(source, delta_data)
83
+ print(f"Decoded result: {result}")
84
+ except vcdiff.VCDIFFError as e:
85
+ print(f"Decoding failed: {e}")
86
+ ```
87
+
88
+ ## API Reference
89
+
90
+ ### Core Functions
91
+
92
+ #### `vcdiff.decode(source: bytes, delta: bytes) -> bytes`
93
+
94
+ Decodes a VCDIFF delta file using the provided source data and returns the reconstructed target data.
95
+
96
+ **Parameters:**
97
+ - `source`: The original source data (may be empty for deltas that don't reference source)
98
+ - `delta`: The VCDIFF delta file data
99
+
100
+ **Returns:**
101
+ - Decoded target data as bytes
102
+
103
+ **Raises:**
104
+ - `VCDIFFError`: If decoding fails (malformed delta, checksum validation failure, etc.)
105
+
106
+ #### `vcdiff.Decoder(source: bytes)`
107
+
108
+ Creates a new decoder instance with the specified source data. Useful for decoding multiple deltas against the same source.
109
+
110
+ **Parameters:**
111
+ - `source`: The source data for decoding operations
112
+
113
+ **Returns:**
114
+ - A `Decoder` instance that can be used to decode multiple deltas
115
+
116
+ #### `decoder.decode(delta: bytes) -> bytes`
117
+
118
+ Decodes a single VCDIFF delta using the decoder's source data.
119
+
120
+ ### Error Handling
121
+
122
+ The decoder provides detailed error messages for various failure conditions:
123
+ - Invalid VCDIFF format or magic bytes
124
+ - Malformed varint encoding
125
+ - Out-of-bounds memory access attempts
126
+ - Checksum validation failures
127
+ - Truncated or corrupted delta files
128
+
129
+ **Exception Hierarchy:**
130
+ - `VCDIFFError`: Base exception for all VCDIFF-related errors
131
+ - `InvalidMagicError`: Invalid VCDIFF magic bytes
132
+ - `InvalidVersionError`: Unsupported VCDIFF version
133
+ - `InvalidFormatError`: Malformed delta structure
134
+ - `CorruptedDataError`: Data corruption detected
135
+ - `InvalidChecksumError`: Checksum validation failure
136
+
137
+ ## Testing
138
+
139
+ ### Prerequisites
140
+
141
+ For comprehensive testing, this project uses xdelta3 as a reference implementation to verify the correctness of the decoder.
142
+
143
+ #### Installing xdelta3
144
+
145
+ ##### macOS (Homebrew)
146
+ ```bash
147
+ brew install xdelta
148
+ ```
149
+
150
+ ##### Linux (Ubuntu/Debian)
151
+ ```bash
152
+ sudo apt-get install xdelta3
153
+ ```
154
+
155
+ ### Running Tests
156
+
157
+ To run the Python unit tests:
158
+
159
+ ```bash
160
+ poetry run pytest
161
+ ```
162
+
163
+ To run tests with coverage:
164
+
165
+ ```bash
166
+ poetry run pytest --cov=vcdiff tests/
167
+ ```
168
+
169
+ To run the comprehensive test suite against the VCDIFF test cases (requires submodule):
170
+
171
+ ```bash
172
+ poetry run pytest tests/test_vcdiff.py -v
173
+ ```
174
+
175
+ The test suite includes:
176
+ - **20 general positive tests**: Valid VCDIFF files that should decode successfully
177
+ - **33 targeted negative tests**: Invalid VCDIFF files that should be rejected with appropriate errors
178
+ - **32 targeted positive tests**: Specific feature validation tests
179
+ - **Total**: 85 test cases with 100% pass rate
180
+
181
+ ### Test Results
182
+ - **General Positive Tests**: 20/20 passed ✅
183
+ - **Targeted Negative Tests**: 33/33 passed ✅
184
+ - **Targeted Positive Tests**: 32/32 passed ✅
185
+
186
+ ## Contributing
187
+
188
+ Contributions are welcomed. Please follow these guidelines:
189
+
190
+ ### Getting Started
191
+
192
+ 1. Fork the repository
193
+ 2. Clone your fork with submodules: `git clone --recursive <your-fork-url>`
194
+ 3. Create a feature branch: `git checkout -b feature/your-feature-name`
195
+ 4. Make your changes
196
+ 5. Test your changes thoroughly
197
+ 6. Submit a pull request
198
+
199
+ ### Development Guidelines
200
+
201
+ - **Code Style**: Follow PEP 8 formatting (`black .` for automatic formatting)
202
+ - **Type Hints**: All new code should include proper type annotations
203
+ - **Testing**: All new features must include tests
204
+ - **Documentation**: Update documentation for any API changes
205
+ - **Commits**: Use clear, descriptive commit messages
206
+
207
+ ### Before Submitting
208
+
209
+ Ensure your contribution passes all checks:
210
+
211
+ ```bash
212
+ # Run all tests
213
+ pytest
214
+
215
+ # Format code
216
+ black .
217
+
218
+ # Lint code
219
+ flake8 vcdiff/
220
+
221
+ # Type checking
222
+ mypy vcdiff/
223
+ ```
224
+
225
+ ### Reporting Issues
226
+
227
+ When reporting bugs, please include:
228
+ - Python version
229
+ - Operating system
230
+ - Minimal reproduction case
231
+ - Expected vs actual behavior
232
+ - Sample VCDIFF files (if applicable)
233
+
234
+ ### Feature Requests
235
+
236
+ For new features, please:
237
+ - Check existing issues first
238
+ - Describe the use case
239
+ - Provide RFC 3284 references if applicable
240
+ - Consider backwards compatibility
241
+
242
+ ## Requirements
243
+
244
+ - **Python**: 3.8 or higher
245
+ - **Development Dependencies**:
246
+ - `pytest>=7.0.0`
247
+ - `pytest-cov>=4.0.0`
248
+ - `black>=22.0.0`
249
+ - `flake8>=5.0.0`
250
+ - `mypy>=1.0.0`
251
+
252
+ ## License
253
+
254
+ This project is licensed under the Apache License 2.0. See the LICENSE file for details.
255
+
256
+ ## References
257
+
258
+ - [RFC 3284: The VCDIFF Generic Differencing and Compression Data Format](https://tools.ietf.org/html/rfc3284)
259
+ - [xdelta3: VCDIFF binary diff tool](https://github.com/jmacd/xdelta)
260
+ - [Go VCDIFF Implementation](https://github.com/ably/vcdiff-go) - Algorithmically compatible sibling project
@@ -0,0 +1,43 @@
1
+ """VCDIFF Python Implementation
2
+
3
+ A Python implementation of VCDIFF (RFC 3284) delta compression format.
4
+
5
+ Copyright 2025 Ably Realtime Limited
6
+
7
+ Licensed under the Apache License, Version 2.0 (the "License");
8
+ you may not use this file except in compliance with the License.
9
+ You may obtain a copy of the License at
10
+
11
+ http://www.apache.org/licenses/LICENSE-2.0
12
+
13
+ Unless required by applicable law or agreed to in writing, software
14
+ distributed under the License is distributed on an "AS IS" BASIS,
15
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ See the License for the specific language governing permissions and
17
+ limitations under the License.
18
+ """
19
+
20
+ from .decoder import Decoder, decode, parse_delta
21
+ from .exceptions import (
22
+ VCDIFFError,
23
+ InvalidMagicError,
24
+ InvalidVersionError,
25
+ InvalidFormatError,
26
+ CorruptedDataError,
27
+ InvalidChecksumError,
28
+ )
29
+ from .types import InstructionType
30
+
31
+ __version__ = "1.0.0"
32
+ __all__ = [
33
+ "Decoder",
34
+ "decode",
35
+ "parse_delta",
36
+ "InstructionType",
37
+ "VCDIFFError",
38
+ "InvalidMagicError",
39
+ "InvalidVersionError",
40
+ "InvalidFormatError",
41
+ "CorruptedDataError",
42
+ "InvalidChecksumError",
43
+ ]
@@ -0,0 +1,111 @@
1
+ """Address cache implementation for VCDIFF COPY instructions"""
2
+
3
+ import io
4
+ from typing import BinaryIO, List
5
+
6
+ from .types import SELF_MODE, HERE_MODE
7
+ from .varint import read_varint
8
+ from .exceptions import VCDIFFError
9
+
10
+
11
+ class AddressCache:
12
+ """Manages address encoding/decoding for COPY instructions"""
13
+
14
+ def __init__(self, near_size: int, same_size: int):
15
+ """Initialize address cache with specified sizes
16
+
17
+ Args:
18
+ near_size: Size of the "near" address cache (typically 4)
19
+ same_size: Size of the "same" address cache (typically 3 * 256)
20
+ """
21
+ self.near_size = near_size
22
+ self.same_size = same_size
23
+ self.near: List[int] = [0] * near_size
24
+ self.next_near_slot = 0
25
+ self.same: List[int] = [0] * (same_size * 256)
26
+ self.address_stream: BinaryIO = io.BytesIO()
27
+
28
+ def reset(self, addresses: bytes) -> None:
29
+ """Reset the address cache for a new window
30
+
31
+ Args:
32
+ addresses: Address section data for this window
33
+ """
34
+ self.next_near_slot = 0
35
+
36
+ # Clear near cache
37
+ for i in range(len(self.near)):
38
+ self.near[i] = 0
39
+
40
+ # Clear same cache
41
+ for i in range(len(self.same)):
42
+ self.same[i] = 0
43
+
44
+ self.address_stream = io.BytesIO(addresses)
45
+
46
+ def decode_address(self, here: int, mode: int) -> int:
47
+ """Decode an address using the specified mode
48
+
49
+ Args:
50
+ here: Current position in target stream
51
+ mode: Addressing mode to use
52
+
53
+ Returns:
54
+ The decoded address
55
+
56
+ Raises:
57
+ VCDIFFError: If the addressing mode is invalid or cache is uninitialized
58
+ """
59
+ # Validate addressing mode
60
+ if mode > 8:
61
+ raise VCDIFFError(f"invalid address cache mode {mode}: valid modes are 0-8")
62
+
63
+ if mode == SELF_MODE:
64
+ addr = read_varint(self.address_stream)
65
+
66
+ elif mode == HERE_MODE:
67
+ offset = read_varint(self.address_stream)
68
+ if offset > here:
69
+ raise VCDIFFError(f"HERE mode offset {offset} exceeds current position {here}")
70
+ addr = here - offset
71
+
72
+ else:
73
+ # Near cache or same cache modes
74
+ if mode - 2 < self.near_size:
75
+ # Near cache
76
+ cache_index = mode - 2
77
+ if self.near[cache_index] == 0:
78
+ raise VCDIFFError(f"near cache slot {cache_index} is uninitialized")
79
+ offset = read_varint(self.address_stream)
80
+ addr = self.near[cache_index] + offset
81
+ else:
82
+ # Same cache
83
+ m = mode - (2 + self.near_size)
84
+ if m >= self.same_size:
85
+ raise VCDIFFError(
86
+ f"same cache mode {mode} exceeds available slots "
87
+ f"(max {2 + self.near_size + self.same_size - 1})"
88
+ )
89
+
90
+ byte_data = self.address_stream.read(1)
91
+ if not byte_data:
92
+ raise VCDIFFError("unexpected EOF while reading same cache address")
93
+
94
+ b = byte_data[0]
95
+ addr = self.same[m * 256 + b]
96
+
97
+ self.update(addr)
98
+ return addr
99
+
100
+ def update(self, address: int) -> None:
101
+ """Update the address cache with a new address
102
+
103
+ Args:
104
+ address: Address to add to the cache
105
+ """
106
+ if self.near_size > 0:
107
+ self.near[self.next_near_slot] = address
108
+ self.next_near_slot = (self.next_near_slot + 1) % self.near_size
109
+
110
+ if self.same_size > 0:
111
+ self.same[address % (self.same_size * 256)] = address
@@ -0,0 +1,43 @@
1
+ """Adler-32 checksum implementation for VCDIFF"""
2
+
3
+ from typing import Union
4
+
5
+
6
+ # Base for modulo arithmetic
7
+ ADLER32_BASE = 65521
8
+ # Number of iterations we can safely do before applying the modulo
9
+ ADLER32_NMAX = 5552
10
+
11
+
12
+ def compute_checksum(initial: int, data: Union[bytes, bytearray]) -> int:
13
+ """Compute the Adler32 checksum for the given data
14
+
15
+ Args:
16
+ initial: Initial checksum value (typically 1)
17
+ data: Data to compute checksum for
18
+
19
+ Returns:
20
+ The computed Adler32 checksum
21
+ """
22
+ if not data:
23
+ return initial
24
+
25
+ s1 = initial & 0xFFFF
26
+ s2 = (initial >> 16) & 0xFFFF
27
+
28
+ index = 0
29
+ length = len(data)
30
+
31
+ while length > 0:
32
+ k = min(length, ADLER32_NMAX)
33
+ length -= k
34
+
35
+ for i in range(k):
36
+ s1 += data[index]
37
+ s2 += s1
38
+ index += 1
39
+
40
+ s1 %= ADLER32_BASE
41
+ s2 %= ADLER32_BASE
42
+
43
+ return (s2 << 16) | s1