countio 0.3.0

Byte counting for std::io::{Read, Write, Seek} and its async variants from futures and tokio.
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
#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
mod stdlib;

#[cfg(feature = "futures")]
#[cfg_attr(docsrs, doc(cfg(feature = "futures")))]
mod futures;

#[cfg(feature = "tokio")]
#[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
mod tokio;

/// A wrapper that adds byte counting functionality to any reader, writer, or seeker.
///
/// `Counter<D>` tracks the total number of bytes read from and written to the underlying
/// I/O object, providing methods to query these statistics at any time.
///
/// # Type Parameter
///
/// * `D` - The underlying I/O object (reader, writer, or seeker)
///
/// # Examples
///
/// ## Basic Usage with `std::io`
///
/// ```rust
/// use std::io::{Read, Write};
/// use countio::Counter;
///
/// // Counting bytes read
/// let data = b"Hello, World!";
/// let mut reader = Counter::new(&data[..]);
/// let mut buffer = [0u8; 5];
/// reader.read(&mut buffer).unwrap();
/// assert_eq!(reader.reader_bytes(), 5);
///
/// // Counting bytes written
/// let mut writer = Counter::new(Vec::new());
/// writer.write_all(b"Hello").unwrap();
/// assert_eq!(writer.writer_bytes(), 5);
/// ```
///
/// ## With Buffered I/O
///
/// ```rust
/// use std::io::{BufRead, BufReader, BufWriter, Write};
/// use countio::Counter;
///
/// // Buffered reading
/// let data = "Line 1\nLine 2\nLine 3\n";
/// let reader = BufReader::new(data.as_bytes());
/// let mut counter = Counter::new(reader);
/// let mut line = String::new();
/// counter.read_line(&mut line).unwrap();
/// assert_eq!(counter.reader_bytes(), 7);
///
/// // Buffered writing
/// let writer = BufWriter::new(Vec::new());
/// let mut counter = Counter::new(writer);
/// counter.write_all(b"Hello, World!").unwrap();
/// counter.flush().unwrap();
/// assert_eq!(counter.writer_bytes(), 13);
/// ```
///
/// # Performance
///
/// The overhead of byte counting is minimal - just an integer addition per I/O operation.
/// The wrapper implements all relevant traits (`Read`, `Write`, `Seek`, etc.) by
/// delegating to the inner object while tracking byte counts.
pub struct Counter<D> {
    pub(crate) inner: D,
    pub(crate) reader_bytes: usize,
    pub(crate) writer_bytes: usize,
}

impl<D> Counter<D> {
    /// Creates a new `Counter<D>` wrapping the given I/O object with zero read/written bytes.
    ///
    /// # Arguments
    ///
    /// * `inner` - The I/O object to wrap (reader, writer, seeker, etc.)
    ///
    /// # Examples
    ///
    /// ```rust
    /// use countio::Counter;
    /// use std::io::Cursor;
    ///
    /// let data = vec![1, 2, 3, 4, 5];
    /// let cursor = Cursor::new(data);
    /// let counter = Counter::new(cursor);
    ///
    /// assert_eq!(counter.reader_bytes(), 0);
    /// assert_eq!(counter.writer_bytes(), 0);
    /// ```
    #[inline]
    pub const fn new(inner: D) -> Self {
        Self::with_bytes(inner, 0, 0)
    }

    /// Creates a new `Counter<D>` with pre-existing read/written byte counts.
    ///
    /// This is useful when you want to continue counting from a previous session
    /// or when wrapping an I/O object that has already processed some data.
    ///
    /// # Arguments
    ///
    /// * `inner` - The I/O object to wrap
    /// * `reader_bytes` - Initial count of bytes read
    /// * `writer_bytes` - Initial count of bytes written
    ///
    /// # Examples
    ///
    /// ```rust
    /// use countio::Counter;
    /// use std::io::Cursor;
    ///
    /// let data = vec![1, 2, 3, 4, 5];
    /// let cursor = Cursor::new(data);
    /// let counter = Counter::with_bytes(cursor, 100, 50);
    ///
    /// assert_eq!(counter.reader_bytes(), 100);
    /// assert_eq!(counter.writer_bytes(), 50);
    /// ```
    #[inline]
    pub const fn with_bytes(inner: D, reader_bytes: usize, writer_bytes: usize) -> Self {
        Self {
            inner,
            reader_bytes,
            writer_bytes,
        }
    }

    /// Returns the total number of bytes read from the underlying I/O object.
    ///
    /// This count includes all bytes successfully read through any of the
    /// `Read` or `BufRead` trait methods.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::io::Read;
    /// use countio::Counter;
    ///
    /// let data = b"Hello, World!";
    /// let mut reader = Counter::new(&data[..]);
    /// let mut buffer = [0u8; 5];
    ///
    /// reader.read_exact(&mut buffer).unwrap();
    /// assert_eq!(reader.reader_bytes(), 5);
    /// assert_eq!(reader.writer_bytes(), 0);
    /// ```
    #[inline]
    pub const fn reader_bytes(&self) -> usize {
        self.reader_bytes
    }

    /// Returns the total number of bytes written to the underlying I/O object.
    ///
    /// This count includes all bytes successfully written through any of the
    /// `Write` trait methods.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::io::Write;
    /// use countio::Counter;
    ///
    /// let mut writer = Counter::new(Vec::new());
    /// writer.write_all(b"Hello").unwrap();
    /// writer.write_all(b", World!").unwrap();
    ///
    /// assert_eq!(writer.writer_bytes(), 13);
    /// assert_eq!(writer.reader_bytes(), 0);
    /// ```
    #[inline]
    pub const fn writer_bytes(&self) -> usize {
        self.writer_bytes
    }

    /// Returns the total number of bytes processed (read + written) as a `u128`.
    ///
    /// This is the sum of all bytes that have been read from or written to
    /// the underlying I/O object since the `Counter` was created. Using `u128`
    /// prevents overflow issues that could occur with large byte counts.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::io::{Read, Write};
    /// use countio::Counter;
    ///
    /// let mut counter = Counter::new(Vec::new());
    /// counter.write_all(b"Hello").unwrap();
    ///
    /// let data = b"World";
    /// let mut reader = Counter::new(&data[..]);
    /// let mut buf = [0u8; 5];
    /// reader.read(&mut buf).unwrap();
    ///
    /// assert_eq!(counter.total_bytes(), 5);
    /// assert_eq!(reader.total_bytes(), 5);
    /// ```
    #[inline]
    pub const fn total_bytes(&self) -> u128 {
        (self.reader_bytes as u128) + (self.writer_bytes as u128)
    }

    /// Consumes the `Counter<D>` and returns the underlying I/O object.
    ///
    /// This is useful when you need to recover the original I/O object,
    /// perhaps to pass it to code that doesn't know about the `Counter` wrapper.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::io::Write;
    /// use countio::Counter;
    ///
    /// let original_writer = Vec::new();
    /// let mut counter = Counter::new(original_writer);
    /// counter.write_all(b"Hello").unwrap();
    ///
    /// let recovered_writer = counter.into_inner();
    /// assert_eq!(recovered_writer, b"Hello");
    /// ```
    #[inline]
    pub fn into_inner(self) -> D {
        self.inner
    }

    /// Gets a reference to the underlying I/O object.
    ///
    /// This allows you to access the wrapped object's methods directly
    /// without consuming the `Counter`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use countio::Counter;
    /// use std::io::Cursor;
    ///
    /// let data = vec![1, 2, 3, 4, 5];
    /// let cursor = Cursor::new(data.clone());
    /// let counter = Counter::new(cursor);
    ///
    /// assert_eq!(counter.get_ref().position(), 0);
    /// ```
    #[inline]
    pub const fn get_ref(&self) -> &D {
        &self.inner
    }

    /// Gets a mutable reference to the underlying I/O object.
    ///
    /// This allows you to modify the wrapped object directly. Note that
    /// any bytes read or written through the direct reference will not
    /// be counted by the `Counter`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use countio::Counter;
    /// use std::io::Cursor;
    ///
    /// let data = vec![1, 2, 3, 4, 5];
    /// let cursor = Cursor::new(data);
    /// let mut counter = Counter::new(cursor);
    ///
    /// counter.get_mut().set_position(2);
    /// assert_eq!(counter.get_ref().position(), 2);
    /// ```
    #[inline]
    pub const fn get_mut(&mut self) -> &mut D {
        &mut self.inner
    }

    /// Resets the byte counters to zero without affecting the underlying I/O object.
    ///
    /// This is useful when you want to start counting from a fresh state
    /// without recreating the wrapper or losing the underlying object's state.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::io::{Read, Write};
    /// use countio::Counter;
    ///
    /// let mut counter = Counter::new(Vec::new());
    /// counter.write_all(b"Hello").unwrap();
    /// assert_eq!(counter.writer_bytes(), 5);
    ///
    /// counter.reset();
    /// assert_eq!(counter.writer_bytes(), 0);
    /// assert_eq!(counter.reader_bytes(), 0);
    ///
    /// // The underlying data is preserved
    /// assert_eq!(counter.get_ref(), b"Hello");
    /// ```
    #[inline]
    pub const fn reset(&mut self) {
        self.reader_bytes = 0;
        self.writer_bytes = 0;
    }
}

impl<D> From<D> for Counter<D> {
    #[inline]
    fn from(inner: D) -> Self {
        Self::new(inner)
    }
}

impl<D: Clone> Clone for Counter<D> {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
            reader_bytes: self.reader_bytes,
            writer_bytes: self.writer_bytes,
        }
    }
}

impl<D: Default> Default for Counter<D> {
    fn default() -> Self {
        Self::new(D::default())
    }
}

impl<D: core::fmt::Debug> core::fmt::Debug for Counter<D> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("Counter")
            .field("inner", &self.inner)
            .field("read", &self.reader_bytes)
            .field("written", &self.writer_bytes)
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_inner() {
        let writer = vec![8u8];
        assert_eq!(writer.len(), 1);

        let mut writer = Counter::new(writer);
        writer.get_mut().clear();
        assert_eq!(writer.get_ref().len(), 0);

        let writer = writer.into_inner();
        assert_eq!(writer.len(), 0);
    }

    #[test]
    fn test_from() {
        let _: Counter<_> = Vec::<u8>::new().into();
    }

    #[test]
    fn test_with_bytes_creates_counter_with_initial_counts() {
        let counter = Counter::with_bytes(Vec::<u8>::new(), 100, 200);
        assert_eq!(counter.reader_bytes(), 100);
        assert_eq!(counter.writer_bytes(), 200);
        assert_eq!(counter.total_bytes(), 300);
    }

    #[test]
    fn test_reset() {
        use std::io::Write;

        let mut counter = Counter::new(Vec::new());
        counter.write_all(b"Hello").unwrap();
        assert_eq!(counter.writer_bytes(), 5);

        counter.reset();
        assert_eq!(counter.writer_bytes(), 0);
        assert_eq!(counter.reader_bytes(), 0);
        assert_eq!(counter.total_bytes(), 0);

        // Data is preserved
        assert_eq!(counter.get_ref(), b"Hello");
    }

    #[test]
    fn test_clone() {
        use std::io::Write;

        let mut counter = Counter::new(Vec::new());
        counter.write_all(b"Hello").unwrap();

        let cloned = counter.clone();
        assert_eq!(cloned.writer_bytes(), 5);
        assert_eq!(cloned.get_ref(), b"Hello");
    }

    #[test]
    fn test_default() {
        let counter: Counter<Vec<u8>> = Counter::default();
        assert_eq!(counter.reader_bytes(), 0);
        assert_eq!(counter.writer_bytes(), 0);
        assert!(counter.get_ref().is_empty());
    }
}