Skip to content

Commit

Permalink
[python] Implement items on Peers
Browse files Browse the repository at this point in the history
  • Loading branch information
jopemachine committed Jan 2, 2024
1 parent 865729a commit 83d0f8c
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 2 deletions.
1 change: 1 addition & 0 deletions binding/python/raftify.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ class Peers:
""" """

def __init__(self, peers: dict) -> None: ...
def items(self) -> list[tuple[int, str]]: ...
def get(self, node_id: int) -> str: ...
def add_peer(self, node_id: int, addr: str) -> None: ...
def remove(self, node_id: int) -> None: ...
Expand Down
14 changes: 13 additions & 1 deletion binding/python/src/bindings/peers.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
use fxhash::FxHasher;
use pyo3::{
prelude::*,
types::{PyDict, PyString},
types::{PyDict, PyString, PyTuple},
};
use raftify::Peers;
use std::{collections::HashMap, hash::BuildHasherDefault};

use super::utils::new_py_list;

#[derive(Clone)]
#[pyclass(name = "Peers")]
pub struct PyPeers {
Expand Down Expand Up @@ -33,6 +35,16 @@ impl PyPeers {
Ok(format!("{:?}", self.inner))
}

pub fn items(&self, py: Python) -> PyResult<PyObject> {
let peer_items = self
.inner
.iter()
.map(|(id, peer)| (id, peer.addr.to_string()))
.collect::<Vec<(u64, String)>>();

Ok(new_py_list::<(u64, String), _>(py, peer_items)?.to_object(py))
}

// TODO: Replace String with Peer
pub fn get(&self, node_id: u64) -> Option<String> {
self.inner
Expand Down
17 changes: 16 additions & 1 deletion binding/python/src/bindings/utils.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,20 @@
use pyo3::prelude::*;
use pyo3::{prelude::*, types::PyList};

pub fn get_python_repr(obj: &PyAny) -> String {
obj.call_method("__repr__", (), None).unwrap().to_string()
}

pub fn new_py_list<T, U>(
py: Python<'_>,
elements: impl IntoIterator<Item = T, IntoIter = U>,
) -> PyResult<&PyList>
where
T: ToPyObject,
U: ExactSizeIterator<Item = T>,
{
let items = elements
.into_iter()
.map(|e| e.to_object(py))
.collect::<Vec<_>>();
Ok(PyList::new(py, &items))
}

0 comments on commit 83d0f8c

Please sign in to comment.