Skip to main content

coven_database/
input_bytes.rs

1//! Local bounded reads of retained provider bytes during an apply transaction.
2
3use super::{read_local, sql_offset, InputConnection, InputRead, RANGES};
4use std::io::{self, Read, Seek, SeekFrom};
5use std::sync::Arc;
6
7/// Independent cursor over one pinned input. Closing the database invalidates
8/// every cursor; an absent cached range returns an I/O error, never a network read.
9#[derive(Clone)]
10pub struct RetainedBytes {
11    database: InputConnection,
12    reading: Arc<InputRead>,
13    position: u64,
14    length: u64,
15}
16
17impl RetainedBytes {
18    pub(super) fn new(database: InputConnection, reading: Arc<InputRead>, length: u64) -> Self {
19        Self { database, reading, position: 0, length }
20    }
21
22    /// The received object's declared length.
23    pub fn len(&self) -> u64 {
24        self.length
25    }
26
27    /// Whether this object has no bytes.
28    pub fn is_empty(&self) -> bool {
29        self.length == 0
30    }
31}
32
33impl Read for RetainedBytes {
34    fn read(&mut self, output: &mut [u8]) -> io::Result<usize> {
35        let length = self
36            .length
37            .saturating_sub(self.position)
38            .min(output.len() as u64)
39            .min(coven_format::chunks::CHUNK_SIZE as u64);
40        if length == 0 {
41            return Ok(0);
42        }
43        let start = self.position;
44        let end = start + length;
45        let ranges = read_local(&self.database, |db, _| {
46            Ok(db.query(
47                RANGES,
48                (self.reading.id, sql_offset(start)?, sql_offset(end)?),
49                |row| Ok((row.get::<_, i64>(0)? as u64, row.get::<_, Vec<u8>>(1)?)),
50            )?)
51        })
52        .map_err(io::Error::other)?;
53        let mut copied = 0;
54        for (offset, bytes) in ranges {
55            if offset != start + copied as u64 {
56                break;
57            }
58            output[copied..copied + bytes.len()].copy_from_slice(&bytes);
59            copied += bytes.len();
60        }
61        if copied == 0 {
62            return Err(io::Error::new(
63                io::ErrorKind::UnexpectedEof,
64                "provider bytes have not been received",
65            ));
66        }
67        #[cfg(any(test, feature = "test-utils"))]
68        coven_foundation::test_work::retained_read(copied);
69        self.position += copied as u64;
70        Ok(copied)
71    }
72}
73
74impl Seek for RetainedBytes {
75    fn seek(&mut self, from: SeekFrom) -> io::Result<u64> {
76        let position = match from {
77            SeekFrom::Start(position) => Some(position),
78            SeekFrom::End(offset) => self.length.checked_add_signed(offset),
79            SeekFrom::Current(offset) => self.position.checked_add_signed(offset),
80        }
81        .ok_or_else(|| {
82            io::Error::new(io::ErrorKind::InvalidInput, "input position is outside u64")
83        })?;
84        self.position = position;
85        Ok(position)
86    }
87    fn stream_position(&mut self) -> io::Result<u64> {
88        Ok(self.position)
89    }
90}