Skip to main content

dsi_bitstream/traits/
words.rs

1/*
2 * SPDX-FileCopyrightText: 2023 Tommaso Fontana
3 * SPDX-FileCopyrightText: 2023 Inria
4 * SPDX-FileCopyrightText: 2023 Sebastiano Vigna
5 *
6 * SPDX-License-Identifier: Apache-2.0 OR LGPL-2.1-or-later
7 */
8
9use core::error::Error;
10
11use common_traits::*;
12
13/// This is a trait alias for all the properties that we need for words of
14/// memory read and wrote by either a [`WordRead`] or [`WordWrite`],
15/// respectively.
16pub trait Word: UnsignedInt + ToBytes + FromBytes + FiniteRangeNumber {}
17impl<W: UnsignedInt + ToBytes + FromBytes + FiniteRangeNumber> Word for W {}
18
19/// Sequential, streaming word-by-word reads.
20pub trait WordRead {
21    type Error: Error + Send + Sync + 'static;
22
23    /// The word type (the type of the result of [`WordRead::read_word`]).
24    type Word: Word;
25
26    /// Reads a word and advance the current position.
27    fn read_word(&mut self) -> Result<Self::Word, Self::Error>;
28}
29
30/// Sequential, streaming word-by-word writes.
31pub trait WordWrite {
32    type Error: Error + Send + Sync + 'static;
33
34    /// The word type (the type of the argument of [`WordWrite::write_word`]).
35    type Word: Word;
36
37    /// Writes a word and advance the current position.
38    fn write_word(&mut self, word: Self::Word) -> Result<(), Self::Error>;
39
40    /// Flush the stream.
41    fn flush(&mut self) -> Result<(), Self::Error>;
42}
43
44/// Seekability for [`WordRead`] and [`WordWrite`] streams.
45pub trait WordSeek {
46    type Error: Error + Send + Sync + 'static;
47    /// Gets the current position in words from the start of the file.
48    fn word_pos(&mut self) -> Result<u64, Self::Error>;
49
50    /// Sets the current position in words from the start of the file to `word_pos`.
51    fn set_word_pos(&mut self, word_pos: u64) -> Result<(), Self::Error>;
52}
53
54#[derive(Debug, Clone, PartialEq)]
55/// Replacement of [`std::io::Error`] for `no_std` environments
56pub enum WordError {
57    UnexpectedEof { word_pos: usize },
58}
59
60impl core::error::Error for WordError {}
61impl core::fmt::Display for WordError {
62    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
63        match self {
64            WordError::UnexpectedEof { word_pos } => {
65                write!(f, "Unexpected end of data at word position {}", word_pos)
66            }
67        }
68    }
69}