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
/*
 * SPDX-FileCopyrightText: 2023 Tommaso Fontana
 * SPDX-FileCopyrightText: 2023 Inria
 * SPDX-FileCopyrightText: 2023 Sebastiano Vigna
 *
 * SPDX-License-Identifier: Apache-2.0 OR LGPL-2.1-or-later
 */

use core::convert::Infallible;

use crate::traits::*;
use common_traits::UnsignedInt;

/// An implementation of [`WordRead`], [`WordWrite`], and [`WordSeek`] for a
/// mutable slice.
///
/// Writing beyond the end of the slice will return an error.
///
/// # Example
/// ```
/// use dsi_bitstream::prelude::*;
///
/// let mut words: [u64; 2] = [
///     0x0043b59fcdf16077,
///     0x702863e6f9739b86,
/// ];
///
/// let mut word_writer = MemWordWriterSlice::new(&mut words);
///
/// // the stream is read sequentially
/// assert_eq!(word_writer.get_word_pos().unwrap(), 0);
/// assert_eq!(word_writer.read_word().unwrap(), 0x0043b59fcdf16077);
/// assert_eq!(word_writer.get_word_pos().unwrap(), 1);
/// assert_eq!(word_writer.read_word().unwrap(), 0x702863e6f9739b86);
/// assert_eq!(word_writer.get_word_pos().unwrap(), 2);
/// assert!(word_writer.read_word().is_err());
///
/// // you can change position
/// assert!(word_writer.set_word_pos(1).is_ok());
/// assert_eq!(word_writer.get_word_pos().unwrap(), 1);
/// assert_eq!(word_writer.read_word().unwrap(), 0x702863e6f9739b86);
///
/// // errored set position doesn't change the current position
/// assert_eq!(word_writer.get_word_pos().unwrap(), 2);
/// assert!(word_writer.set_word_pos(100).is_err());
/// assert_eq!(word_writer.get_word_pos().unwrap(), 2);
///
/// // we can write and read back!
/// assert!(word_writer.set_word_pos(0).is_ok());
/// assert!(word_writer.write_word(0x0b801b2bf696e8d2).is_ok());
/// assert_eq!(word_writer.get_word_pos().unwrap(), 1);
/// assert!(word_writer.set_word_pos(0).is_ok());
/// assert_eq!(word_writer.read_word().unwrap(), 0x0b801b2bf696e8d2);
/// assert_eq!(word_writer.get_word_pos().unwrap(), 1);
/// ```
#[derive(Debug, PartialEq)]
pub struct MemWordWriterSlice<W: UnsignedInt, B: AsMut<[W]>> {
    data: B,
    word_index: usize,
    _marker: core::marker::PhantomData<W>,
}

impl<W: UnsignedInt, B: AsMut<[W]> + AsRef<[W]>> MemWordWriterSlice<W, B> {
    /// Create a new [`MemWordWriterSlice`] from a slice of **ZERO INITIALIZED** data
    #[must_use]
    pub fn new(data: B) -> Self {
        Self {
            data,
            word_index: 0,
            _marker: Default::default(),
        }
    }

    pub fn len(&self) -> usize {
        self.data.as_ref().len()
    }

    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

/// An implementation of [`WordRead`], [`WordWrite`], and [`WordSeek`]
/// for a mutable vector.
///
/// The vector will be extended as new data is written.
///
/// # Example
/// ```
/// use dsi_bitstream::prelude::*;
///
/// let mut words: Vec<u64> = vec![
///     0x0043b59fcdf16077,
/// ];
///
/// let mut word_writer = MemWordWriterVec::new(&mut words);
///
/// // the stream is read sequentially
/// assert_eq!(word_writer.get_word_pos().unwrap(), 0);
/// assert!(word_writer.write_word(0).is_ok());
/// assert_eq!(word_writer.get_word_pos().unwrap(), 1);
/// assert!(word_writer.write_word(1).is_ok());
/// assert_eq!(word_writer.get_word_pos().unwrap(), 2);
/// ```
#[derive(Debug, PartialEq)]
#[cfg(feature = "alloc")]
pub struct MemWordWriterVec<W: UnsignedInt, B: AsMut<alloc::vec::Vec<W>>> {
    data: B,
    word_index: usize,
    _marker: core::marker::PhantomData<W>,
}

#[cfg(feature = "alloc")]
impl<W: UnsignedInt, B: AsMut<alloc::vec::Vec<W>> + AsRef<alloc::vec::Vec<W>>>
    MemWordWriterVec<W, B>
{
    /// Create a new [`MemWordWriterSlice`] from a slice of **ZERO INITIALIZED** data
    #[must_use]
    pub fn new(data: B) -> Self {
        Self {
            data,
            word_index: 0,
            _marker: Default::default(),
        }
    }

    pub fn len(&self) -> usize {
        self.data.as_ref().len()
    }

    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

impl<W: UnsignedInt, B: AsMut<[W]>> WordRead for MemWordWriterSlice<W, B> {
    type Error = std::io::Error;
    type Word = W;

    #[inline]
    fn read_word(&mut self) -> Result<W, std::io::Error> {
        match self.data.as_mut().get(self.word_index) {
            Some(word) => {
                self.word_index += 1;
                Ok(*word)
            }
            None => Err(std::io::Error::new(
                std::io::ErrorKind::UnexpectedEof,
                "Cannot read next word as the underlying memory ended",
            )),
        }
    }
}

impl<W: UnsignedInt, B: AsRef<[W]> + AsMut<[W]>> WordSeek for MemWordWriterSlice<W, B> {
    type Error = std::io::Error;

    #[inline(always)]
    fn get_word_pos(&mut self) -> Result<u64, std::io::Error> {
        Ok(self.word_index as u64)
    }

    #[inline(always)]
    fn set_word_pos(&mut self, word_index: u64) -> Result<(), std::io::Error> {
        return if word_index > self.data.as_ref().len() as u64 {
            Err(std::io::Error::new(
                std::io::ErrorKind::UnexpectedEof,
                format_args!(
                    "Position beyond end of vector: {} > {}",
                    word_index,
                    self.data.as_ref().len()
                )
                .to_string(),
            ))
        } else {
            self.word_index = word_index as usize;
            Ok(())
        };
    }
}

impl<W: UnsignedInt, B: AsMut<[W]>> WordWrite for MemWordWriterSlice<W, B> {
    type Error = std::io::Error;
    type Word = W;

    #[inline]
    fn write_word(&mut self, word: W) -> Result<(), std::io::Error> {
        match self.data.as_mut().get_mut(self.word_index) {
            Some(word_ref) => {
                self.word_index += 1;
                *word_ref = word;
                Ok(())
            }
            None => Err(std::io::Error::new(
                std::io::ErrorKind::UnexpectedEof,
                "Cannot write next word as the underlying memory ended",
            )),
        }
    }
}

#[cfg(feature = "alloc")]
impl<W: UnsignedInt, B: AsMut<alloc::vec::Vec<W>>> WordWrite for MemWordWriterVec<W, B> {
    type Error = Infallible;
    type Word = W;

    #[inline]
    fn write_word(&mut self, word: W) -> Result<(), Infallible> {
        if self.word_index >= self.data.as_mut().len() {
            self.data.as_mut().resize(self.word_index + 1, W::ZERO);
        }
        self.data.as_mut()[self.word_index] = word;
        self.word_index += 1;
        Ok(())
    }
}

#[cfg(feature = "alloc")]
impl<W: UnsignedInt, B: AsMut<alloc::vec::Vec<W>>> WordRead for MemWordWriterVec<W, B> {
    type Error = std::io::Error;
    type Word = W;

    #[inline]
    fn read_word(&mut self) -> Result<W, std::io::Error> {
        match self.data.as_mut().get(self.word_index) {
            Some(word) => {
                self.word_index += 1;
                Ok(*word)
            }
            None => Err(std::io::Error::new(
                std::io::ErrorKind::UnexpectedEof,
                "Cannot read next word as the underlying memory ended",
            )),
        }
    }
}

#[cfg(feature = "alloc")]
impl<W: UnsignedInt, B: AsMut<alloc::vec::Vec<W>> + AsRef<alloc::vec::Vec<W>>> WordSeek
    for MemWordWriterVec<W, B>
{
    type Error = std::io::Error;

    #[inline(always)]
    fn get_word_pos(&mut self) -> Result<u64, std::io::Error> {
        Ok(self.word_index as u64)
    }

    #[inline(always)]
    fn set_word_pos(&mut self, word_index: u64) -> Result<(), std::io::Error> {
        return if word_index > self.data.as_ref().len() as u64 {
            Err(std::io::Error::new(
                std::io::ErrorKind::UnexpectedEof,
                format_args!(
                    "Position beyond end of vector: {} > {}",
                    word_index,
                    self.data.as_ref().len()
                )
                .to_string(),
            ))
        } else {
            self.word_index = word_index as usize;
            Ok(())
        };
    }
}