1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// =============================================================================
// Copyright (c) 2026 Haixing Hu.
//
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0.
// =============================================================================
//! Runtime-owned byte sink for incrementally serialized safe text.
use std::io;
use std::io::Write;
/// Bounds serializer output before it becomes an unpublished operation.
pub(crate) struct OperationByteSink {
/// Serializer bytes retained only after complete-token admission.
output: Vec<u8>,
/// Maximum bytes the operation may retain.
maximum: usize,
}
impl OperationByteSink {
/// Creates an empty byte sink with one operation's output allowance.
///
/// # Parameters
///
/// - `maximum`: Maximum serializer bytes retained for this operation.
///
/// # Returns
///
/// An empty in-memory byte sink.
#[must_use]
#[inline(always)]
pub(crate) const fn new(maximum: usize) -> Self {
Self {
output: Vec::new(),
maximum,
}
}
/// Converts accepted serializer bytes into UTF-8 text.
///
/// # Returns
///
/// `Some(text)` contains valid UTF-8; `None` means retained bytes were
/// not a complete UTF-8 string.
#[must_use]
#[inline(always)]
pub(crate) fn into_string(self) -> Option<String> {
String::from_utf8(self.output).ok()
}
}
impl Write for OperationByteSink {
/// Atomically appends `buffer` when the complete serializer token fits.
///
/// # Errors
///
/// Returns [`io::ErrorKind::WriteZero`] if the whole buffer cannot fit.
///
/// # Parameters
///
/// - `buffer`: One serializer write, accepted or rejected as a whole.
///
/// # Returns
///
/// The complete buffer length after successful retention.
#[inline]
fn write(&mut self, buffer: &[u8]) -> io::Result<usize> {
if self.output.len().saturating_add(buffer.len()) > self.maximum {
return Err(io::Error::from(io::ErrorKind::WriteZero));
}
self.output.extend_from_slice(buffer);
Ok(buffer.len())
}
/// Returns success without external I/O; in-memory flushing cannot fail.
#[inline(always)]
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}