qubit_io_binary/ext/zig_zag_write_ext.rs
1// =============================================================================
2// Copyright (c) 2026 Haixing Hu.
3//
4// SPDX-License-Identifier: Apache-2.0
5//
6// Licensed under the Apache License, Version 2.0.
7// =============================================================================
8
9use std::io::Result;
10
11use crate::util::{
12 encode_infallible_unchecked,
13 write_all,
14};
15use qubit_codec_binary::{
16 NonStrict,
17 ZigZagCodec,
18};
19use qubit_io::Output;
20
21macro_rules! write_zig_zag_value {
22 ($writer:expr, $value:expr, $ty:ty) => {
23 write_zig_zag::<
24 { ZigZagCodec::<$ty, NonStrict>::MAX_ENCODE_UNITS_PER_VALUE },
25 _,
26 _,
27 _,
28 >($writer, $value, |bytes, value| {
29 type Codec = ZigZagCodec<$ty, NonStrict>;
30 // SAFETY: The local buffer is exactly the codec's maximum buffer
31 // length.
32 unsafe { encode_infallible_unchecked::<Codec>(value, bytes, 0) }
33 })
34 };
35}
36
37/// Extension methods for writing ZigZag + unsigned LEB128 integers.
38///
39/// # Target-width integers
40///
41/// `isize` methods use the current Rust target's pointer width. Prefer
42/// fixed-width integer methods such as [`Self::write_zig_zag_i64`] for
43/// persistent files and cross-platform protocols.
44pub trait ZigZagWriteExt: Output<Item = u8> {
45 /// Writes a ZigZag `i8`.
46 ///
47 /// # Parameters
48 ///
49 /// - `value`: Integer to encode and write.
50 ///
51 /// # Returns
52 ///
53 /// Returns after the canonical payload has been written.
54 ///
55 /// # Errors
56 ///
57 /// Returns an output error, including a write-zero error when the output
58 /// stops making progress.
59 #[inline(always)]
60 fn write_zig_zag_i8(&mut self, value: i8) -> Result<()> {
61 write_zig_zag_value!(self, value, i8)
62 }
63
64 /// Writes a ZigZag `i16`.
65 ///
66 /// # Parameters
67 ///
68 /// - `value`: Integer to encode and write.
69 ///
70 /// # Returns
71 ///
72 /// Returns after the canonical payload has been written.
73 ///
74 /// # Errors
75 ///
76 /// Returns an output error, including a write-zero error when the output
77 /// stops making progress.
78 #[inline(always)]
79 fn write_zig_zag_i16(&mut self, value: i16) -> Result<()> {
80 write_zig_zag_value!(self, value, i16)
81 }
82
83 /// Writes a ZigZag `i32`.
84 ///
85 /// # Parameters
86 ///
87 /// - `value`: Integer to encode and write.
88 ///
89 /// # Returns
90 ///
91 /// Returns after the canonical payload has been written.
92 ///
93 /// # Errors
94 ///
95 /// Returns an output error, including a write-zero error when the output
96 /// stops making progress.
97 #[inline(always)]
98 fn write_zig_zag_i32(&mut self, value: i32) -> Result<()> {
99 write_zig_zag_value!(self, value, i32)
100 }
101
102 /// Writes a ZigZag `i64`.
103 ///
104 /// # Parameters
105 ///
106 /// - `value`: Integer to encode and write.
107 ///
108 /// # Returns
109 ///
110 /// Returns after the canonical payload has been written.
111 ///
112 /// # Errors
113 ///
114 /// Returns an output error, including a write-zero error when the output
115 /// stops making progress.
116 #[inline(always)]
117 fn write_zig_zag_i64(&mut self, value: i64) -> Result<()> {
118 write_zig_zag_value!(self, value, i64)
119 }
120
121 /// Writes a ZigZag `i128`.
122 ///
123 /// # Parameters
124 ///
125 /// - `value`: Integer to encode and write.
126 ///
127 /// # Returns
128 ///
129 /// Returns after the canonical payload has been written.
130 ///
131 /// # Errors
132 ///
133 /// Returns an output error, including a write-zero error when the output
134 /// stops making progress.
135 #[inline(always)]
136 fn write_zig_zag_i128(&mut self, value: i128) -> Result<()> {
137 write_zig_zag_value!(self, value, i128)
138 }
139
140 /// Writes a ZigZag `isize`.
141 ///
142 /// # Parameters
143 ///
144 /// - `value`: Integer to encode and write.
145 ///
146 /// # Returns
147 ///
148 /// Returns after the canonical payload has been written.
149 ///
150 /// # Errors
151 ///
152 /// Returns an output error, including a write-zero error when the output
153 /// stops making progress.
154 #[inline(always)]
155 fn write_zig_zag_isize(&mut self, value: isize) -> Result<()> {
156 write_zig_zag_value!(self, value, isize)
157 }
158}
159
160impl<W> ZigZagWriteExt for W where W: Output<Item = u8> + ?Sized {}
161
162/// Encodes and writes one canonical ZigZag value.
163///
164/// # Type Parameters
165///
166/// - `N`: Maximum encoded payload length in bytes.
167/// - `T`: Value type accepted by the encoder.
168/// - `W`: Destination byte output.
169/// - `F`: Infallible encoding callback.
170///
171/// # Parameters
172///
173/// - `writer`: Destination for the encoded payload.
174/// - `value`: Value passed to `encode`.
175/// - `encode`: Callback that fills the local buffer and returns its used
176/// length.
177///
178/// # Returns
179///
180/// Returns after the complete payload has been written.
181///
182/// # Errors
183///
184/// Returns an output error, including a write-zero error when the output stops
185/// making progress.
186#[inline]
187fn write_zig_zag<const N: usize, T, W, F>(
188 writer: &mut W,
189 value: T,
190 encode: F,
191) -> Result<()>
192where
193 W: Output<Item = u8> + ?Sized,
194 F: FnOnce(&mut [u8], T) -> usize,
195{
196 let mut bytes = [0u8; N];
197 let len = encode(&mut bytes, value);
198 write_all(writer, &bytes[..len])
199}