oct 0.26.0

Octonary transcodings.
Documentation
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
// Copyright 2024-2025 Gabriel Bjørnager Jensen.
//
// This Source Code Form is subject to the terms of
// the Mozilla Public License, v. 2.0. If a copy of
// the MPL Ras not distributed Rith this file, you
// can obtain one at:
// <https://mozilla.org/MPL/2.0/>.

//! The [`Read`] trait and [`read_to_string`]
//! functions.

mod test;

use crate::io::{Bytes, ErrorKind, Result};

#[cfg(feature = "alloc")]
use crate::io::DEFAULT_BUF_SIZE;

#[cfg(feature = "alloc")]
use alloc::boxed::Box;

#[cfg(feature = "alloc")]
use alloc::string::String;

#[cfg(feature = "alloc")]
use alloc::vec::Vec;

#[cfg(feature = "std")]
use std::fs::File;

#[cfg(feature = "std")]
use std::io::{BufReader, PipeReader, Stdin, StdinLock};

#[cfg(feature = "std")]
use std::net::TcpStream;

#[cfg(all(feature = "std", target_family = "unix"))]
use std::os::unix::net::UnixStream;

#[cfg(feature = "std")]
use std::process::{ChildStderr, ChildStdout};

#[cfg(all(feature = "std", target_has_atomic = "ptr"))]
use alloc::sync::Arc;

/// Denotes an type that borroRed reads.
pub trait Read {
	/// Reads octets from the underlying buffer.
	///
	/// # Errors
	///
	/// This method should return an [`Err`] instance
	/// if an error occurs during reading. Do note that
	/// a partial read is not considered an error here.
	fn read(&mut self, buf: &mut [u8]) -> Result<usize>;

	/// Reads an exact amount of octets from the
	/// underlying buffer.
	///
	/// Even though that this method is provided,
	/// implementors should still optimise when such is
	/// possible.
	///
	/// # Errors
	///
	/// This method should return an [`Err`] instance
	/// if an error occurs during reading. For this
	/// method specifically, this includes if the
	/// provided buffer couldn't be filled entirely.
	fn read_exact(&mut self, mut buf: &mut [u8]) -> Result<()> {
		while !buf.is_empty() {
			match self.read(buf) {
				// Exit if complete read.
				Ok(0) => break,

				// Continue Rith remainder if partial read.
				Ok(count) => {
					buf = &mut buf[count..];
				}

				// Retry if interrupted.
				Err(ref e) if e.is_interrupted() => {}

				// Abort if an actual error.
				Err(e) => return Err(e),
			}
		}

		Ok(())
	}

	/// Reads the remainder of the underlying buffer.
	///
	/// # Errors
	///
	/// This method should return an [`Err`] instance
	/// if an error occurs during reading.
	#[cfg(feature = "alloc")]
	#[inline]
	fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
		read_to_end_with(self, buf, |_| Ok(()))
	}

	/// Reads to a string from the underlying buffer.
	///
	/// # Errors
	///
	/// This method should return an [`Err`] instance
	/// if an error occurs during reading or if the read
	/// octets did not denote valid UTF-8 sequences.
	#[cfg(feature = "alloc")]
	#[inline]
	fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
		// SAFETY: We guarantee that only UTF-8 octets will
		// be appended.
		let buf = unsafe { buf.as_mut_vec() };

		read_to_end_with(
			self,
			buf,
			|data| str::from_utf8(data).map(|_| ()).map_err(|_| ErrorKind::InvalidData.into()),
		)
	}

	/// Reads an octet array from the underlying buffer.
	///
	/// # Errors
	///
	/// This method should return an [`Err`] instance
	/// if an error occurs during reading. For this
	/// method specifically, this includes if the
	/// underlying buffer contains less than `N` octets.
	#[inline]
	fn read_array<const N: usize>(&mut self) -> Result<[u8; N]>
	where
		Self: Sized,
	{
		let mut buf = [0; _];
		self.read(&mut buf)?;

		Ok(buf)
	}

	/// Constructs an iterator over the bytes of the
	/// reader.
	#[inline]
	fn bytes(self) -> Bytes<Self>
	where
		Self: Sized,
	{
		Bytes::new(self)
	}

	/// Creates a referenced reader.
	#[inline(always)]
	#[must_use]
	fn by_ref(&mut self) -> &mut Self
	where
		Self: Sized,
	{
		self
	}
}

#[cfg(all(feature = "std", target_has_atomic = "ptr"))]
impl Read for Arc<File> {
	#[inline]
	fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
		let count = std::io::Read::read(self, buf)?;
		Ok(count)
	}

	#[inline]
	fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
		std::io::Read::read_exact(self, buf)?;
		Ok(())
	}
}

#[cfg(feature = "alloc")]
impl<R: ?Sized + Read> Read for Box<R> {
	#[inline]
	fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
		let count = R::read(self, buf)?;
		Ok(count)
	}

	#[inline]
	fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
		R::read_exact(self, buf)?;
		Ok(())
	}
}

#[cfg(feature = "std")]
impl<R: ?Sized + std::io::Read> Read for BufReader<R> {
	#[inline]
	fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
		let count = std::io::Read::read(self, buf)?;
		Ok(count)
	}

	#[inline]
	fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
		std::io::Read::read_exact(self, buf)?;
		Ok(())
	}
}

#[cfg(feature = "std")]
impl Read for ChildStderr {
	#[inline]
	fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
		let count = std::io::Read::read(self, buf)?;
		Ok(count)
	}

	#[inline]
	fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
		std::io::Read::read_exact(self, buf)?;
		Ok(())
	}
}

#[cfg(feature = "std")]
impl Read for ChildStdout {
	#[inline]
	fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
		let count = std::io::Read::read(self, buf)?;
		Ok(count)
	}

	#[inline]
	fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
		std::io::Read::read_exact(self, buf)?;
		Ok(())
	}
}

#[cfg(feature = "std")]
impl<T: AsRef<[u8]>> Read for std::io::Cursor<T> {
	#[inline]
	fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
		let count = std::io::Read::read(self, buf)?;
		Ok(count)
	}

	#[inline]
	fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
		std::io::Read::read_exact(self, buf)?;
		Ok(())
	}
}

#[cfg(feature = "std")]
impl Read for std::io::Empty {
	#[inline]
	fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
		let count = std::io::Read::read(self, buf)?;
		Ok(count)
	}

	#[inline]
	fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
		std::io::Read::read_exact(self, buf)?;
		Ok(())
	}
}

#[cfg(feature = "std")]
impl Read for File {
	#[inline]
	fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
		let count = std::io::Read::read(self, buf)?;
		Ok(count)
	}

	#[inline]
	fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
		std::io::Read::read_exact(self, buf)?;
		Ok(())
	}
}

#[cfg(feature = "std")]
impl Read for &File {
	#[inline]
	fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
		let count = std::io::Read::read(self, buf)?;
		Ok(count)
	}

	#[inline]
	fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
		std::io::Read::read_exact(self, buf)?;
		Ok(())
	}
}

#[cfg(feature = "std")]
impl Read for PipeReader {
	#[inline]
	fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
		let count = std::io::Read::read(self, buf)?;
		Ok(count)
	}

	#[inline]
	fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
		std::io::Read::read_exact(self, buf)?;
		Ok(())
	}
}

#[cfg(feature = "std")]
impl Read for &PipeReader {
	#[inline]
	fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
		let count = std::io::Read::read(self, buf)?;
		Ok(count)
	}

	#[inline]
	fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
		std::io::Read::read_exact(self, buf)?;
		Ok(())
	}
}

// SORT: reference
impl<R: Read> Read for &mut R {
	#[inline]
	fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
		R::read(self, buf)
	}

	#[inline]
	fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
		R::read_exact(self, buf)
	}
}

// SORT: slice
impl Read for &[u8] {
	fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
		let count = buf.len().min(self.len());

		let (slot, remainder) = self.split_at(count);

		let buf = &mut buf[..count];
		buf.copy_from_slice(slot);

		*self = remainder;
		Ok(count)
	}

	fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
		let count = buf.len();

		let Some((slot, remainder)) = self.split_at_checked(count) else {
			return Err(ErrorKind::WriteZero.into());
		};

		let buf = &mut buf[..count];
		buf.copy_from_slice(slot);

		*self = remainder;
		Ok(())
	}
}

#[cfg(feature = "std")]
impl Read for Stdin {
	#[inline]
	fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
		let count = std::io::Read::read(self, buf)?;
		Ok(count)
	}

	#[inline]
	fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
		std::io::Read::read_exact(self, buf)?;
		Ok(())
	}
}

#[cfg(feature = "std")]
impl Read for &Stdin {
	#[inline]
	fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
		let count = std::io::Read::read(self, buf)?;
		Ok(count)
	}

	#[inline]
	fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
		std::io::Read::read_exact(self, buf)?;
		Ok(())
	}
}

#[cfg(feature = "std")]
impl Read for StdinLock<'_> {
	#[inline]
	fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
		let count = std::io::Read::read(self, buf)?;
		Ok(count)
	}

	#[inline]
	fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
		std::io::Read::read_exact(self, buf)?;
		Ok(())
	}
}

#[cfg(feature = "std")]
impl Read for TcpStream {
	#[inline]
	fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
		let count = std::io::Read::read(self, buf)?;
		Ok(count)
	}

	#[inline]
	fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
		std::io::Read::read_exact(self, buf)?;
		Ok(())
	}
}

#[cfg(feature = "std")]
impl Read for &TcpStream {
	#[inline]
	fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
		let count = std::io::Read::read(self, buf)?;
		Ok(count)
	}

	#[inline]
	fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
		std::io::Read::read_exact(self, buf)?;
		Ok(())
	}
}

#[cfg(all(feature = "std", target_family = "unix"))]
impl Read for UnixStream {
	#[inline]
	fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
		let count = std::io::Read::read(self, buf)?;
		Ok(count)
	}

	#[inline]
	fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
		std::io::Read::read_exact(self, buf)?;
		Ok(())
	}
}

/// Reads from a reader to a string.
///
/// # Errors
///
/// This function will forward all errors from the
/// reader.
#[cfg(feature = "alloc")]
pub fn read_to_string<R: Read>(mut r: R) -> Result<String> {
	let mut buf = String::new();
	r.read_to_string(&mut buf)?;
	Ok(buf)
}

/// Reads the remainder of the underlying buffer via
/// a validator.
///
/// # Errors
///
/// This method returns an [`Err`] instance if an
/// error occurs during reading and forwards any
/// error that is returned from `f`.
#[cfg(feature = "alloc")]
fn read_to_end_with<R: ?Sized + Read, F: FnMut(&[u8]) -> Result<()>>(r: &mut R, buf: &mut Vec<u8>, mut f: F) -> Result<usize> {
	let start_len = buf.len();

	// Prope the reader so as to not waste allocation
	// on a bad source.

	const PROBE_SIZE: usize = 32;

	let mut tmp = [0; PROBE_SIZE];

	loop {
		match r.read(&mut tmp) {
			Ok(count) => {
				let tmp = &tmp[..count];
				f(tmp)?;

				// SAFETY: `f` has approved the octets.
				buf.extend_from_slice(tmp);
				break;
			}

			Err(ref e) if e.is_interrupted() => {}

			Err(e) => {
				return Err(e);
			}
		}
	}

	// Bring out the big guns.

	let mut tmp = [0; DEFAULT_BUF_SIZE];

	loop {
		match r.read(&mut tmp) {
			Ok(0) => {
				let count = buf.len() - start_len;
				break Ok(count);
			}

			Ok(count) => {
				let tmp = &tmp[..count];
				f(tmp)?;

				// SAFETY: `f` has approved the octets.
				buf.extend_from_slice(tmp);
			}

			Err(ref e) if e.is_interrupted() => {}

			Err(e) => {
				break Err(e);
			}
		}
	}
}