Debian Codegraph @

third_party/rust/rusqlite/src/blob/pos_io.rs

raw
1 use super::Blob;
2
3 use std::mem::MaybeUninit;
4 use std::slice::from_raw_parts_mut;
5
6 use crate::ffi;
7 use crate::{Error, Result};
8
9 impl Blob<'_> {
10 /// Write `buf` to `self` starting at `write_start`, returning an error if
11 /// `write_start + buf.len()` is past the end of the blob.
12 ///
13 /// If an error is returned, no data is written.
14 ///
15 /// Note: the blob cannot be resized using this function -- that must be
16 /// done using SQL (for example, an `UPDATE` statement).
17 ///
18 /// Note: This is part of the positional I/O API, and thus takes an absolute
19 /// position write to, instead of using the internal position that can be
20 /// manipulated by the `std::io` traits.
21 ///
22 /// Unlike the similarly named [`FileExt::write_at`][fext_write_at] function
23 /// (from `std::os::unix`), it's always an error to perform a "short write".
24 ///
25 /// [fext_write_at]: https://doc.rust-lang.org/std/os/unix/fs/trait.FileExt.html#tymethod.write_at
26 #[inline]
27 pub fn write_at(&mut self, buf: &[u8], write_start: usize) -> Result<()> {
28 let len = self.len();
29
30 if buf.len().saturating_add(write_start) > len {
31 return Err(Error::BlobSizeError);
32 }
33 // We know `len` fits in an `i32`, so either:
34 //
35 // 1. `buf.len() + write_start` overflows, in which case we'd hit the
36 // return above (courtesy of `saturating_add`).
37 //
38 // 2. `buf.len() + write_start` doesn't overflow but is larger than len,
39 // in which case ditto.
40 //
41 // 3. `buf.len() + write_start` doesn't overflow but is less than len.
42 // This means that both `buf.len()` and `write_start` can also be
43 // losslessly converted to i32, since `len` came from an i32.
44 // Sanity check the above.
45 debug_assert!(i32::try_from(write_start).is_ok() && i32::try_from(buf.len()).is_ok());
46 self.conn.decode_result(unsafe {
47 ffi::sqlite3_blob_write(
48 self.blob,
49 buf.as_ptr().cast(),
50 buf.len() as i32,
51 write_start as i32,
52 )
53 })
54 }
55
56 /// An alias for `write_at` provided for compatibility with the conceptually
57 /// equivalent [`std::os::unix::FileExt::write_all_at`][write_all_at]
58 /// function from libstd:
59 ///
60 /// [write_all_at]: https://doc.rust-lang.org/std/os/unix/fs/trait.FileExt.html#method.write_all_at
61 #[inline]
62 pub fn write_all_at(&mut self, buf: &[u8], write_start: usize) -> Result<()> {
63 self.write_at(buf, write_start)
64 }
65
66 /// Read as much as possible from `offset` to `offset + buf.len()` out of
67 /// `self`, writing into `buf`. On success, returns the number of bytes
68 /// written.
69 ///
70 /// If there's insufficient data in `self`, then the returned value will be
71 /// less than `buf.len()`.
72 ///
73 /// See also [`Blob::raw_read_at`], which can take an uninitialized buffer,
74 /// or [`Blob::read_at_exact`] which returns an error if the entire `buf` is
75 /// not read.
76 ///
77 /// Note: This is part of the positional I/O API, and thus takes an absolute
78 /// position to read from, instead of using the internal position that can
79 /// be manipulated by the `std::io` traits. Consequently, it does not change
80 /// that value either.
81 #[inline]
82 pub fn read_at(&self, buf: &mut [u8], read_start: usize) -> Result<usize> {
83 // Safety: this is safe because `raw_read_at` never stores uninitialized
84 // data into `as_uninit`.
85 let as_uninit: &mut [MaybeUninit<u8>] =
86 unsafe { from_raw_parts_mut(buf.as_mut_ptr().cast(), buf.len()) };
87 self.raw_read_at(as_uninit, read_start).map(|s| s.len())
88 }
89
90 /// Read as much as possible from `offset` to `offset + buf.len()` out of
91 /// `self`, writing into `buf`. On success, returns the portion of `buf`
92 /// which was initialized by this call.
93 ///
94 /// If there's insufficient data in `self`, then the returned value will be
95 /// shorter than `buf`.
96 ///
97 /// See also [`Blob::read_at`], which takes a `&mut [u8]` buffer instead of
98 /// a slice of `MaybeUninit<u8>`.
99 ///
100 /// Note: This is part of the positional I/O API, and thus takes an absolute
101 /// position to read from, instead of using the internal position that can
102 /// be manipulated by the `std::io` traits. Consequently, it does not change
103 /// that value either.
104 #[inline]
105 pub fn raw_read_at<'a>(
106 &self,
107 buf: &'a mut [MaybeUninit<u8>],
108 read_start: usize,
109 ) -> Result<&'a mut [u8]> {
110 let len = self.len();
111
112 let read_len = match len.checked_sub(read_start) {
113 None | Some(0) => 0,
114 Some(v) => v.min(buf.len()),
115 };
116
117 if read_len == 0 {
118 // We could return `Ok(&mut [])`, but it seems confusing that the
119 // pointers don't match, so fabricate an empty slice of u8 with the
120 // same base pointer as `buf`.
121 let empty = unsafe { from_raw_parts_mut(buf.as_mut_ptr().cast::<u8>(), 0) };
122 return Ok(empty);
123 }
124
125 // At this point we believe `read_start as i32` is lossless because:
126 //
127 // 1. `len as i32` is known to be lossless, since it comes from a SQLite
128 // api returning an i32.
129 //
130 // 2. If we got here, `len.checked_sub(read_start)` was Some (or else
131 // we'd have hit the `if read_len == 0` early return), so `len` must
132 // be larger than `read_start`, and so it must fit in i32 as well.
133 debug_assert!(i32::try_from(read_start).is_ok());
134
135 // We also believe that `read_start + read_len <= len` because:
136 //
137 // 1. This is equivalent to `read_len <= len - read_start` via algebra.
138 // 2. We know that `read_len` is `min(len - read_start, buf.len())`
139 // 3. Expanding, this is `min(len - read_start, buf.len()) <= len - read_start`,
140 // or `min(A, B) <= A` which is clearly true.
141 //
142 // Note that this stuff is in debug_assert so no need to use checked_add
143 // and such -- we'll always panic on overflow in debug builds.
144 debug_assert!(read_start + read_len <= len);
145
146 // These follow naturally.
147 debug_assert!(buf.len() >= read_len);
148 debug_assert!(i32::try_from(buf.len()).is_ok());
149 debug_assert!(i32::try_from(read_len).is_ok());
150
151 unsafe {
152 self.conn.decode_result(ffi::sqlite3_blob_read(
153 self.blob,
154 buf.as_mut_ptr().cast(),
155 read_len as i32,
156 read_start as i32,
157 ))?;
158
159 Ok(from_raw_parts_mut(buf.as_mut_ptr().cast::<u8>(), read_len))
160 }
161 }
162
163 /// Equivalent to [`Blob::read_at`], but returns a `BlobSizeError` if `buf`
164 /// is not fully initialized.
165 #[inline]
166 pub fn read_at_exact(&self, buf: &mut [u8], read_start: usize) -> Result<()> {
167 let n = self.read_at(buf, read_start)?;
168 if n != buf.len() {
169 Err(Error::BlobSizeError)
170 } else {
171 Ok(())
172 }
173 }
174
175 /// Equivalent to [`Blob::raw_read_at`], but returns a `BlobSizeError` if
176 /// `buf` is not fully initialized.
177 #[inline]
178 pub fn raw_read_at_exact<'a>(
179 &self,
180 buf: &'a mut [MaybeUninit<u8>],
181 read_start: usize,
182 ) -> Result<&'a mut [u8]> {
183 let buflen = buf.len();
184 let initted = self.raw_read_at(buf, read_start)?;
185 if initted.len() != buflen {
186 Err(Error::BlobSizeError)
187 } else {
188 Ok(initted)
189 }
190 }
191 }
192
193 #[cfg(test)]
194 mod test {
195 use crate::{Connection, DatabaseName, Result};
196 // to ensure we don't modify seek pos
197 use std::io::Seek as _;
198
199 #[test]
200 fn test_pos_io() -> Result<()> {
201 let db = Connection::open_in_memory()?;
202 db.execute_batch("CREATE TABLE test_table(content BLOB);")?;
203 db.execute("INSERT INTO test_table(content) VALUES (ZEROBLOB(10))", [])?;
204
205 let rowid = db.last_insert_rowid();
206 let mut blob = db.blob_open(DatabaseName::Main, "test_table", "content", rowid, false)?;
207 // modify the seek pos to ensure we aren't using it or modifying it.
208 blob.seek(std::io::SeekFrom::Start(1)).unwrap();
209
210 let one2ten: [u8; 10] = [1u8, 2, 3, 4, 5, 6, 7, 8, 9, 10];
211 blob.write_at(&one2ten, 0)?;
212
213 let mut s = [0u8; 10];
214 blob.read_at_exact(&mut s, 0)?;
215 assert_eq!(&s, &one2ten, "write should go through");
216 blob.read_at_exact(&mut s, 1).unwrap_err();
217
218 blob.read_at_exact(&mut s, 0)?;
219 assert_eq!(&s, &one2ten, "should be unchanged");
220
221 let mut fives = [0u8; 5];
222 blob.read_at_exact(&mut fives, 0)?;
223 assert_eq!(&fives, &[1u8, 2, 3, 4, 5]);
224
225 blob.read_at_exact(&mut fives, 5)?;
226 assert_eq!(&fives, &[6u8, 7, 8, 9, 10]);
227 blob.read_at_exact(&mut fives, 7).unwrap_err();
228 blob.read_at_exact(&mut fives, 12).unwrap_err();
229 blob.read_at_exact(&mut fives, 10).unwrap_err();
230 blob.read_at_exact(&mut fives, i32::MAX as usize)
231 .unwrap_err();
232 blob.read_at_exact(&mut fives, i32::MAX as usize + 1)
233 .unwrap_err();
234
235 // zero length writes are fine if in bounds
236 blob.read_at_exact(&mut [], 10)?;
237 blob.read_at_exact(&mut [], 0)?;
238 blob.read_at_exact(&mut [], 5)?;
239
240 blob.write_all_at(&[16, 17, 18, 19, 20], 5)?;
241 blob.read_at_exact(&mut s, 0)?;
242 assert_eq!(&s, &[1u8, 2, 3, 4, 5, 16, 17, 18, 19, 20]);
243
244 blob.write_at(&[100, 99, 98, 97, 96], 6).unwrap_err();
245 blob.write_at(&[100, 99, 98, 97, 96], i32::MAX as usize)
246 .unwrap_err();
247 blob.write_at(&[100, 99, 98, 97, 96], i32::MAX as usize + 1)
248 .unwrap_err();
249
250 blob.read_at_exact(&mut s, 0)?;
251 assert_eq!(&s, &[1u8, 2, 3, 4, 5, 16, 17, 18, 19, 20]);
252
253 let mut s2: [std::mem::MaybeUninit<u8>; 10] = [std::mem::MaybeUninit::uninit(); 10];
254 {
255 let read = blob.raw_read_at_exact(&mut s2, 0)?;
256 assert_eq!(read, &s);
257 assert!(std::ptr::eq(read.as_ptr(), s2.as_ptr().cast()));
258 }
259
260 let mut empty = [];
261 assert!(std::ptr::eq(
262 blob.raw_read_at_exact(&mut empty, 0)?.as_ptr(),
263 empty.as_ptr().cast(),
264 ));
265 blob.raw_read_at_exact(&mut s2, 5).unwrap_err();
266
267 let end_pos = blob.stream_position().unwrap();
268 assert_eq!(end_pos, 1);
269 Ok(())
270 }
271 }