|
| 1 | +use pyo3::prelude::*; |
| 2 | +use pyo3::create_exception; |
| 3 | +use pyo3::wrap_pyfunction; |
| 4 | +use pyo3::types::{PyBytes, PyTuple}; |
| 5 | +use pyo3::exceptions; |
| 6 | + |
| 7 | +use std::sync::{Arc, Mutex}; |
| 8 | +use streamson_lib::{error, handler, matcher, Collector}; |
| 9 | + |
| 10 | +create_exception!(streamson, StreamsonError, exceptions::ValueError); |
| 11 | + |
| 12 | +impl From<error::General> for StreamsonError { |
| 13 | + fn from(gerror: error::General) -> Self { |
| 14 | + Self |
| 15 | + } |
| 16 | +} |
| 17 | + |
| 18 | +/// Low level Python wrapper for Simple matcher and Buffer handler |
| 19 | +#[pyclass] |
| 20 | +pub struct SimpleStreamson { |
| 21 | + collector: Collector, |
| 22 | + handler: Arc<Mutex<handler::Buffer>>, |
| 23 | +} |
| 24 | + |
| 25 | +#[pymethods] |
| 26 | +impl SimpleStreamson { |
| 27 | + |
| 28 | + /// Create a new instance of SimpleStreamson |
| 29 | + /// |
| 30 | + /// # Arguments |
| 31 | + /// * `matches` - a list of valid simple matches (e.g. `{"users"}`, `[]{"name"}`, `[0]{}`) |
| 32 | + #[new] |
| 33 | + pub fn new(matches: Vec<String>) -> Self { |
| 34 | + let handler = Arc::new(Mutex::new(handler::Buffer::new())); |
| 35 | + let mut collector = Collector::new(); |
| 36 | + for path_match in matches { |
| 37 | + collector = collector.add_matcher( |
| 38 | + Box::new(matcher::Simple::new(path_match)), |
| 39 | + &[handler.clone()], |
| 40 | + ); |
| 41 | + } |
| 42 | + Self { collector, handler } |
| 43 | + } |
| 44 | + |
| 45 | + /// Feeds Streamson processor with data |
| 46 | + /// |
| 47 | + /// # Arguments |
| 48 | + /// * `data` - input data to be processed |
| 49 | + pub fn feed(&mut self, data: &[u8]) -> PyResult<()> { |
| 50 | + if let Err(err) = self.collector.process(data) { |
| 51 | + Err(StreamsonError::from(err).into()) |
| 52 | + } else { |
| 53 | + Ok(()) |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + /// Reads data from Buffer handler |
| 58 | + /// |
| 59 | + /// # Returns |
| 60 | + /// * `None` - if no data present |
| 61 | + /// * `Some(<path>, <bytes>)` if there are some data |
| 62 | + fn pop(&mut self) -> Option<(String, Vec<u8>)>{ |
| 63 | + |
| 64 | + match self.handler.lock().unwrap().pop() { |
| 65 | + Some((path, bytes)) => { |
| 66 | + Some((path, bytes.to_vec())) |
| 67 | + }, |
| 68 | + None => None, |
| 69 | + } |
| 70 | + |
| 71 | + } |
| 72 | +} |
| 73 | +/// This module is a python module implemented in Rust. |
| 74 | +#[pymodule] |
| 75 | +fn streamson(py: Python, m: &PyModule) -> PyResult<()> { |
| 76 | + m.add_class::<SimpleStreamson>()?; |
| 77 | + |
| 78 | + Ok(()) |
| 79 | +} |
0 commit comments