qubit_io_text/adapters/string_text_reader.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// =============================================================================
8use std::convert::Infallible;
9
10use crate::TextLineReader;
11use crate::TextReader;
12use crate::adapters::text_cursor::read_char_at;
13use crate::adapters::text_cursor::read_chars_at;
14use crate::adapters::text_cursor::read_to_string_at;
15use crate::line_ending_set::LineEndingSet;
16use crate::line_ending_set::read_line_with;
17
18/// Text reader over an owned string.
19///
20/// The reader tracks its physical UTF-8 byte offset, including any character
21/// read ahead while recognizing line endings. It recognizes LF, CRLF, and CR
22/// line endings by default.
23///
24/// # Examples
25///
26/// ```
27/// use qubit_io_text::StringTextReader;
28/// use qubit_io_text::TextReader;
29///
30/// let mut reader = StringTextReader::new(String::from("hello"));
31/// let mut output = String::new();
32/// let count = reader.read_to_string(&mut output)?;
33/// assert_eq!(count, 5);
34/// assert_eq!(output, "hello");
35/// # Ok::<(), std::convert::Infallible>(())
36/// ```
37#[derive(Debug)]
38pub struct StringTextReader {
39 /// Owned UTF-8 text being consumed by this reader.
40 text: String,
41 /// Physical UTF-8 byte offset, including line-ending lookahead.
42 position: usize,
43 /// Line terminators recognized by [`TextLineReader::read_line`].
44 line_endings: LineEndingSet,
45 /// Character retained after line-ending lookahead for the next read.
46 pending_char: Option<char>,
47}
48
49impl StringTextReader {
50 /// Creates a reader over owned text.
51 ///
52 /// # Parameters
53 /// - `text`: Text to own and read.
54 ///
55 /// # Returns
56 /// A reader positioned at the start of the text.
57 #[inline]
58 #[must_use]
59 pub fn new(text: String) -> Self {
60 Self {
61 text,
62 position: 0,
63 line_endings: LineEndingSet::ALL,
64 pending_char: None,
65 }
66 }
67
68 /// Returns the physical UTF-8 byte position in the underlying string.
69 ///
70 /// Line-ending detection may read one character ahead and retain it for the
71 /// next read. This position includes that character and can equal the input
72 /// length before all characters have been returned. Reading a retained
73 /// character does not advance this position. Do not use this value as a
74 /// checkpoint of text already delivered to the caller.
75 ///
76 /// # Returns
77 /// The underlying byte offset, including any line-ending lookahead.
78 #[inline]
79 #[must_use]
80 pub const fn position(&self) -> usize {
81 self.position
82 }
83
84 /// Returns the line endings recognized by this reader.
85 ///
86 /// # Returns
87 /// The line endings recognized by this reader.
88 #[must_use]
89 #[inline]
90 pub const fn line_endings(&self) -> LineEndingSet {
91 self.line_endings
92 }
93
94 /// Sets the line endings recognized by [`TextLineReader::read_line`].
95 ///
96 /// # Parameters
97 /// - `line_endings`: Accepted line-ending sequences.
98 ///
99 /// # Returns
100 /// This reader with the requested line-ending configuration.
101 #[inline]
102 #[must_use]
103 pub const fn with_line_endings(mut self, line_endings: LineEndingSet) -> Self {
104 self.line_endings = line_endings;
105 self
106 }
107
108 /// Returns the owned string.
109 ///
110 /// # Returns
111 /// The original string owned by this reader.
112 #[inline]
113 #[must_use]
114 pub fn into_inner(self) -> String {
115 self.text
116 }
117}
118
119impl TextReader for StringTextReader {
120 /// This in-memory reader cannot fail while decoding its valid UTF-8 input.
121 type Error = Infallible;
122
123 /// Returns the next Unicode scalar value, including any character retained
124 /// during line-ending lookahead, or `None` when the input is exhausted.
125 ///
126 /// # Returns
127 /// `Ok(Some(ch))` when a character is available, or `Ok(None)` at EOF.
128 ///
129 /// # Errors
130 /// This in-memory reader never returns an error because its error type is
131 /// [`Infallible`].
132 #[inline]
133 fn read_char(&mut self) -> Result<Option<char>, Self::Error> {
134 if let Some(ch) = self.pending_char.take() {
135 return Ok(Some(ch));
136 }
137 Ok(read_char_at(self.text.as_str(), &mut self.position))
138 }
139
140 /// Appends up to `max` Unicode scalar values to `output` and returns the
141 /// number appended. A character retained during line-ending lookahead is
142 /// returned first; a zero limit leaves it pending.
143 ///
144 /// # Parameters
145 /// - `output`: Destination that receives the characters, appended after its
146 /// existing contents.
147 /// - `max`: Maximum number of Unicode scalar values to append.
148 ///
149 /// # Returns
150 /// `Ok(count)` with the number of characters appended.
151 ///
152 /// # Errors
153 /// This in-memory reader never returns an error because its error type is
154 /// [`Infallible`].
155 #[inline]
156 fn read_chars(&mut self, output: &mut Vec<char>, max: usize) -> Result<usize, Self::Error> {
157 let mut count = 0;
158 if max > 0
159 && let Some(ch) = self.pending_char.take()
160 {
161 output.push(ch);
162 count = 1;
163 }
164 Ok(count
165 + read_chars_at(
166 self.text.as_str(),
167 &mut self.position,
168 output,
169 max.saturating_sub(count),
170 ))
171 }
172
173 /// Appends all remaining text, including any retained lookahead character,
174 /// to `output` and returns the number of Unicode scalar values appended.
175 ///
176 /// # Parameters
177 /// - `output`: Destination that receives the remaining text, appended after
178 /// its existing contents.
179 ///
180 /// # Returns
181 /// `Ok(count)` with the number of Unicode scalar values appended.
182 ///
183 /// # Errors
184 /// This in-memory reader never returns an error because its error type is
185 /// [`Infallible`].
186 #[inline]
187 fn read_to_string(&mut self, output: &mut String) -> Result<usize, Self::Error> {
188 let mut count = 0;
189 if let Some(ch) = self.pending_char.take() {
190 output.push(ch);
191 count = 1;
192 }
193 Ok(count + read_to_string_at(self.text.as_str(), &mut self.position, output))
194 }
195}
196
197impl TextLineReader for StringTextReader {
198 /// Appends the next line to `output`, consuming its recognized line ending
199 /// when present. Returns `false` only when no line content or terminator
200 /// remains; a final unterminated line is returned with `true`.
201 ///
202 /// # Parameters
203 /// - `output`: Destination that receives the next line, appended after its
204 /// existing contents.
205 ///
206 /// # Returns
207 /// `Ok(true)` when a line or final unterminated line is read, or
208 /// `Ok(false)` when no content or terminator remains.
209 ///
210 /// # Errors
211 /// This in-memory reader never returns an error because its error type is
212 /// [`Infallible`].
213 #[inline]
214 fn read_line(&mut self, output: &mut String) -> Result<bool, Self::Error> {
215 let text = self.text.as_str();
216 let position = &mut self.position;
217 let mut pending_char = self.pending_char.take();
218 let line_endings = self.line_endings;
219 let result = read_line_with(line_endings, output, &mut pending_char, || {
220 Ok(read_char_at(text, position))
221 });
222 self.pending_char = pending_char;
223 result
224 }
225}