use crate::error::{PyrucastError, Result};
use crate::handle::Handle;
use std::any::Any;
pub trait Aggregate: Default {
type Sub: Any + Send + Sync;
fn items(&self) -> &[Handle<Self::Sub>];
fn items_mut(&mut self) -> &mut Vec<Handle<Self::Sub>>;
fn type_name() -> &'static str;
fn empty() -> Self
where
Self: Sized,
{
Self::default()
}
fn sub_display_name() -> &'static str {
"item(s)"
}
fn display_extra(&self) -> Option<String> {
None
}
fn merge(&self, other: &Self) -> Result<Self>
where
Self: Sized,
{
let mut result = Self::default();
result.try_extend_from(self)?;
result.try_extend_from(other)?;
result.finalize()?;
Ok(result)
}
fn union(&self, other: &Self) -> Result<Self>
where
Self: Sized,
{
self.merge(other)
}
fn union_sub(&self, h: &Handle<Self::Sub>) -> Result<Self>
where
Self: Sized,
{
let mut out = Self::default();
out.try_extend_from(self)?;
if !out.contains_handle(h) {
out.add_sub(h.clone())?;
}
out.finalize()?;
Ok(out)
}
fn union_sub_first(&self, h: &Handle<Self::Sub>) -> Result<Self>
where
Self: Sized,
{
let mut out = Self::default();
out.add_sub(h.clone())?;
out.try_extend_from(self)?;
out.finalize()?;
Ok(out)
}
fn subset<I: IntoIterator<Item = usize>>(&self, indices: I) -> Result<Self>
where
Self: Sized,
{
let mut out = Self::default();
for i in indices {
out.add_sub(self.get(i)?)?;
}
out.finalize()?;
Ok(out)
}
fn finalize(&mut self) -> Result<()>
where
Self: Sized,
{
Ok(())
}
fn len(&self) -> usize {
self.items().len()
}
fn is_empty(&self) -> bool {
self.items().is_empty()
}
fn unit(&self) -> Result<Handle<Self::Sub>> {
match self.items() {
[h] => Ok(h.clone()),
items => Err(PyrucastError::Message(format!(
"expected a unitary {} (exactly one {}), found {}",
Self::type_name(),
Self::sub_display_name(),
items.len(),
))),
}
}
fn get(&self, i: usize) -> Result<Handle<Self::Sub>> {
self.items().get(i).cloned().ok_or_else(|| {
PyrucastError::Message(format!("index {} out of bounds (len={})", i, self.len()))
})
}
fn push(&mut self, h: Handle<Self::Sub>) {
self.items_mut().push(h);
}
fn iter(&self) -> std::slice::Iter<'_, Handle<Self::Sub>> {
self.items().iter()
}
fn extend_from(&mut self, other: &Self) {
for h in other.iter() {
self.items_mut().push(h.clone());
}
}
fn contains_handle(&self, h: &Handle<Self::Sub>) -> bool {
self.items().iter().any(|existing| existing.same_object(h))
}
fn check_push(&self, _h: &Handle<Self::Sub>) -> crate::error::Result<()> {
Ok(())
}
fn post_push(&mut self) {}
fn check_add(&self, _h: &Handle<Self::Sub>) -> crate::error::Result<()> {
Ok(())
}
fn add_sub(&mut self, h: Handle<Self::Sub>) -> crate::error::Result<()> {
self.check_push(&h)?;
self.check_add(&h)?;
self.push(h);
self.post_push();
Ok(())
}
fn add_subs(&mut self, other: &Self) -> crate::error::Result<()>
where
Self: Sized,
{
for h in other.iter() {
self.add_sub(h.clone())?;
}
Ok(())
}
fn try_extend_from(&mut self, other: &Self) -> crate::error::Result<()> {
if let Some(h) = other.items().first() {
self.check_push(h)?;
}
const SCAN_BELOW: usize = 16;
if self.len() + other.len() <= SCAN_BELOW {
for h in other.iter() {
if self.contains_handle(h) {
continue;
}
self.items_mut().push(h.clone());
self.post_push();
}
return Ok(());
}
let mut held: std::collections::HashSet<usize> =
self.items().iter().map(|h| h.id()).collect();
for h in other.iter() {
if !held.insert(h.id()) {
continue;
}
self.items_mut().push(h.clone());
self.post_push();
}
Ok(())
}
}
pub(crate) fn repeated_sub<A: Aggregate>(agg: &A) -> Option<(usize, usize)> {
for (i, h) in agg.iter().enumerate() {
if let Some(first) = agg.iter().take(i).position(|z| z.same_object(h)) {
return Some((first, i));
}
}
None
}
pub struct DebugItems<'a, S: Any + Send + Sync>(pub &'a [Handle<S>]);
impl<S: Any + Send + Sync + std::fmt::Debug> std::fmt::Debug for DebugItems<'_, S> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut map = f.debug_map();
for h in self.0 {
map.entry(h, &DebugItem(h));
}
map.finish()
}
}
pub(crate) struct Unquoted<'a>(pub(crate) &'a str);
impl std::fmt::Debug for Unquoted<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.0)
}
}
struct DebugItem<'a, S: Any + Send + Sync>(&'a Handle<S>);
impl<S: Any + Send + Sync + std::fmt::Debug> std::fmt::Debug for DebugItem<'_, S> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let s = self.0.read();
if f.alternate() {
write!(f, "{:#?}", *s)
} else {
write!(f, "{:?}", *s)
}
}
}
pub fn normalize_index(idx: isize, len: usize) -> Option<usize> {
let n = len as isize;
let i = if idx < 0 { n + idx } else { idx };
if i < 0 || i >= n {
None
} else {
Some(i as usize)
}
}
#[cfg(feature = "python-api")]
#[macro_export]
macro_rules! impl_aggregate_pymethods {
(
$T:ident, $Sub:ident, $name:literal, $sub:ident, $Inner:ty,
$stub:literal, $sub_stub:literal
$(, $components:ident)?
) => {
paste::paste! {
#[cfg_attr(
feature = "stub-gen",
pyo3_stub_gen::derive::gen_stub_pymethods
)]
#[pyo3::pymethods]
impl $T {
fn __len__(&self) -> pyo3::PyResult<usize> {
Ok($crate::aggregate::Aggregate::len(&self.inner))
}
}
#[pyo3::pymethods]
impl $T {
fn __getitem__(
&self,
py: pyo3::Python<'_>,
key: &pyo3::Bound<'_, pyo3::PyAny>,
) -> pyo3::PyResult<pyo3::Py<pyo3::PyAny>> {
let n = $crate::aggregate::Aggregate::len(&self.inner);
if let Ok(slice) = key.cast::<pyo3::types::PySlice>() {
let ind = slice.indices(n as isize)?;
let mut idxs = Vec::new();
let mut i = ind.start;
if ind.step > 0 {
while i < ind.stop {
idxs.push(i as usize);
i += ind.step;
}
} else {
while i > ind.stop {
idxs.push(i as usize);
i += ind.step;
}
}
let inner = $crate::aggregate::Aggregate::subset(&self.inner, idxs)?;
return Ok(pyo3::Py::new(py, $T { inner })?.into_any());
}
$(
let _ = stringify!($components);
if let Ok(name) = key.extract::<String>() {
let inner =
$crate::containers::field::Field::filter_components(&self.inner, name)?;
return Ok(pyo3::Py::new(py, $T { inner })?.into_any());
}
if let Ok(names) = key.extract::<Vec<String>>() {
let inner =
$crate::containers::field::Field::filter_components(&self.inner, names)?;
return Ok(pyo3::Py::new(py, $T { inner })?.into_any());
}
)?
let idx: isize = key.extract().map_err(|_| {
pyo3::exceptions::PyTypeError::new_err(concat!(
$name,
" indices must be integers or slices"
))
})?;
let i = $crate::aggregate::normalize_index(idx, n).ok_or_else(|| {
pyo3::exceptions::PyIndexError::new_err(format!(
concat!($name, " index {} out of range (len={})"),
idx, n
))
})?;
let h = $crate::aggregate::Aggregate::get(&self.inner, i)?;
Ok(pyo3::Py::new(py, $Sub { handle: h })?.into_any())
}
}
#[cfg_attr(
feature = "stub-gen",
pyo3_stub_gen::derive::gen_stub_pymethods
)]
#[pyo3::pymethods]
impl $T {
fn unit(&self) -> pyo3::PyResult<$Sub> {
let h = $crate::aggregate::Aggregate::unit(&self.inner)?;
Ok($Sub { handle: h })
}
fn add_sub(&mut self, sub: pyo3::PyRef<'_, $Sub>) -> pyo3::PyResult<()> {
$crate::aggregate::Aggregate::add_sub(&mut self.inner, sub.handle.clone())?;
Ok(())
}
fn add_subs(&mut self, other: pyo3::PyRef<'_, $T>) -> pyo3::PyResult<()> {
$crate::aggregate::Aggregate::add_subs(&mut self.inner, &other.inner)?;
Ok(())
}
fn __repr__(&self) -> pyo3::PyResult<String> {
Ok(format!("{:?}", self.inner))
}
fn __str__(&self) -> pyo3::PyResult<String> {
Ok(format!("{}", self.inner))
}
#[pyo3(signature = (precision=3, max_rows=20, max_cols=12))]
fn dump(
&self,
py: pyo3::Python<'_>,
precision: usize,
max_rows: usize,
max_cols: usize,
) -> pyo3::PyResult<()> {
let text = $crate::dump::Dump::render(
&self.inner,
&$crate::dump::DumpOptions { precision, max_rows, max_cols },
);
$crate::dump::py_print(py, &text)
}
}
#[pyo3::pymethods]
impl $T {
fn __or__(
&self,
py: pyo3::Python<'_>,
other: &pyo3::Bound<'_, pyo3::PyAny>,
) -> pyo3::PyResult<pyo3::Py<pyo3::PyAny>> {
use $crate::aggregate::Aggregate;
if let Ok(o) = other.extract::<pyo3::PyRef<'_, $T>>() {
let inner = self.inner.union(&o.inner)?;
return Ok(pyo3::Py::new(py, $T { inner })?.into_any());
}
if let Ok(s) = other.extract::<pyo3::PyRef<'_, $Sub>>() {
let inner = self.inner.union_sub(&s.handle)?;
return Ok(pyo3::Py::new(py, $T { inner })?.into_any());
}
Ok(py.NotImplemented())
}
fn __ror__(
&self,
py: pyo3::Python<'_>,
other: &pyo3::Bound<'_, pyo3::PyAny>,
) -> pyo3::PyResult<pyo3::Py<pyo3::PyAny>> {
use $crate::aggregate::Aggregate;
if let Ok(s) = other.extract::<pyo3::PyRef<'_, $Sub>>() {
let inner = self.inner.union_sub_first(&s.handle)?;
return Ok(pyo3::Py::new(py, $T { inner })?.into_any());
}
Ok(py.NotImplemented())
}
}
#[pyo3::pymethods]
impl $Sub {
fn __or__(
&self,
py: pyo3::Python<'_>,
other: &pyo3::Bound<'_, pyo3::PyAny>,
) -> pyo3::PyResult<pyo3::Py<pyo3::PyAny>> {
if let Ok(o) = other.extract::<pyo3::PyRef<'_, $Sub>>() {
let inner = <$Inner>::union_subs(&self.handle, &o.handle)?;
return Ok(pyo3::Py::new(py, $T { inner })?.into_any());
}
Ok(py.NotImplemented())
}
}
#[cfg(feature = "stub-gen")]
pyo3_stub_gen::inventory::submit! {
pyo3_stub_gen::derive::gen_methods_from_python! { $stub }
}
#[cfg(feature = "stub-gen")]
pyo3_stub_gen::inventory::submit! {
pyo3_stub_gen::derive::gen_methods_from_python! { $sub_stub }
}
}
};
}
#[cfg(feature = "python-api")]
#[macro_export]
macro_rules! impl_dump_pymethod {
(handle $PyT:ty, $field:ident) => {
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pymethods)]
#[pyo3::pymethods]
impl $PyT {
fn __str__(&self) -> pyo3::PyResult<String> {
Ok(format!("{}", *self.$field.read()))
}
fn __repr__(&self) -> pyo3::PyResult<String> {
Ok(format!("{:?}", *self.$field.read()))
}
#[pyo3(signature = (precision=3, max_rows=20, max_cols=12))]
fn dump(
&self,
py: pyo3::Python<'_>,
precision: usize,
max_rows: usize,
max_cols: usize,
) -> pyo3::PyResult<()> {
let opts = $crate::dump::DumpOptions {
precision,
max_rows,
max_cols,
};
let text = $crate::dump::Dump::render(&*self.$field.read(), &opts);
$crate::dump::py_print(py, &text)
}
}
};
(value $PyT:ty, $field:ident) => {
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pymethods)]
#[pyo3::pymethods]
impl $PyT {
fn __str__(&self) -> pyo3::PyResult<String> {
Ok(format!("{}", self.$field))
}
fn __repr__(&self) -> pyo3::PyResult<String> {
Ok(format!("{:?}", self.$field))
}
#[pyo3(signature = (precision=3, max_rows=20, max_cols=12))]
fn dump(
&self,
py: pyo3::Python<'_>,
precision: usize,
max_rows: usize,
max_cols: usize,
) -> pyo3::PyResult<()> {
let opts = $crate::dump::DumpOptions {
precision,
max_rows,
max_cols,
};
let text = $crate::dump::Dump::render(&self.$field, &opts);
$crate::dump::py_print(py, &text)
}
}
};
}
#[macro_export]
macro_rules! impl_aggregate {
($T:ty, $Sub:ty, $sub:ident, $name:literal) => {
$crate::impl_aggregate!($T, $Sub, $sub, $name, {});
};
($T:ty, $Sub:ty, $sub:ident, $name:literal, { $($override:tt)* }) => {
paste::paste! {
impl $crate::aggregate::Aggregate for $T {
type Sub = $Sub;
fn items(&self) -> &[$crate::handle::Handle<$Sub>] { &self.subs }
fn items_mut(&mut self) -> &mut Vec<$crate::handle::Handle<$Sub>> {
&mut self.subs
}
fn type_name() -> &'static str { stringify!($T) }
fn sub_display_name() -> &'static str { $name }
$($override)*
}
$crate::impl_aggregate_std_traits!($T);
}
};
}
#[macro_export]
macro_rules! impl_aggregate_std_traits {
($T:ty) => {
impl std::ops::Index<usize> for $T {
type Output = $crate::handle::Handle<<$T as $crate::aggregate::Aggregate>::Sub>;
fn index(&self, idx: usize) -> &Self::Output {
&$crate::aggregate::Aggregate::items(self)[idx]
}
}
impl<'a> IntoIterator for &'a $T {
type Item = &'a $crate::handle::Handle<<$T as $crate::aggregate::Aggregate>::Sub>;
type IntoIter = std::slice::Iter<
'a,
$crate::handle::Handle<<$T as $crate::aggregate::Aggregate>::Sub>,
>;
fn into_iter(self) -> Self::IntoIter {
$crate::aggregate::Aggregate::iter(self)
}
}
impl std::fmt::Debug for $T {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let extra = <$T as $crate::aggregate::Aggregate>::display_extra(self);
let extra = extra.as_deref().map(|e| e.trim_start_matches(", "));
let mut s = f.debug_struct(<$T as $crate::aggregate::Aggregate>::type_name());
s.field("count", &$crate::aggregate::Aggregate::len(self));
if let Some(extra) = extra {
s.field("summary", &$crate::aggregate::Unquoted(extra));
}
s.field(
"items",
&$crate::aggregate::DebugItems($crate::aggregate::Aggregate::items(self)),
)
.finish()
}
}
impl std::fmt::Display for $T {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}: {} {}",
<$T as $crate::aggregate::Aggregate>::type_name(),
$crate::aggregate::Aggregate::len(self),
<$T as $crate::aggregate::Aggregate>::sub_display_name(),
)?;
let items = $crate::aggregate::Aggregate::items(self);
if !items.is_empty() {
f.write_str(" [")?;
for (i, h) in items.iter().take(3).enumerate() {
if i > 0 {
f.write_str(", ")?;
}
write!(f, "#{:x}", h.tag())?;
}
if items.len() > 3 {
write!(f, ", … +{}", items.len() - 3)?;
}
f.write_str("]")?;
}
if let Some(extra) = $crate::aggregate::Aggregate::display_extra(self) {
f.write_str(&extra)?;
}
Ok(())
}
}
impl $T {
pub fn union_subs(
a: &$crate::handle::Handle<<$T as $crate::aggregate::Aggregate>::Sub>,
b: &$crate::handle::Handle<<$T as $crate::aggregate::Aggregate>::Sub>,
) -> $crate::error::Result<$T> {
use $crate::aggregate::Aggregate;
let mut out = <$T as ::std::default::Default>::default();
out.add_sub(a.clone())?;
if !a.same_object(b) {
out.add_sub(b.clone())?;
}
out.finalize()?;
Ok(out)
}
}
};
}
#[macro_export]
macro_rules! impl_aggregate_dump {
($T:ty) => {
impl $crate::dump::Dump for $T {
fn render(&self, opts: &$crate::dump::DumpOptions) -> String {
let mut out = format!("{self}\n");
for (i, h) in $crate::aggregate::Aggregate::items(self).iter().enumerate() {
let body = $crate::dump::Dump::render(&*h.read(), opts);
out.push_str(&format!("── [{i}] {h} ──\n"));
for line in body.lines() {
out.push_str(" ");
out.push_str(line);
out.push('\n');
}
}
out
}
}
};
}
#[cfg(test)]
mod tests {
use super::*;
use crate::handle::Handle;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
struct Item(u32);
#[derive(Default)]
struct Bag {
items: Vec<Handle<Item>>,
}
impl Aggregate for Bag {
type Sub = Item;
fn items(&self) -> &[Handle<Item>] {
&self.items
}
fn items_mut(&mut self) -> &mut Vec<Handle<Item>> {
&mut self.items
}
fn type_name() -> &'static str {
"Bag"
}
}
#[test]
fn empty_bag_is_empty() {
let b = Bag::default();
assert_eq!(b.len(), 0);
assert!(b.is_empty());
assert!(b.get(0).is_err());
}
#[test]
fn push_then_get() {
let mut b = Bag::default();
b.push(Handle::new(Item(1)));
b.push(Handle::new(Item(2)));
b.push(Handle::new(Item(3)));
assert_eq!(b.len(), 3);
let h = b.get(1).unwrap();
assert_eq!(h.read().0, 2);
}
#[test]
fn add_subs_concatenates_without_deduplicating() {
let shared = Handle::new(Item(2));
let mut a = Bag::default();
a.push(Handle::new(Item(1)));
a.push(shared.clone());
let mut b = Bag::default();
b.push(shared.clone()); b.push(Handle::new(Item(3)));
a.add_subs(&b).unwrap();
let collected: Vec<u32> = a.iter().map(|h| h.read().0).collect();
assert_eq!(collected, vec![1, 2, 2, 3]);
assert!(a.get(2).unwrap().same_object(&shared));
assert_eq!(b.len(), 2);
}
#[test]
fn iter_walks_in_order() {
let mut b = Bag::default();
b.push(Handle::new(Item(10)));
b.push(Handle::new(Item(20)));
let collected: Vec<u32> = b.iter().map(|h| h.read().0).collect();
assert_eq!(collected, vec![10, 20]);
}
#[test]
fn out_of_bounds_message_includes_len() {
let b = Bag::default();
let err = b.get(5).unwrap_err();
let msg = format!("{}", err);
assert!(msg.contains("out of bounds"));
assert!(msg.contains("len=0"));
}
#[test]
fn unit_returns_sole_handle_or_errors() {
let mut b = Bag::default();
assert!(b.unit().is_err()); b.push(Handle::new(Item(7)));
let h = b.unit().unwrap();
assert_eq!(h.read().0, 7);
b.push(Handle::new(Item(8)));
assert!(b.unit().is_err()); }
#[test]
fn union_sub_first_mirrors_union_sub() {
let mut b = Bag::default();
b.push(Handle::new(Item(1)));
b.push(Handle::new(Item(2)));
let h = Handle::new(Item(3));
let appended = b.union_sub(&h).unwrap();
let prepended = b.union_sub_first(&h).unwrap();
let values = |bag: &Bag| -> Vec<u32> { bag.iter().map(|h| h.read().0).collect() };
assert_eq!(values(&appended), vec![1, 2, 3]);
assert_eq!(values(&prepended), vec![3, 1, 2]);
let already = b.get(1).unwrap();
assert_eq!(values(&b.union_sub_first(&already).unwrap()), vec![2, 1]);
}
#[test]
fn normalize_negative_index() {
assert_eq!(normalize_index(0, 3), Some(0));
assert_eq!(normalize_index(2, 3), Some(2));
assert_eq!(normalize_index(-1, 3), Some(2));
assert_eq!(normalize_index(-3, 3), Some(0));
assert_eq!(normalize_index(-4, 3), None);
assert_eq!(normalize_index(3, 3), None);
assert_eq!(normalize_index(0, 0), None);
}
}