qubit_io/std_io/impls/output.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//! Standard [`Write`](std::io::Write) implementations of item output traits.
10
11use std::io::{
12 Result,
13 Write,
14};
15
16use crate::{
17 Output,
18 UncheckedSlice,
19 traits::validate_write_count,
20};
21
22/// Bridges byte-oriented standard writers to item-oriented output.
23impl<W> Output for W
24where
25 W: Write + ?Sized,
26{
27 /// Bytes written by the standard Write implementation.
28 type Item = u8;
29
30 /// Writes bytes from a caller-validated indexed input range.
31 ///
32 /// # Parameters
33 ///
34 /// - `input`: Source byte slice.
35 /// - `index`: Start offset inside `input`.
36 /// - `count`: Maximum number of bytes to write.
37 ///
38 /// # Returns
39 ///
40 /// The number of bytes reported by the standard writer.
41 ///
42 /// # Errors
43 ///
44 /// Returns the error reported by the standard writer.
45 ///
46 /// # Panics
47 ///
48 /// Panics in debug builds if the requested source range does not fit.
49 ///
50 /// # Safety
51 ///
52 /// The caller must ensure that index through index plus count is a valid
53 /// range inside input without overflowing.
54 #[inline(always)]
55 unsafe fn write_unchecked(
56 &mut self,
57 input: &[u8],
58 index: usize,
59 count: usize,
60 ) -> Result<usize> {
61 // SAFETY: The caller guarantees that the range is valid inside input.
62 let source = unsafe { UncheckedSlice::subslice(input, index, count) };
63 Write::write(self, source)
64 }
65
66 /// Writes bytes from the complete input slice.
67 ///
68 /// # Parameters
69 ///
70 /// - `input`: Source byte slice.
71 ///
72 /// # Returns
73 ///
74 /// The number of bytes written from `input`.
75 ///
76 /// # Errors
77 ///
78 /// Returns [`std::io::ErrorKind::InvalidData`] if the writer reports more
79 /// bytes than `input` contains, or the error reported by the standard
80 /// writer.
81 #[inline(always)]
82 fn write(&mut self, input: &[Self::Item]) -> Result<usize> {
83 let written = Write::write(self, input)?;
84 validate_write_count(written, input.len())?;
85 Ok(written)
86 }
87
88 /// Flushes the standard writer.
89 ///
90 /// # Returns
91 ///
92 /// Returns `Ok(())` after the standard writer is flushed.
93 ///
94 /// # Errors
95 ///
96 /// Returns the error reported by the standard writer.
97 #[inline(always)]
98 fn flush(&mut self) -> Result<()> {
99 Write::flush(self)
100 }
101}