Skip to content

Commit

Permalink
use python bytes
Browse files Browse the repository at this point in the history
  • Loading branch information
abyesilyurt committed Oct 7, 2024
1 parent 7a864c4 commit a68e979
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 12 deletions.
29 changes: 18 additions & 11 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use pyo3::prelude::*;
use fast_rsync::{Signature, SignatureOptions};
use pyo3::types::PyBytes;

/// Formats the sum of two numbers as string.
#[pyfunction]
Expand All @@ -8,35 +9,41 @@ fn sum_as_string(a: usize, b: usize) -> PyResult<String> {
}



#[pyfunction]
fn diff(data: &[u8], new_data: &[u8]) -> PyResult<Vec<u8>> {
fn diff(py: Python, data: &[u8], new_data: &[u8]) -> PyResult<Py<PyBytes>> {
// Calculate the signature and store it in a variable
let calculated_signature = Signature::calculate(
data,
SignatureOptions {
block_size: 4096,
block_size: 4096, // Adjust this based on your data characteristics
crypto_hash_size: 8,
},
);

// Index the signature
let signature = calculated_signature.index();

let mut out = Vec::new();
fast_rsync::diff(&signature, new_data, &mut out).unwrap();
// Return the delta as a byte vector
Ok(out)
let mut out = Vec::with_capacity(new_data.len()); // Pre-allocate memory for the output
fast_rsync::diff(&signature, new_data, &mut out)
.map_err(|e| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(format!("Diff error: {:?}", e)))?;

// Convert Vec<u8> to PyBytes and return
Ok(PyBytes::new_bound(py, &out).into())
}

#[pyfunction]
fn apply(base: &[u8], delta: &[u8]) -> PyResult<Vec<u8>> {
fn apply(py: Python, base: &[u8], delta: &[u8]) -> PyResult<Py<PyBytes>> {
// Apply the delta to the data
let mut out = Vec::new();
fast_rsync::apply(base, delta, &mut out).unwrap();
// Return the patched data as a byte vector
Ok(out)
let mut out = Vec::with_capacity(base.len() + delta.len()); // Pre-allocate memory for the output
fast_rsync::apply(base, delta, &mut out)
.map_err(|e| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(format!("Apply error: {:?}", e)))?;

// Convert Vec<u8> to PyBytes and return
Ok(PyBytes::new_bound(py, &out).into())
}


/// A Python module implemented in Rust.
#[pymodule]
fn py_fast_rsync(m: &Bound<'_, PyModule>) -> PyResult<()> {
Expand Down
1 change: 0 additions & 1 deletion tests/test_fast_rsync.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ def test_diff():
byte_data1 = b"hello world"
byte_data2 = b"hello world!"
diff = py_fast_rsync.diff(byte_data1, byte_data2)
print(diff)

new_data = py_fast_rsync.apply(byte_data1, diff)
assert new_data == byte_data2

0 comments on commit a68e979

Please sign in to comment.