team-ljyzipelo

공개

단일 멤버 메모리 GZip 검증기를 추가함

작성자
시로사키 하나
작성 시각
커밋
e1ffd7bbffc358b6e53358682a93bf3ce075e892
부모
018e759
이 시점의 파일 보기

변경된 파일 9개

+709-0
추가experiments/rust-memory-gzip-reader/Cargo.lock+16-0
@@ -0,0 +1,16 @@
1추가: # This file is automatically @generated by Cargo.
2추가: # It is not intended for manual editing.
3추가: version = 4
4추가:
5추가: [[package]]
6추가: name = "zipelo-memory-gzip-reader"
7추가: version = "0.1.0"
8추가: dependencies = [
9추가: "zlib-rs",
10추가: ]
11추가:
12추가: [[package]]
13추가: name = "zlib-rs"
14추가: version = "0.6.8"
15추가: source = "registry+https://github.com/rust-lang/crates.io-index"
16추가: checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112"
추가experiments/rust-memory-gzip-reader/Cargo.toml+14-0
@@ -0,0 +1,14 @@
1추가: [package]
2추가: name = "zipelo-memory-gzip-reader"
3추가: version = "0.1.0"
4추가: edition = "2024"
5추가: license = "MIT"
6추가: publish = false
7추가:
8추가: [lib]
9추가: path = "src/lib.rs"
10추가:
11추가: [dependencies]
12추가: zlib-rs = { version = "=0.6.8", default-features = false, features = ["rust-allocator"] }
13추가:
14추가: [workspace]
추가experiments/rust-memory-gzip-reader/LICENSE+21-0
@@ -0,0 +1,21 @@
1추가: MIT License
2추가:
3추가: Copyright (c) 2026 Team-LJY contributors
4추가:
5추가: Permission is hereby granted, free of charge, to any person obtaining a copy
6추가: of this software and associated documentation files (the "Software"), to deal
7추가: in the Software without restriction, including without limitation the rights
8추가: to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9추가: copies of the Software, and to permit persons to whom the Software is
10추가: furnished to do so, subject to the following conditions:
11추가:
12추가: The above copyright notice and this permission notice shall be included in all
13추가: copies or substantial portions of the Software.
14추가:
15추가: THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16추가: IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17추가: FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18추가: AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19추가: LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20추가: OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21추가: SOFTWARE.
추가experiments/rust-memory-gzip-reader/SHA256SUMS+8-0
@@ -0,0 +1,8 @@
1추가: 511197f27b89d37c86f82ae1e8dda4229a3e5082ede9274efe8480df6e650d24 Cargo.lock
2추가: ae76aededbb85cdd6c9227b4c06a1c8fef1bb7f203f1703e787b68f30ccfab6a Cargo.toml
3추가: 0714945e52a4d5b560c02c9a18478519f8c4e2572cbf87bd6d52adcfb2b63c62 LICENSE
4추가: 655ad3bee8c41a593c2b00cbb0a12be11e7246c41dda00319c223dd3f904910e THIRD-PARTY-NOTICES.txt
5추가: 1346c0b6f0ce5221acb9aef5067b0169e08ea6752f4db41a8b9c36b10ef9b43b contract.json
6추가: 3f71220451f8cd55dafdb6e6ae901572ec7bbe1be9c93d78953b44244aec6b07 dependencies.json
7추가: b0d0b891a048712baba2038b8439d809a0359638f390b806f88496733753d61c src/budget.rs
8추가: a865a114fdb9d79b66226387b9f0e3fa601aad29cfe65ab443c946d6cbd74062 src/lib.rs
추가experiments/rust-memory-gzip-reader/THIRD-PARTY-NOTICES.txt+27-0
@@ -0,0 +1,27 @@
1추가: zlib-rs 0.6.8
2추가: License: Zlib
3추가: Source: https://crates.io/crates/zlib-rs/0.6.8
4추가: Repository: https://github.com/trifectatechfoundation/zlib-rs
5추가: Archive SHA256: b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112
6추가: LICENSE SHA256: e72111c52b7d96ebe25348dee19f0744f444d3c95ae6b1ecb6ccaecc5bce05ba
7추가: The LICENSE bytes below are preserved verbatim.
8추가:
9추가: (C) 2024 Trifecta Tech Foundation
10추가:
11추가: This software is provided 'as-is', without any express or implied
12추가: warranty. In no event will the authors be held liable for any damages
13추가: arising from the use of this software.
14추가:
15추가: Permission is granted to anyone to use this software for any purpose,
16추가: including commercial applications, and to alter it and redistribute it
17추가: freely, subject to the following restrictions:
18추가:
19추가: 1. The origin of this software must not be misrepresented; you must not
20추가: claim that you wrote the original software. If you use this software
21추가: in a product, an acknowledgment in the product documentation would be
22추가: appreciated but is not required.
23추가:
24추가: 2. Altered source versions must be plainly marked as such, and must not be
25추가: misrepresented as being the original software.
26추가:
27추가: 3. This notice may not be removed or altered from any source distribution.
추가experiments/rust-memory-gzip-reader/contract.json+137-0
@@ -0,0 +1,137 @@
1추가: {
2추가: "schema_version": 1,
3추가: "base_head": "018e7593ecb2b3a7ae0bc17a440ecf2c0de8b4dd",
4추가: "csharp_reference": {
5추가: "head": "f56324c98468076c57e18255ac1661a66fe26f84",
6추가: "pr": 18,
7추가: "paths": [
8추가: "tests/gzip-history-integration-probe/BoundaryProbe.cs",
9추가: "tests/gzip-history-integration-probe/PendingValidation.cs",
10추가: "tests/gzip-history-integration-probe/contract.json"
11추가: ]
12추가: },
13추가: "provenance": {
14추가: "implementation": "New Rust implementation of the C# boundary/budget behavior. No source inclusion or dependency on another candidate. Root MIT license applies.",
15추가: "api_reference": "PR33 90eafe0b4dcda137e90c78685b64abefa6f33357 experiments/rust-typed-deflate/src/typed_deflate.rs and cached zlib-rs 0.6.8 public API",
16추가: "differences_from_pr33": [
17추가: "No ZIP/JSON/base64, crc32fast, cfg-if, path source inclusion, provisional sink or expected ZIP size",
18추가: "Actual failed decode output charged before backend error propagation",
19추가: "No 131072-call ceiling; continuation requires consumed input or produced output"
20추가: ]
21추가: },
22추가: "api": {
23추가: "read": "read(Request { input: Box<[u8]>, selected: bool }, &mut Budget, FnMut(Checkpoint) -> Result<(), Stop<E>>) -> Result<Completed, Error<E>>",
24추가: "budget": "Budget::new(Limits), limits(), usage(), elapsed(). Caller retains the same mutable Budget across retries; no reset API. Instant starts at construction.",
25추가: "completed": "Boundary { header_bytes, deflate_bytes, read_ahead_bytes, inflated_bytes, crc32, member_bytes, offered_bytes }; bytes: Option<Vec<u8>>; cumulative usage snapshot",
26추가: "unselected": "None output still fully decodes and verifies. Some(empty Vec) distinguishes selected empty payload.",
27추가: "ownership": "Input consumed by ownership. Output stays private until successful final check after decoder drop. Failure drops all temporary output but retains budget charges. No early sink or user-controlled decoder injection."
28추가: },
29추가: "format": [
30추가: "Single GZip member only; exact magic, CM=8, reserved flags clear",
31추가: "Consume MTIME/XFL/OS and FTEXT without interpreting them",
32추가: "FEXTRA u16 length and exact bytes; FNAME/FCOMMENT terminated byte fields, never paths or Unicode strings",
33추가: "FHCRC lower 16 bits of zlib-rs CRC32 over preceding header bytes",
34추가: "Raw Inflate::new(false,15); typed Status and InflateError; no dictionary supplied",
35추가: "Actual StreamEnd consumed-input position defines trailer. Re-read read-ahead without duplicate input charge",
36추가: "Trailer little-endian CRC32 then ISIZE modulo 2^32 then exact EOF; reject concatenated members and any trailing bytes including zero"
37추가: ],
38추가: "limits": {
39추가: "input_per_call": 16777216,
40추가: "processed_cumulative": 134217728,
41추가: "selected_output_cumulative": 16777216,
42추가: "metadata_cumulative": 1048576,
43추가: "duration_seconds": 300,
44추가: "chunk_bytes": 65536,
45추가: "caller_limits": "Clamp to hard caps. u64 byte limits allow zero; zero duration invalid. Caller may only lower effective caps.",
46추가: "zero": "Input=0 rejects nonempty before parsing; metadata=0 rejects first header attempt; processed=0 rejects first input charge; output=0 still allows unselected decoding and selected empty payload.",
47추가: "metadata": "Each attempted header byte is charged, including FHCRC; trailer excluded. Metadata charge can survive truncated input.",
48추가: "processed": "Header input + bytes offered to decoder including read-ahead + any fresh trailer bytes + all decoded bytes, selected or not. Input high-water is per call; processed survives retries.",
49추가: "failed_output": "Validate total_out delta <=65536 then charge actual delta even on decoder Err. A decoded overrun remains in usage and future checks reject. Input/output/metadata charges that would exceed limits fail before increment.",
50추가: "allocation": "Charge selected output before try_reserve_exact and append; failure retains charge. Buffer size <=65536. No total allocator-memory or panic/OOM recovery guarantee."
51추가: },
52추가: "precedence": [
53추가: "Start checkpoint (Cancelled/Deadline/Callback(E)) then shared processed/time check then input-length cap",
54추가: "Ordinary header check then metadata charge then byte check/EOF/input charge. FHCRC metadata charge precedes byte check as in C#",
55추가: "BeforeInflate checkpoint/time check; new offered-input charge before decoder call",
56추가: "After decoder: invalid total_out delta => Boundary; valid actual decoded charge overrun => Budget; backend Err => Backend(original InflateError); only successful backend return reaches AfterInflate checkpoint/time check",
57추가: "Successful call then consumed-input validation, CRC update, selected-output charge/reserve/copy, AfterOutput checkpoint",
58추가: "StreamEnd checks, trailer CRC mismatch => Crc before Size before TrailingData; final decoder drop then BeforeReturn checkpoint/time check",
59추가: "Any callback Stop::Callback(E) returned unchanged. No later checkpoints after an error. Returned first error retained through normal decoder drop."
60추가: ],
61추가: "progress": {
62추가: "rule": "Each continued decoder call must consume >0 input or produce >0 output. Refill at exhausted window only, <=65536 bytes. Empty-input drain allowed for pending output. Zero progress without StreamEnd becomes Truncated if input exhausted, otherwise NoProgress.",
63추가: "finite": "Input <=16MiB; all output charged against cumulative128MiB (at most one chunk observed overrun). No repeated zero-progress calls and no arbitrary call-count ceiling.",
64추가: "limitations": "Typed backend has no IsNeedingInput property; zero-progress classification uses supplied/consumed positions. Exact SharpZipLib malformed-stream consumption and failure-cost identity is not claimed."
65추가: },
66추가: "checkpoint": {
67추가: "stages": [
68추가: "Start",
69추가: "Header",
70추가: "BeforeInflate",
71추가: "AfterInflate",
72추가: "AfterOutput",
73추가: "Trailer",
74추가: "BeforeReturn"
75추가: ],
76추가: "ordering": "Callback first, then Instant/processed check. Stop::Cancelled takes precedence over elapsed deadline at that check. Callback failure retains E; injected Stop::Deadline maps Budget.",
77추가: "granularity": "Header checked per byte, raw input and output at <=64KiB, after output and after decoder cleanup. Callback time counts; callback/codec cannot be forcibly interrupted.",
78추가: "observability": "Checkpoints expose usage, not provisional output. Stage calls are Rust API seams, not a claim of identical C# token poll counts."
79추가: },
80추가: "errors": {
81추가: "reader": [
82추가: "InvalidRequest",
83추가: "Header",
84추가: "Truncated",
85추가: "Boundary",
86추가: "Crc",
87추가: "Size",
88추가: "TrailingData",
89추가: "Budget",
90추가: "NoProgress",
91추가: "Allocation",
92추가: "Cancelled"
93추가: ],
94추가: "backend": "InflateError re-export, preserved NeedDict { dict_id }, StreamError, DataError, MemError",
95추가: "callback": "Original generic E preserved; no message matching, catch/default or blanket unwind handling",
96추가: "cleanup": "zlib-rs Drop runs decoder cleanup but does not expose its return status. No external sink Dispose in this API; no claim that cleanup failures, panic or OOM are recovered."
97추가: },
98추가: "tests": {
99추가: "status": "No regression execution in this implementation task. Separate regression owner to be assigned after fixed source head.",
100추가: "preserve": [
101추가: "Normal/header options/FHCRC/CRC/ISIZE/truncation/trailing member rejection",
102추가: "Budget exact boundaries/zero limits/failure charging/shared retries/cancellation/deadline/final-result discard"
103추가: ],
104추가: "adapt": [
105추가: "Partial feed and drain become adapter behavior cases, no arbitrary feed size public argument",
106추가: "Sink cancellation becomes checkpoint cancellation; HashSink becomes test hashing of Completed bytes",
107추가: "SharpZipLib backend failure becomes original typed zlib-rs error with separately tested counter/precedence behavior"
108추가: ],
109추가: "not_directly_applicable": [
110추가: "Mutable backing array with owned Box input",
111추가: "External sink/Dispose exception and injected inflater counter corruption",
112추가: "C# assembly identity, CLI, filesystem/Stream I/O"
113추가: ],
114추가: "not_claimed": [
115추가: "Existing C# 184+162 test counts or equivalent passes",
116추가: "Independent execution, Windows, full-product acceptance, performance or vulnerability-free dependency"
117추가: ]
118추가: },
119추가: "out_of_scope": [
120추가: "tar.gz/TAR interpretation",
121추가: "multiple members",
122추가: "disk publishing",
123추가: "worker/IPC/UI",
124추가: "encryption",
125추가: "main merge",
126추가: "C# deletion"
127추가: ],
128추가: "validation": {
129추가: "toolchain": "Rust/Cargo 1.99.1",
130추가: "build": "cargo +1.99.1 build --lib --locked --offline --manifest-path experiments/rust-memory-gzip-reader/Cargo.toml",
131추가: "target_directory": "tests/memory-gzip-build/target",
132추가: "build_exit": 0,
133추가: "regression_tests_executed": 0,
134추가: "format": "cargo +1.99.1 fmt --manifest-path experiments/rust-memory-gzip-reader/Cargo.toml",
135추가: "security_advisories": "Not checked in this implementation pass; no current advisory or vulnerability-free claim"
136추가: }
137추가: }
추가experiments/rust-memory-gzip-reader/dependencies.json+35-0
@@ -0,0 +1,35 @@
1추가: {
2추가: "direct": [
3추가: {
4추가: "name": "zlib-rs",
5추가: "version": "0.6.8",
6추가: "default_features": false,
7추가: "features": [
8추가: "rust-allocator"
9추가: ],
10추가: "license": "Zlib",
11추가: "source": "registry+https://github.com/rust-lang/crates.io-index",
12추가: "archive_sha256": "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112",
13추가: "verified_archive_source_files": {
14추가: "Cargo.toml": "85e89ef7d52508403f921caba72bb16545815e928083b6ab4ffecb8bf65c96b6",
15추가: "LICENSE": "e72111c52b7d96ebe25348dee19f0744f444d3c95ae6b1ecb6ccaecc5bce05ba",
16추가: "src/lib.rs": "30eeb6cf4b939db03130340b4ed83432c1710085445dfab12c820b8acc90708f",
17추가: "src/stable.rs": "ba6f0d5ce10aaa274b30103bc86c0766068b2dc62d7faafced1df8c782c0c703",
18추가: "src/crc32.rs": "2e5fde22a4fc26bd7a9e87a8716c7c7a381d8ee2da8763e8440c8cec0049681b"
19추가: }
20추가: }
21추가: ],
22추가: "selected_external_transitive": [],
23추가: "selected_features": [
24추가: "zlib-rs/rust-allocator"
25추가: ],
26추가: "not_selected": [
27추가: "std",
28추가: "c-allocator",
29추가: "arbitrary",
30추가: "quickcheck",
31추가: "__internal-api"
32추가: ],
33추가: "lock_external_packages": 1,
34추가: "notice_scope": "Single selected external package for this candidate, not final all-platform product distribution notices."
35추가: }
추가experiments/rust-memory-gzip-reader/src/budget.rs+120-0
@@ -0,0 +1,120 @@
1추가: use crate::Failure;
2추가: use std::time::{Duration, Instant};
3추가:
4추가: pub const CHUNK_SIZE: usize = 65_536;
5추가:
6추가: #[derive(Clone, Copy, Debug)]
7추가: pub struct Limits {
8추가: pub input: u64,
9추가: pub processed: u64,
10추가: pub output: u64,
11추가: pub metadata: u64,
12추가: pub duration: Duration,
13추가: }
14추가:
15추가: impl Default for Limits {
16추가: fn default() -> Self {
17추가: Self {
18추가: input: 16 * 1024 * 1024,
19추가: processed: 128 * 1024 * 1024,
20추가: output: 16 * 1024 * 1024,
21추가: metadata: 1024 * 1024,
22추가: duration: Duration::from_secs(300),
23추가: }
24추가: }
25추가: }
26추가:
27추가: #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
28추가: pub struct Usage {
29추가: pub processed: u64,
30추가: pub output: u64,
31추가: pub metadata: u64,
32추가: }
33추가:
34추가: #[derive(Debug)]
35추가: pub struct Budget {
36추가: limits: Limits,
37추가: usage: Usage,
38추가: started: Instant,
39추가: }
40추가:
41추가: impl Budget {
42추가: pub fn new(requested: Limits) -> Result<Self, Failure> {
43추가: if requested.duration.is_zero() {
44추가: return Err(Failure::InvalidRequest);
45추가: }
46추가: let cap = Limits::default();
47추가: Ok(Self {
48추가: limits: Limits {
49추가: input: requested.input.min(cap.input),
50추가: processed: requested.processed.min(cap.processed),
51추가: output: requested.output.min(cap.output),
52추가: metadata: requested.metadata.min(cap.metadata),
53추가: duration: requested.duration.min(cap.duration),
54추가: },
55추가: usage: Usage::default(),
56추가: started: Instant::now(),
57추가: })
58추가: }
59추가:
60추가: pub fn limits(&self) -> Limits {
61추가: self.limits
62추가: }
63추가: pub fn usage(&self) -> Usage {
64추가: self.usage
65추가: }
66추가: pub fn elapsed(&self) -> Duration {
67추가: self.started.elapsed()
68추가: }
69추가:
70추가: pub(crate) fn check(&self) -> Result<(), Failure> {
71추가: if self.usage.processed > self.limits.processed || self.elapsed() >= self.limits.duration {
72추가: return Err(Failure::Budget);
73추가: }
74추가: Ok(())
75추가: }
76추가:
77추가: pub(crate) fn input(&mut self, count: usize) -> Result<(), Failure> {
78추가: charge(
79추가: &mut self.usage.processed,
80추가: count as u64,
81추가: self.limits.processed,
82추가: )
83추가: }
84추가:
85추가: pub(crate) fn decoded(&mut self, count: u64) -> Result<(), Failure> {
86추가: if count > CHUNK_SIZE as u64 {
87추가: return Err(Failure::Boundary);
88추가: }
89추가: if self.usage.processed > self.limits.processed {
90추가: return Err(Failure::Budget);
91추가: }
92추가: // 이미 생성된 출력은 한도 초과 시에도 누적함.
93추가: self.usage.processed = self
94추가: .usage
95추가: .processed
96추가: .checked_add(count)
97추가: .ok_or(Failure::Boundary)?;
98추가: if self.usage.processed > self.limits.processed {
99추가: return Err(Failure::Budget);
100추가: }
101추가: Ok(())
102추가: }
103추가:
104추가: pub(crate) fn output(&mut self, count: usize) -> Result<(), Failure> {
105추가: charge(&mut self.usage.output, count as u64, self.limits.output)
106추가: }
107추가:
108추가: pub(crate) fn metadata(&mut self) -> Result<(), Failure> {
109추가: charge(&mut self.usage.metadata, 1, self.limits.metadata)
110추가: }
111추가: }
112추가:
113추가: fn charge(value: &mut u64, count: u64, limit: u64) -> Result<(), Failure> {
114추가: let next = value.checked_add(count).ok_or(Failure::Budget)?;
115추가: if next > limit {
116추가: return Err(Failure::Budget);
117추가: }
118추가: *value = next;
119추가: Ok(())
120추가: }
추가experiments/rust-memory-gzip-reader/src/lib.rs+331-0
@@ -0,0 +1,331 @@
1추가: #![forbid(unsafe_code)]
2추가:
3추가: mod budget;
4추가: pub use budget::{Budget, CHUNK_SIZE, Limits, Usage};
5추가: pub use zlib_rs::InflateError;
6추가: use zlib_rs::{Inflate, InflateFlush, Status, crc32::crc32};
7추가:
8추가: #[derive(Clone, Copy, Debug, PartialEq, Eq)]
9추가: pub enum Failure {
10추가: InvalidRequest,
11추가: Header,
12추가: Truncated,
13추가: Boundary,
14추가: Crc,
15추가: Size,
16추가: TrailingData,
17추가: Budget,
18추가: NoProgress,
19추가: Allocation,
20추가: Cancelled,
21추가: }
22추가:
23추가: #[derive(Debug)]
24추가: pub enum Error<E> {
25추가: Reader(Failure),
26추가: Backend(InflateError),
27추가: Callback(E),
28추가: }
29추가:
30추가: impl<E> From<Failure> for Error<E> {
31추가: fn from(value: Failure) -> Self {
32추가: Self::Reader(value)
33추가: }
34추가: }
35추가:
36추가: #[derive(Debug)]
37추가: pub enum Stop<E> {
38추가: Cancelled,
39추가: Deadline,
40추가: Callback(E),
41추가: }
42추가:
43추가: #[derive(Clone, Copy, Debug, PartialEq, Eq)]
44추가: pub enum Stage {
45추가: Start,
46추가: Header,
47추가: BeforeInflate,
48추가: AfterInflate,
49추가: AfterOutput,
50추가: Trailer,
51추가: BeforeReturn,
52추가: }
53추가:
54추가: #[derive(Clone, Copy, Debug, PartialEq, Eq)]
55추가: pub struct Checkpoint {
56추가: pub stage: Stage,
57추가: pub usage: Usage,
58추가: }
59추가:
60추가: pub struct Request {
61추가: pub input: Box<[u8]>,
62추가: pub selected: bool,
63추가: }
64추가:
65추가: #[derive(Clone, Copy, Debug, PartialEq, Eq)]
66추가: pub struct Boundary {
67추가: pub header_bytes: usize,
68추가: pub deflate_bytes: u64,
69추가: pub read_ahead_bytes: usize,
70추가: pub inflated_bytes: u64,
71추가: pub crc32: u32,
72추가: pub member_bytes: usize,
73추가: pub offered_bytes: u64,
74추가: }
75추가:
76추가: #[derive(Debug)]
77추가: pub struct Completed {
78추가: pub boundary: Boundary,
79추가: pub bytes: Option<Vec<u8>>,
80추가: pub usage: Usage,
81추가: }
82추가:
83추가: pub fn read<E>(
84추가: request: Request,
85추가: budget: &mut Budget,
86추가: mut checkpoint: impl FnMut(Checkpoint) -> Result<(), Stop<E>>,
87추가: ) -> Result<Completed, Error<E>> {
88추가: let mut context = Context {
89추가: budget,
90추가: checkpoint: &mut checkpoint,
91추가: };
92추가: context.check(Stage::Start)?;
93추가: if request.input.len() as u64 > context.budget.limits().input {
94추가: return Err(Failure::Budget.into());
95추가: }
96추가: let mut cursor = Cursor {
97추가: input: &request.input,
98추가: position: 0,
99추가: high_water: 0,
100추가: };
101추가: let header_bytes = header(&mut cursor, &mut context)?;
102추가: let mut bytes = request.selected.then(Vec::new);
103추가: let boundary = {
104추가: let mut decoder = Inflate::new(false, 15);
105추가: decode(
106추가: &mut decoder,
107추가: &mut cursor,
108추가: &mut context,
109추가: header_bytes,
110추가: &mut bytes,
111추가: )?
112추가: };
113추가: // decoder 정리 이후에만 완료 결과를 노출함.
114추가: context.check(Stage::BeforeReturn)?;
115추가: Ok(Completed {
116추가: boundary,
117추가: bytes,
118추가: usage: context.budget.usage(),
119추가: })
120추가: }
121추가:
122추가: struct Context<'a, F> {
123추가: budget: &'a mut Budget,
124추가: checkpoint: &'a mut F,
125추가: }
126추가:
127추가: impl<E, F: FnMut(Checkpoint) -> Result<(), Stop<E>>> Context<'_, F> {
128추가: fn check(&mut self, stage: Stage) -> Result<(), Error<E>> {
129추가: (self.checkpoint)(Checkpoint {
130추가: stage,
131추가: usage: self.budget.usage(),
132추가: })
133추가: .map_err(|stop| match stop {
134추가: Stop::Cancelled => Error::Reader(Failure::Cancelled),
135추가: Stop::Deadline => Error::Reader(Failure::Budget),
136추가: Stop::Callback(error) => Error::Callback(error),
137추가: })?;
138추가: self.budget.check()?;
139추가: Ok(())
140추가: }
141추가: }
142추가:
143추가: struct Cursor<'a> {
144추가: input: &'a [u8],
145추가: position: usize,
146추가: high_water: usize,
147추가: }
148추가:
149추가: impl Cursor<'_> {
150추가: fn account(&mut self, end: usize, budget: &mut Budget) -> Result<(), Failure> {
151추가: if end > self.input.len() {
152추가: return Err(Failure::Boundary);
153추가: }
154추가: if end > self.high_water {
155추가: budget.input(end - self.high_water)?;
156추가: self.high_water = end;
157추가: }
158추가: Ok(())
159추가: }
160추가:
161추가: fn byte<E, F: FnMut(Checkpoint) -> Result<(), Stop<E>>>(
162추가: &mut self,
163추가: context: &mut Context<'_, F>,
164추가: stage: Stage,
165추가: ) -> Result<u8, Error<E>> {
166추가: context.check(stage)?;
167추가: let value = *self.input.get(self.position).ok_or(Failure::Truncated)?;
168추가: let end = self.position.checked_add(1).ok_or(Failure::Boundary)?;
169추가: self.account(end, context.budget)?;
170추가: self.position = end;
171추가: Ok(value)
172추가: }
173추가: }
174추가:
175추가: fn header<E, F: FnMut(Checkpoint) -> Result<(), Stop<E>>>(
176추가: cursor: &mut Cursor<'_>,
177추가: context: &mut Context<'_, F>,
178추가: ) -> Result<usize, Error<E>> {
179추가: let mut crc = 0;
180추가: fn next<E, F: FnMut(Checkpoint) -> Result<(), Stop<E>>>(
181추가: cursor: &mut Cursor<'_>,
182추가: context: &mut Context<'_, F>,
183추가: crc: &mut u32,
184추가: ) -> Result<u8, Error<E>> {
185추가: context.check(Stage::Header)?;
186추가: context.budget.metadata()?;
187추가: let value = cursor.byte(context, Stage::Header)?;
188추가: *crc = crc32(*crc, &[value]);
189추가: Ok(value)
190추가: }
191추가: for expected in [0x1f, 0x8b, 8] {
192추가: if next(cursor, context, &mut crc)? != expected {
193추가: return Err(Failure::Header.into());
194추가: }
195추가: }
196추가: let flags = next(cursor, context, &mut crc)?;
197추가: if flags & 0xe0 != 0 {
198추가: return Err(Failure::Header.into());
199추가: }
200추가: for _ in 0..6 {
201추가: next(cursor, context, &mut crc)?;
202추가: }
203추가: if flags & 4 != 0 {
204추가: let low = next(cursor, context, &mut crc)?;
205추가: let high = next(cursor, context, &mut crc)?;
206추가: for _ in 0..u16::from_le_bytes([low, high]) {
207추가: next(cursor, context, &mut crc)?;
208추가: }
209추가: }
210추가: for mask in [8, 16] {
211추가: if flags & mask != 0 {
212추가: while next(cursor, context, &mut crc)? != 0 {}
213추가: }
214추가: }
215추가: if flags & 2 != 0 {
216추가: context.budget.metadata()?;
217추가: let low = cursor.byte(context, Stage::Header)?;
218추가: context.budget.metadata()?;
219추가: let high = cursor.byte(context, Stage::Header)?;
220추가: if u16::from_le_bytes([low, high]) != crc as u16 {
221추가: return Err(Failure::Header.into());
222추가: }
223추가: }
224추가: Ok(cursor.position)
225추가: }
226추가:
227추가: fn decode<E, F: FnMut(Checkpoint) -> Result<(), Stop<E>>>(
228추가: decoder: &mut Inflate,
229추가: cursor: &mut Cursor<'_>,
230추가: context: &mut Context<'_, F>,
231추가: header_bytes: usize,
232추가: bytes: &mut Option<Vec<u8>>,
233추가: ) -> Result<Boundary, Error<E>> {
234추가: let mut output = [0; CHUNK_SIZE];
235추가: let mut consumed_position = header_bytes;
236추가: let mut offered_end = header_bytes;
237추가: let mut crc = 0;
238추가: loop {
239추가: context.check(Stage::BeforeInflate)?;
240추가: if consumed_position == offered_end && offered_end < cursor.input.len() {
241추가: offered_end = offered_end
242추가: .checked_add(CHUNK_SIZE)
243추가: .ok_or(Failure::Boundary)?
244추가: .min(cursor.input.len());
245추가: cursor.account(offered_end, context.budget)?;
246추가: cursor.position = offered_end;
247추가: }
248추가: let before_in = decoder.total_in();
249추가: let before_out = decoder.total_out();
250추가: let result = decoder.decompress(
251추가: &cursor.input[consumed_position..offered_end],
252추가: &mut output,
253추가: InflateFlush::NoFlush,
254추가: );
255추가: // backend 오류보다 실제 출력 증가분 검증과 과금을 먼저 수행함.
256추가: let produced = decoder
257추가: .total_out()
258추가: .checked_sub(before_out)
259추가: .ok_or(Failure::Boundary)?;
260추가: context.budget.decoded(produced)?;
261추가: let status = result.map_err(Error::Backend)?;
262추가: context.check(Stage::AfterInflate)?;
263추가: let consumed = decoder
264추가: .total_in()
265추가: .checked_sub(before_in)
266추가: .ok_or(Failure::Boundary)?;
267추가: let consumed = usize::try_from(consumed).map_err(|_| Failure::Boundary)?;
268추가: if consumed > offered_end - consumed_position {
269추가: return Err(Failure::Boundary.into());
270추가: }
271추가: consumed_position = consumed_position
272추가: .checked_add(consumed)
273추가: .ok_or(Failure::Boundary)?;
274추가: if decoder.total_in() != (consumed_position - header_bytes) as u64 {
275추가: return Err(Failure::Boundary.into());
276추가: }
277추가: let produced = produced as usize;
278추가: if produced != 0 {
279추가: crc = crc32(crc, &output[..produced]);
280추가: if let Some(saved) = bytes {
281추가: context.budget.output(produced)?;
282추가: saved
283추가: .try_reserve_exact(produced)
284추가: .map_err(|_| Failure::Allocation)?;
285추가: saved.extend_from_slice(&output[..produced]);
286추가: context.check(Stage::AfterOutput)?;
287추가: }
288추가: }
289추가: if status == Status::StreamEnd {
290추가: break;
291추가: }
292추가: if consumed == 0 && produced == 0 {
293추가: return Err(if consumed_position == cursor.input.len() {
294추가: Failure::Truncated
295추가: } else {
296추가: Failure::NoProgress
297추가: }
298추가: .into());
299추가: }
300추가: }
301추가: context.check(Stage::Trailer)?;
302추가: let read_ahead_bytes = offered_end
303추가: .checked_sub(consumed_position)
304추가: .ok_or(Failure::Boundary)?;
305추가: cursor.position = consumed_position;
306추가: let mut trailer = [0; 8];
307추가: for byte in &mut trailer {
308추가: *byte = cursor.byte(context, Stage::Trailer)?;
309추가: }
310추가: let expected_crc = u32::from_le_bytes([trailer[0], trailer[1], trailer[2], trailer[3]]);
311추가: let expected_size = u32::from_le_bytes([trailer[4], trailer[5], trailer[6], trailer[7]]);
312추가: if expected_crc != crc {
313추가: return Err(Failure::Crc.into());
314추가: }
315추가: if expected_size != decoder.total_out() as u32 {
316추가: return Err(Failure::Size.into());
317추가: }
318추가: if cursor.position != cursor.input.len() {
319추가: return Err(Failure::TrailingData.into());
320추가: }
321추가: context.check(Stage::Trailer)?;
322추가: Ok(Boundary {
323추가: header_bytes,
324추가: deflate_bytes: decoder.total_in(),
325추가: read_ahead_bytes,
326추가: inflated_bytes: decoder.total_out(),
327추가: crc32: crc,
328추가: member_bytes: cursor.position,
329추가: offered_bytes: (offered_end - header_bytes) as u64,
330추가: })
331추가: }