Skip to content

Instantly share code, notes, and snippets.

@eu90h
Created March 15, 2024 15:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eu90h/4388e755c12a9d0d9631cb685ddeebb3 to your computer and use it in GitHub Desktop.
Save eu90h/4388e755c12a9d0d9631cb685ddeebb3 to your computer and use it in GitHub Desktop.
A silly PyO3 example to demonstrate memory allocation.
#[pyfunction]
fn process_file(file: &PyAny, callback: &PyAny) {
assert!(callback.is_callable());
let file = file.to_string();
if let Ok(lines) = read_lines(file) {
for line in lines {
Python::with_gil(|py| {
let pool = unsafe { py.new_pool() };
let py = pool.python();
for msg in line.unwrap().replace("}{", "}\n{").split("\n") {
let mut msg = msg.to_owned();
let obj: Value = unsafe { simd_json::serde::from_str(&mut msg).expect("JSON parsing failed") };
let py_msg = PyDict::new(py);
for (key, value) in obj.as_object().unwrap() {
py_msg.set_item(key, value).expect("failed to set key");
}
callback.call(PyTuple::new(py, vec![py_msg]), None).expect("failed to invoke callback");
}
});
}
}
}
#[pyfunction]
fn process_file(file: &PyAny, callback: &PyAny) {
assert!(callback.is_callable());
let file = file.to_string();
if let Ok(lines) = read_lines(file) {
for line in lines {
for msg in line.unwrap().replace("}{", "}\n{").split("\n") {
let mut msg = msg.to_owned();
let obj: Value = unsafe { simd_json::serde::from_str(&mut msg).expect("JSON parsing failed") };
let py_msg = PyDict::new(py);
for (key, value) in obj.as_object().unwrap() {
py_msg.set_item(key, value).expect("failed to set key");
}
callback.call(PyTuple::new(py, vec![py_msg]), None).expect("failed to invoke callback");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment