qubit_io_text/adapters/str_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 a borrowed string slice.
19///
20/// The reader borrows its input and tracks its physical UTF-8 byte offset,
21/// including any character read ahead while recognizing line endings. It
22/// recognizes LF, CRLF, and CR line endings by default.
23///
24/// # Type Parameters
25///
26/// - `'a`: Lifetime of the borrowed text.
27///
28/// # Examples
29///
30/// ```
31/// use qubit_io_text::StrTextReader;
32/// use qubit_io_text::TextReader;
33///
34/// let mut reader = StrTextReader::new("hello");
35/// let mut output = String::new();
36/// let count = reader.read_to_string(&mut output)?;
37/// assert_eq!(count, 5);
38/// assert_eq!(output, "hello");
39/// # Ok::<(), std::convert::Infallible>(())
40/// ```
41#[derive(Debug)]
42pub struct StrTextReader<'a> {
43 /// Borrowed text being consumed by this reader.
44 text: &'a str,
45 /// Physical UTF-8 byte offset, including line-ending lookahead.
46 position: usize,
47 /// Line terminators recognized by [`TextLineReader::read_line`].
48 line_endings: LineEndingSet,
49 /// Character retained after line-ending lookahead for the next read.
50 pending_char: Option<char>,
51}
52
53impl<'a> StrTextReader<'a> {
54 /// Creates a reader over `text`.
55 ///
56 /// # Parameters
57 /// - `text`: Borrowed text to read.
58 ///
59 /// # Returns
60 /// A reader positioned at the start of the text.
61 #[must_use]
62 #[inline]
63 pub const fn new(text: &'a str) -> Self {
64 Self {
65 text,
66 position: 0,
67 line_endings: LineEndingSet::ALL,
68 pending_char: None,
69 }
70 }
71
72 /// Returns the physical UTF-8 byte position in the underlying string.
73 ///
74 /// Line-ending detection may read one character ahead and retain it for the
75 /// next read. This position includes that character and can equal the input
76 /// length before all characters have been returned. Reading a retained
77 /// character does not advance this position. Do not use this value as a
78 /// checkpoint of text already delivered to the caller.
79 ///
80 /// # Returns
81 /// The underlying byte offset, including any line-ending lookahead.
82 #[must_use]
83 #[inline]
84 pub const fn position(&self) -> usize {
85 self.position
86 }
87
88 /// Returns the line endings recognized by this reader.
89 #[must_use]
90 #[inline]
91 pub const fn line_endings(&self) -> LineEndingSet {
92 self.line_endings
93 }
94
95 /// Sets the line endings recognized by [`TextLineReader::read_line`].
96 ///
97 /// # Parameters
98 /// - `line_endings`: Accepted line-ending sequences.
99 ///
100 /// # Returns
101 /// This reader with the requested line-ending configuration.
102 #[must_use]
103 #[inline]
104 pub const fn with_line_endings(mut self, line_endings: LineEndingSet) -> Self {
105 self.line_endings = line_endings;
106 self
107 }
108}
109
110impl TextReader for StrTextReader<'_> {
111 /// This reader cannot fail because it reads from an in-memory string slice.
112 type Error = Infallible;
113
114 /// Returns the next Unicode scalar value, first consuming any character
115 /// retained by line-ending lookahead.
116 ///
117 /// # Returns
118 /// `Ok(Some(ch))` when a character was read, or `Ok(None)` when the input
119 /// is exhausted.
120 #[inline]
121 fn read_char(&mut self) -> Result<Option<char>, Self::Error> {
122 if let Some(ch) = self.pending_char.take() {
123 return Ok(Some(ch));
124 }
125 Ok(read_char_at(self.text, &mut self.position))
126 }
127
128 /// Appends up to `max` characters, including a retained lookahead
129 /// character when the limit is nonzero, and returns the number appended.
130 ///
131 /// # Parameters
132 /// - `output`: Buffer that receives the characters.
133 /// - `max`: Maximum number of characters to append.
134 ///
135 /// # Returns
136 /// The number of characters appended. The result is always successful.
137 #[inline]
138 fn read_chars(&mut self, output: &mut Vec<char>, max: usize) -> Result<usize, Self::Error> {
139 let mut count = 0;
140 if max > 0
141 && let Some(ch) = self.pending_char.take()
142 {
143 output.push(ch);
144 count = 1;
145 }
146 Ok(count + read_chars_at(self.text, &mut self.position, output, max.saturating_sub(count)))
147 }
148
149 /// Appends all remaining text and any retained lookahead character, then
150 /// returns the number of characters appended.
151 ///
152 /// # Parameters
153 /// - `output`: String that receives the remaining text.
154 ///
155 /// # Returns
156 /// The number of characters appended. The result is always successful.
157 #[inline]
158 fn read_to_string(&mut self, output: &mut String) -> Result<usize, Self::Error> {
159 let mut count = 0;
160 if let Some(ch) = self.pending_char.take() {
161 output.push(ch);
162 count = 1;
163 }
164 Ok(count + read_to_string_at(self.text, &mut self.position, output))
165 }
166}
167
168impl TextLineReader for StrTextReader<'_> {
169 /// Appends the next line according to this reader's configured line
170 /// endings, returning whether a line was read. A trailing terminator does
171 /// not produce an additional empty line.
172 ///
173 /// # Parameters
174 /// - `output`: String that receives the line contents, without its
175 /// terminator.
176 ///
177 /// # Returns
178 /// `true` if a line was read, or `false` if no text remains. The result is
179 /// always successful.
180 #[inline]
181 fn read_line(&mut self, output: &mut String) -> Result<bool, Self::Error> {
182 let text = self.text;
183 let position = &mut self.position;
184 let mut pending_char = self.pending_char.take();
185 let line_endings = self.line_endings;
186 let result = read_line_with(line_endings, output, &mut pending_char, || {
187 Ok(read_char_at(text, position))
188 });
189 self.pending_char = pending_char;
190 result
191 }
192}