sqlite_compressions/
bsdiff4.rs

1use std::io::Cursor;
2
3use qbsdiff::bsdiff::Bsdiff;
4use qbsdiff::bspatch::Bspatch;
5use rusqlite::Error::UserFunctionError;
6
7use crate::common_diff::{register_differ, Differ};
8use crate::rusqlite::{Connection, Result};
9
10/// Register the `bsdiff4` and `bspatch4` SQL functions with the given `SQLite` connection.
11/// The `bsdiff4` function takes two arguments, and returns the [BSDiff delta](https://github.com/mendsley/bsdiff#readme) (blob) of the binary difference.
12/// The arguments can be either a string or a blob.
13/// If any of the arguments are `NULL`, the result is `NULL`.
14///
15/// # Example
16///
17/// ```
18/// # use sqlite_compressions::rusqlite::{Connection, Result};
19/// # use sqlite_compressions::register_bsdiff4_functions;
20/// # fn main() -> Result<()> {
21/// let db = Connection::open_in_memory()?;
22/// register_bsdiff4_functions(&db)?;
23/// let result: Vec<u8> = db.query_row("SELECT bspatch4('013479', bsdiff4('013479', '23456789'))", [], |r| r.get(0))?;
24/// let expected = b"23456789";
25/// assert_eq!(result, expected);
26/// # Ok(())
27/// # }
28/// ```
29pub fn register_bsdiff4_functions(conn: &Connection) -> Result<()> {
30    register_differ::<Bsdiff4Differ>(conn)
31}
32
33pub struct Bsdiff4Differ;
34
35impl Differ for Bsdiff4Differ {
36    fn diff_name() -> &'static str {
37        "bsdiff4"
38    }
39
40    fn patch_name() -> &'static str {
41        "bspatch4"
42    }
43
44    fn diff(source: &[u8], target: &[u8]) -> Result<Vec<u8>> {
45        let mut patch = Vec::new();
46        Bsdiff::new(source, target)
47            .compare(Cursor::new(&mut patch))
48            .map_err(|e| UserFunctionError(e.into()))?;
49        Ok(patch)
50    }
51
52    fn patch(source: &[u8], patch: &[u8]) -> Result<Vec<u8>> {
53        let mut target = Vec::new();
54        Bspatch::new(patch)
55            .and_then(|patch| patch.apply(source, Cursor::new(&mut target)))
56            .map_err(|e| UserFunctionError(e.into()))?;
57        Ok(target)
58    }
59}