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