use std::collections::HashMap;
use std::collections::HashSet;
use std::collections::hash_map::Entry;
use std::fmt;
use std::hash::Hash;
use std::marker::PhantomData;
use serde::Deserialize;
use serde::Deserializer;
use serde::Serialize;
use serde::Serializer;
use serde::ser::SerializeStruct as _;
pub mod defaults;
pub trait Markable {
type Mark;
fn get_mark(&self) -> Option<&Self::Mark>;
fn set_mark(&mut self, mark: Self::Mark) -> Option<Self::Mark>;
fn clear_mark(&mut self) -> Option<Self::Mark>;
}
pub trait Node: Clone + Default + PartialEq {
type Update;
type Diff;
const IS_CONTAINER: bool;
fn apply_update(&mut self, update: Self::Update);
fn as_update(&self) -> Self::Update;
fn compute_diff(&self, other: &Self) -> Option<Self::Diff>;
fn apply_diff(&mut self, diff: Self::Diff);
fn as_diff(&self) -> Self::Diff;
fn merge(&self, merge: &mut Self);
fn is_empty(&self) -> bool;
}
#[derive(Debug, Default, PartialEq, Eq, Clone, Hash)]
pub struct Value<V> {
pub(crate) value: V,
pub(crate) default: DefaultValueConstructor<V>,
}
impl<V: Serialize> Serialize for Value<V> {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
self.value.serialize(serializer)
}
}
impl<V> AsRef<V> for Value<V> {
fn as_ref(&self) -> &V {
self.value()
}
}
impl<V> Value<V> {
pub fn value(&self) -> &V {
&self.value
}
pub fn into_value(self) -> V {
self.value
}
#[doc(hidden)]
pub fn with_custom_default(value: V, default: V) -> Self {
Self {
value,
default: DefaultValueConstructor::Custom(default),
}
}
}
impl<V> Value<V>
where
V: Clone + Default,
{
pub fn set_to_default(&mut self) {
match self.default {
DefaultValueConstructor::Default => self.value = V::default(),
DefaultValueConstructor::Custom(ref v) => self.value = v.clone(),
}
}
}
impl<V> From<V> for Value<V> {
fn from(value: V) -> Self {
Self {
value,
default: DefaultValueConstructor::Default,
}
}
}
impl From<&str> for Value<String> {
fn from(s: &str) -> Self {
Self {
value: s.to_string(),
default: DefaultValueConstructor::Default,
}
}
}
#[derive(Debug, Default, PartialEq, Eq, Clone, Hash, Serialize, Deserialize)]
enum DefaultValueConstructor<V> {
#[default]
Default,
Custom(V),
}
#[derive(Debug, PartialEq, Eq, Clone, Hash, Serialize, Deserialize, Default)]
pub enum ValueUpdate<V> {
#[default]
NoChange,
SetToDefault,
Set(V),
}
#[derive(Debug, PartialEq, Eq, Clone, Hash, Serialize, Deserialize)]
#[must_use]
pub struct ValueDiff<V> {
pub value: V,
}
impl<V> Node for Value<V>
where
V: Clone + Default + PartialEq,
{
type Update = ValueUpdate<V>;
type Diff = ValueDiff<V>;
const IS_CONTAINER: bool = false;
fn apply_update(&mut self, update: Self::Update) {
match update {
ValueUpdate::Set(v) => self.value = v,
ValueUpdate::SetToDefault => self.set_to_default(),
ValueUpdate::NoChange => {}
}
}
fn as_update(&self) -> Self::Update {
ValueUpdate::Set(self.value().clone())
}
fn compute_diff(&self, other: &Self) -> Option<Self::Diff> {
if self.value != other.value {
Some(ValueDiff {
value: other.value.to_owned(),
})
} else {
None
}
}
fn apply_diff(&mut self, diff: Self::Diff) {
self.value = diff.value;
}
fn as_diff(&self) -> Self::Diff {
ValueDiff {
value: self.value().to_owned(),
}
}
fn merge(&self, merge: &mut Self) {
merge.value = self.value.clone();
}
fn is_empty(&self) -> bool {
false
}
}
#[derive(Debug, PartialEq, Eq, Clone, Hash)]
pub struct OptRecord<R> {
record: Option<R>,
}
impl<R: Serialize> Serialize for OptRecord<R> {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
self.record.serialize(serializer)
}
}
impl<'de, R: Deserialize<'de>> Deserialize<'de> for OptRecord<R> {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
Ok(Self {
record: Option::<R>::deserialize(deserializer)?,
})
}
}
impl<R> OptRecord<R> {
pub fn record(&self) -> Option<&R> {
self.record.as_ref()
}
pub fn record_mut(&mut self) -> Option<&mut R> {
self.record.as_mut()
}
pub fn into_record(self) -> Option<R> {
self.record
}
pub fn is_empty(&self) -> bool {
self.record.is_none()
}
}
impl<R> OptRecord<R>
where
R: Node,
{
pub fn cleanup_empty_containers(&mut self) {
if !R::IS_CONTAINER {
return;
}
if self.record.as_ref().map(|r| r.is_empty()).unwrap_or(false) {
self.record = None;
}
}
}
#[derive(Debug, Default, PartialEq, Eq, Clone, Hash, Serialize, Deserialize)]
pub enum OptRecordUpdate<R>
where
R: Node,
{
#[default]
NoChange,
Clear,
Set(R),
Update {
update: R::Update,
insert: bool,
},
}
#[derive(Debug, PartialEq, Eq, Clone, Hash, Serialize, Deserialize)]
#[must_use]
pub enum OptRecordDiff<R>
where
R: Node,
{
Clear,
Update(R::Diff),
}
impl<R> Default for OptRecord<R> {
fn default() -> Self {
Self { record: None }
}
}
impl<R> Node for OptRecord<R>
where
R: Node,
{
type Update = OptRecordUpdate<R>;
type Diff = OptRecordDiff<R>;
const IS_CONTAINER: bool = true;
fn apply_update(&mut self, update: Self::Update) {
match update {
OptRecordUpdate::Set(r) => self.record = Some(r),
OptRecordUpdate::Update { insert, update } => match self.record.as_mut() {
Some(r) => r.apply_update(update),
None => {
if insert {
let mut r = R::default();
r.apply_update(update);
self.record = Some(r);
}
}
},
OptRecordUpdate::Clear => self.record = None,
OptRecordUpdate::NoChange => {}
}
}
fn as_update(&self) -> Self::Update {
match self.record.as_ref() {
Some(r) => OptRecordUpdate::Set(r.to_owned()),
None => OptRecordUpdate::Clear,
}
}
fn compute_diff(&self, other: &Self) -> Option<Self::Diff> {
match (self.record.as_ref(), other.record.as_ref()) {
(Some(r1), Some(r2)) => {
let diff = r1.compute_diff(r2)?;
Some(OptRecordDiff::Update(diff))
}
(Some(_), None) => Some(OptRecordDiff::Clear),
(None, Some(r)) => Some(OptRecordDiff::Update(r.as_diff())),
_ => None,
}
}
fn apply_diff(&mut self, diff: Self::Diff) {
match diff {
OptRecordDiff::Clear => self.record = None,
OptRecordDiff::Update(d) => self.record.get_or_insert_default().apply_diff(d),
}
}
fn as_diff(&self) -> Self::Diff {
match self.record.as_ref() {
Some(r) => OptRecordDiff::Update(r.as_diff()),
None => OptRecordDiff::Clear,
}
}
fn merge(&self, merge: &mut Self) {
match (self.record.as_ref(), merge.record.as_mut()) {
(Some(record), Some(merge_record)) => record.merge(merge_record),
(Some(record), None) => merge.record = Some(record.clone()),
_ => {}
}
}
fn is_empty(&self) -> bool {
self.record.is_none()
}
}
#[derive(Debug, PartialEq, Eq, Clone, Hash)]
pub struct OptValue<V> {
value: Option<V>,
}
impl<V: Serialize> Serialize for OptValue<V> {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
self.value.serialize(serializer)
}
}
impl<'de, V: Deserialize<'de>> Deserialize<'de> for OptValue<V> {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
Ok(Self {
value: Option::<V>::deserialize(deserializer)?,
})
}
}
impl<V> From<Option<V>> for OptValue<V> {
fn from(value: Option<V>) -> Self {
Self { value }
}
}
#[derive(Debug, Default, PartialEq, Eq, Clone, Hash, Serialize, Deserialize)]
pub enum OptValueUpdate<V> {
#[default]
NoChange,
Clear,
Set(V),
}
#[derive(Debug, PartialEq, Eq, Clone, Hash, Serialize, Deserialize)]
#[must_use]
pub enum OptValueDiff<V> {
Clear,
Set(V),
}
impl<V> Default for OptValue<V> {
fn default() -> Self {
Self { value: None }
}
}
impl<V> OptValue<V> {
pub fn value(&self) -> Option<&V> {
self.value.as_ref()
}
pub fn into_value(self) -> Option<V> {
self.value
}
pub fn is_empty(&self) -> bool {
self.value.is_none()
}
pub fn set(&mut self, v: V) {
self.value = Some(v);
}
}
impl<V> Node for OptValue<V>
where
V: Clone + PartialEq,
{
type Update = OptValueUpdate<V>;
type Diff = OptValueDiff<V>;
const IS_CONTAINER: bool = true;
fn apply_update(&mut self, update: Self::Update) {
match update {
OptValueUpdate::Set(v) => self.value = Some(v),
OptValueUpdate::Clear => self.value = None,
OptValueUpdate::NoChange => {}
}
}
fn as_update(&self) -> Self::Update {
match self.value.as_ref() {
Some(v) => OptValueUpdate::Set(v.to_owned()),
None => OptValueUpdate::Clear,
}
}
fn compute_diff(&self, other: &Self) -> Option<Self::Diff> {
match (self.value.as_ref(), other.value.as_ref()) {
(Some(v1), Some(v2)) => {
if v1 != v2 {
Some(OptValueDiff::Set(v2.to_owned()))
} else {
None
}
}
(Some(_), None) => Some(OptValueDiff::Clear),
(None, Some(v)) => Some(OptValueDiff::Set(v.to_owned())),
_ => None,
}
}
fn apply_diff(&mut self, diff: Self::Diff) {
match diff {
OptValueDiff::Clear => self.value = None,
OptValueDiff::Set(v) => self.value = Some(v),
}
}
fn as_diff(&self) -> Self::Diff {
match self.value.as_ref() {
Some(v) => OptValueDiff::Set(v.to_owned()),
None => OptValueDiff::Clear,
}
}
fn merge(&self, merge: &mut Self) {
if let Some(value) = self.value.clone() {
merge.value = Some(value);
}
}
fn is_empty(&self) -> bool {
self.value.is_none()
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ValueList<V>(Vec<V>)
where
V: Clone;
impl<V> Default for ValueList<V>
where
V: Clone,
{
fn default() -> Self {
ValueList(vec![])
}
}
impl<V> ValueList<V>
where
V: Clone,
{
pub fn inner(&self) -> &Vec<V> {
&self.0
}
pub fn inner_mut(&mut self) -> &mut Vec<V> {
&mut self.0
}
pub fn into_inner(self) -> Vec<V> {
self.0
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
}
impl<V: Clone> From<Vec<V>> for ValueList<V> {
fn from(vec: Vec<V>) -> Self {
Self(vec)
}
}
impl<V: Clone> FromIterator<V> for ValueList<V> {
fn from_iter<I: IntoIterator<Item = V>>(iter: I) -> Self {
Self(iter.into_iter().collect())
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum ValueListUpdate<V> {
Append(V),
Prepend(V),
PopLast,
PopFirst,
Replace(Vec<V>),
Remove(V),
Empty,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ValueListUpdates<V>(Vec<ValueListUpdate<V>>);
impl<V> Default for ValueListUpdates<V> {
fn default() -> Self {
Self(vec![])
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[must_use]
pub struct ValueListDiff<V> {
pub new_list: Vec<V>,
}
impl<V> ValueListUpdates<V> {
pub fn new() -> Self {
Self::default()
}
pub fn append(&mut self, v: V) -> &mut Self {
self.0.push(ValueListUpdate::Append(v));
self
}
pub fn prepend(&mut self, v: V) -> &mut Self {
self.0.push(ValueListUpdate::Prepend(v));
self
}
pub fn pop_last(&mut self) -> &mut Self {
self.0.push(ValueListUpdate::PopLast);
self
}
pub fn pop_first(&mut self) -> &mut Self {
self.0.push(ValueListUpdate::PopFirst);
self
}
pub fn replace(&mut self, list: Vec<V>) -> &mut Self {
self.0.push(ValueListUpdate::Replace(list));
self
}
pub fn remove(&mut self, v: V) -> &mut Self {
self.0.push(ValueListUpdate::Remove(v));
self
}
pub fn clear(&mut self) -> &mut Self {
self.0.push(ValueListUpdate::Empty);
self
}
}
impl<V> Node for ValueList<V>
where
V: Clone + PartialEq,
{
type Update = ValueListUpdates<V>;
type Diff = ValueListDiff<V>;
const IS_CONTAINER: bool = true;
fn apply_update(&mut self, updates: Self::Update) {
for update in updates.0 {
match update {
ValueListUpdate::Append(v) => {
self.0.push(v);
}
ValueListUpdate::Prepend(v) => {
self.0.insert(0, v);
}
ValueListUpdate::PopLast => {
self.0.pop();
}
ValueListUpdate::PopFirst => {
if !self.0.is_empty() {
self.0.remove(0);
}
}
ValueListUpdate::Replace(values) => {
self.0 = values;
}
ValueListUpdate::Remove(v) => {
self.0.retain(|value| value != &v);
}
ValueListUpdate::Empty => self.0.clear(),
}
}
}
fn as_update(&self) -> Self::Update {
ValueListUpdates(
self.0
.clone()
.into_iter()
.map(ValueListUpdate::Append)
.collect(),
)
}
fn compute_diff(&self, other: &Self) -> Option<Self::Diff> {
if self.0 == other.0 {
return None;
}
Some(ValueListDiff {
new_list: other.0.clone(),
})
}
fn apply_diff(&mut self, diff: Self::Diff) {
self.0 = diff.new_list;
}
fn as_diff(&self) -> Self::Diff {
ValueListDiff {
new_list: self.0.clone(),
}
}
fn merge(&self, merge: &mut Self) {
merge.0.extend(self.0.iter().cloned());
}
fn is_empty(&self) -> bool {
self.0.is_empty()
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ValueMap<K, V>(HashMap<K, V>)
where
K: PartialEq + Eq + Hash + Clone,
V: Clone;
impl<K, V> Default for ValueMap<K, V>
where
K: PartialEq + Eq + Hash + Clone,
V: Clone,
{
fn default() -> Self {
ValueMap(HashMap::new())
}
}
impl<K, V> ValueMap<K, V>
where
K: PartialEq + Eq + Hash + Clone,
V: Clone,
{
pub fn inner(&self) -> &HashMap<K, V> {
&self.0
}
pub fn inner_mut(&mut self) -> &mut HashMap<K, V> {
&mut self.0
}
pub fn into_inner(self) -> HashMap<K, V> {
self.0
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
}
impl<K, V> From<HashMap<K, V>> for ValueMap<K, V>
where
K: PartialEq + Eq + Hash + Clone,
V: Clone,
{
fn from(map: HashMap<K, V>) -> Self {
Self(map)
}
}
impl<K, V> FromIterator<(K, V)> for ValueMap<K, V>
where
K: PartialEq + Eq + Hash + Clone,
V: Clone,
{
fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
Self(iter.into_iter().collect())
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum ValueMapUpdate<K, V> {
Clear,
Set(K, V),
Del(K),
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ValueMapUpdates<K, V>(Vec<ValueMapUpdate<K, V>>);
impl<K, V> Default for ValueMapUpdates<K, V> {
fn default() -> Self {
Self(vec![])
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(bound(
serialize = "K: Serialize, V: Serialize",
deserialize = "K: Deserialize<'de> + Eq + Hash, V: Deserialize<'de>"
))]
#[must_use]
pub struct ValueMapDiff<K, V> {
pub clear: bool,
pub del: HashSet<K>,
pub set: HashMap<K, V>,
}
impl<K, V> PartialEq for ValueMapDiff<K, V>
where
K: PartialEq + Eq + Hash,
V: PartialEq,
{
fn eq(&self, other: &Self) -> bool {
self.clear == other.clear && self.set == other.set && self.del == other.del
}
}
impl<K, V> ValueMapUpdates<K, V> {
pub fn new() -> Self {
Self::default()
}
pub fn clear(&mut self) -> &mut Self {
self.0.push(ValueMapUpdate::Clear);
self
}
pub fn set(&mut self, k: K, v: V) -> &mut Self {
self.0.push(ValueMapUpdate::Set(k, v));
self
}
pub fn del(&mut self, k: K) -> &mut Self {
self.0.push(ValueMapUpdate::Del(k));
self
}
pub fn iter(&self) -> <&Self as IntoIterator>::IntoIter {
self.into_iter()
}
}
#[derive(Debug)]
pub struct ValueMapUpdatesIntoIter<K, V>(std::vec::IntoIter<ValueMapUpdate<K, V>>);
impl<K, V> Iterator for ValueMapUpdatesIntoIter<K, V> {
type Item = ValueMapUpdate<K, V>;
fn next(&mut self) -> Option<Self::Item> {
self.0.next()
}
}
impl<K, V> IntoIterator for ValueMapUpdates<K, V> {
type Item = ValueMapUpdate<K, V>;
type IntoIter = ValueMapUpdatesIntoIter<K, V>;
fn into_iter(self) -> Self::IntoIter {
ValueMapUpdatesIntoIter(self.0.into_iter())
}
}
#[derive(Debug)]
pub struct ValueMapUpdatesIter<'a, K, V>(std::slice::Iter<'a, ValueMapUpdate<K, V>>);
impl<'a, K, V> Iterator for ValueMapUpdatesIter<'a, K, V> {
type Item = &'a ValueMapUpdate<K, V>;
fn next(&mut self) -> Option<Self::Item> {
self.0.next()
}
}
impl<'a, K, V> IntoIterator for &'a ValueMapUpdates<K, V> {
type Item = &'a ValueMapUpdate<K, V>;
type IntoIter = ValueMapUpdatesIter<'a, K, V>;
fn into_iter(self) -> Self::IntoIter {
ValueMapUpdatesIter(self.0.iter())
}
}
impl<K, V> Node for ValueMap<K, V>
where
K: PartialEq + Eq + Hash + Clone,
V: Clone + PartialEq,
{
type Update = ValueMapUpdates<K, V>;
type Diff = ValueMapDiff<K, V>;
const IS_CONTAINER: bool = true;
fn apply_update(&mut self, updates: Self::Update) {
for update in updates.0 {
match update {
ValueMapUpdate::Del(k) => {
let _ = self.0.remove(&k);
}
ValueMapUpdate::Set(k, v) => {
let _ = self.0.insert(k, v);
}
ValueMapUpdate::Clear => self.0.clear(),
}
}
}
fn as_update(&self) -> Self::Update {
ValueMapUpdates(
self.0
.clone()
.into_iter()
.map(|(k, v)| ValueMapUpdate::Set(k, v))
.collect(),
)
}
fn compute_diff(&self, other: &Self) -> Option<Self::Diff> {
let mut del = HashSet::new();
let mut set = HashMap::new();
for (k, v1) in &self.0 {
match other.0.get(k) {
Some(v2) => {
if v1 != v2 {
set.insert(k.clone(), v2.clone());
}
}
None => {
del.insert(k.clone());
}
}
}
for (k, v) in &other.0 {
if !self.0.contains_key(k) {
set.insert(k.clone(), v.clone());
}
}
if set.is_empty() && del.is_empty() {
None
} else {
Some(ValueMapDiff {
clear: false,
set,
del,
})
}
}
fn apply_diff(&mut self, diff: Self::Diff) {
let ValueMapDiff { set, del, clear } = diff;
if clear {
self.0.clear();
} else {
for key in del {
let _ = self.0.remove(&key);
}
}
for (key, value) in set {
self.0.insert(key, value);
}
}
fn as_diff(&self) -> Self::Diff {
ValueMapDiff {
clear: true,
del: HashSet::new(),
set: self.0.clone(),
}
}
fn merge(&self, merge: &mut Self) {
for (k, v) in &self.0 {
merge.0.insert(k.clone(), v.clone());
}
}
fn is_empty(&self) -> bool {
self.0.is_empty()
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ValueSet<K>(HashSet<K>)
where
K: PartialEq + Eq + Hash + Clone;
impl<K> ValueSet<K>
where
K: PartialEq + Eq + Hash + Clone,
{
pub fn inner(&self) -> &HashSet<K> {
&self.0
}
pub fn inner_mut(&mut self) -> &mut HashSet<K> {
&mut self.0
}
pub fn into_inner(self) -> HashSet<K> {
self.0
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
}
impl<K> From<HashSet<K>> for ValueSet<K>
where
K: PartialEq + Eq + Hash + Clone,
{
fn from(set: HashSet<K>) -> Self {
Self(set)
}
}
impl<K> FromIterator<K> for ValueSet<K>
where
K: PartialEq + Eq + Hash + Clone,
{
fn from_iter<I: IntoIterator<Item = K>>(iter: I) -> Self {
Self(iter.into_iter().collect())
}
}
impl<K> Default for ValueSet<K>
where
K: PartialEq + Eq + Hash + Clone,
{
fn default() -> Self {
ValueSet(HashSet::new())
}
}
impl<K> Node for ValueSet<K>
where
K: PartialEq + Eq + Hash + Clone,
{
type Update = ValueSetUpdates<K>;
type Diff = ValueSetDiff<K>;
const IS_CONTAINER: bool = true;
fn apply_update(&mut self, updates: Self::Update) {
for update in updates.0 {
match update {
ValueSetUpdate::Del(k) => {
let _ = self.0.remove(&k);
}
ValueSetUpdate::Add(k) => {
let _ = self.0.insert(k);
}
ValueSetUpdate::Clear => self.0.clear(),
}
}
}
fn as_update(&self) -> Self::Update {
ValueSetUpdates(
self.0
.clone()
.into_iter()
.map(ValueSetUpdate::Add)
.collect(),
)
}
fn compute_diff(&self, other: &Self) -> Option<Self::Diff> {
if self.0 == other.0 {
return None;
}
let mut add = HashSet::new();
let mut del = HashSet::new();
for k in self.0.difference(&other.0) {
del.insert(k.to_owned());
}
for k in other.0.difference(&self.0) {
add.insert(k.to_owned());
}
if del.is_empty() && add.is_empty() {
None
} else {
Some(ValueSetDiff {
clear: false,
add,
del,
})
}
}
fn apply_diff(&mut self, diff: Self::Diff) {
let ValueSetDiff { clear, add, del } = diff;
if clear {
self.0.clear();
} else {
for key in del {
let _ = self.0.remove(&key);
}
}
for key in add {
self.0.insert(key);
}
}
fn as_diff(&self) -> Self::Diff {
ValueSetDiff {
clear: true,
del: HashSet::new(),
add: self.0.clone(),
}
}
fn merge(&self, merge: &mut Self) {
merge.0.extend(self.0.iter().cloned());
}
fn is_empty(&self) -> bool {
self.0.is_empty()
}
}
#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
pub enum ValueSetUpdate<K> {
Clear,
Add(K),
Del(K),
}
#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
pub struct ValueSetUpdates<K>(Vec<ValueSetUpdate<K>>);
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(bound(
serialize = "K: Serialize",
deserialize = "K: Deserialize<'de> + Eq + Hash"
))]
#[must_use]
pub struct ValueSetDiff<K> {
pub clear: bool,
pub add: HashSet<K>,
pub del: HashSet<K>,
}
impl<K> PartialEq for ValueSetDiff<K>
where
K: PartialEq + Eq + Hash,
{
fn eq(&self, other: &Self) -> bool {
self.clear == other.clear && self.add == other.add && self.del == other.del
}
}
impl<K> Default for ValueSetUpdates<K> {
fn default() -> Self {
Self(vec![])
}
}
impl<K> ValueSetUpdates<K> {
pub fn new() -> Self {
Self::default()
}
pub fn clear(&mut self) -> &mut Self {
self.0.clear();
self.0.push(ValueSetUpdate::Clear);
self
}
#[allow(clippy::should_implement_trait)]
pub fn add(&mut self, k: K) -> &mut Self {
self.0.push(ValueSetUpdate::Add(k));
self
}
pub fn del(&mut self, k: K) -> &mut Self {
self.0.push(ValueSetUpdate::Del(k));
self
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn iter(&self) -> <&Self as IntoIterator>::IntoIter {
self.into_iter()
}
}
impl<K> std::iter::Extend<K> for ValueSetUpdates<K> {
fn extend<I>(&mut self, iter: I)
where
I: IntoIterator<Item = K>,
{
self.0.extend(iter.into_iter().map(ValueSetUpdate::Add))
}
}
#[derive(Debug)]
pub struct ValueSetUpdatesIntoIter<K>(std::vec::IntoIter<ValueSetUpdate<K>>);
impl<K> Iterator for ValueSetUpdatesIntoIter<K> {
type Item = ValueSetUpdate<K>;
fn next(&mut self) -> Option<Self::Item> {
self.0.next()
}
}
impl<K> IntoIterator for ValueSetUpdates<K> {
type Item = ValueSetUpdate<K>;
type IntoIter = ValueSetUpdatesIntoIter<K>;
fn into_iter(self) -> Self::IntoIter {
ValueSetUpdatesIntoIter(self.0.into_iter())
}
}
#[derive(Debug)]
pub struct ValueSetUpdatesIter<'a, K>(std::slice::Iter<'a, ValueSetUpdate<K>>);
impl<'a, K> Iterator for ValueSetUpdatesIter<'a, K> {
type Item = &'a ValueSetUpdate<K>;
fn next(&mut self) -> Option<Self::Item> {
self.0.next()
}
}
impl<'a, K> IntoIterator for &'a ValueSetUpdates<K> {
type Item = &'a ValueSetUpdate<K>;
type IntoIter = ValueSetUpdatesIter<'a, K>;
fn into_iter(self) -> Self::IntoIter {
ValueSetUpdatesIter(self.0.iter())
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct RecordMap<K, R>
where
K: PartialEq + Eq + Hash + Clone,
R: Node,
{
map: HashMap<K, R>,
}
impl<K, R> Serialize for RecordMap<K, R>
where
K: PartialEq + Eq + Hash + Clone + Serialize,
R: Node + Serialize,
{
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
self.map.serialize(serializer)
}
}
impl<'de, K, R> Deserialize<'de> for RecordMap<K, R>
where
K: PartialEq + Eq + Hash + Clone + Deserialize<'de>,
R: Node + Deserialize<'de>,
{
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
Ok(Self {
map: HashMap::<K, R>::deserialize(deserializer)?,
})
}
}
impl<K, R> Default for RecordMap<K, R>
where
K: PartialEq + Eq + Hash + Clone,
R: Node,
{
fn default() -> Self {
Self {
map: HashMap::new(),
}
}
}
impl<K, R> RecordMap<K, R>
where
K: PartialEq + Eq + Hash + Clone,
R: Node,
{
pub fn inner(&self) -> &HashMap<K, R> {
&self.map
}
pub fn inner_mut(&mut self) -> &mut HashMap<K, R> {
&mut self.map
}
pub fn into_inner(self) -> HashMap<K, R> {
self.map
}
pub fn is_empty(&self) -> bool {
self.map.is_empty()
}
pub fn drain(&mut self) -> impl Iterator<Item = (K, R)> {
self.map.drain()
}
pub fn cleanup_empty_containers(&mut self) {
if !R::IS_CONTAINER {
return;
}
self.map.retain(|_, r| !r.is_empty());
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum RecordMapUpdate<K, U> {
Clear,
Update { insert: bool, key: K, update: U },
Del(K),
}
pub struct RecordMapUpdates<K, R>
where
R: Node,
{
updates: Vec<RecordMapUpdate<K, <R as Node>::Update>>,
_phantom: PhantomData<R>,
}
#[derive(Serialize, Deserialize)]
#[serde(bound(
serialize = "K: Serialize, <R as Node>::Diff: Serialize",
deserialize = "K: Deserialize<'de> + Eq + std::hash::Hash, <R as Node>::Diff: Deserialize<'de>"
))]
#[must_use]
pub struct RecordMapDiff<K, R>
where
R: Node,
{
pub clear: bool,
pub update: HashMap<K, <R as Node>::Diff>,
pub del: HashSet<K>,
}
impl<K, R> PartialEq for RecordMapDiff<K, R>
where
K: PartialEq + Eq + Hash,
R: Node,
R::Diff: PartialEq,
{
fn eq(&self, other: &Self) -> bool {
self.clear == other.clear && self.update == other.update && self.del == other.del
}
}
impl<K, R> Clone for RecordMapDiff<K, R>
where
K: Clone,
R: Node,
R::Diff: Clone,
{
fn clone(&self) -> Self {
Self {
clear: self.clear,
update: self.update.clone(),
del: self.del.clone(),
}
}
}
impl<K, R> fmt::Debug for RecordMapDiff<K, R>
where
R: Node + fmt::Debug,
<R as Node>::Diff: fmt::Debug,
K: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("RecordMapDiff")
.field("clear", &self.clear)
.field("del", &self.del)
.field("update", &self.update)
.finish()
}
}
impl<K, C> IntoIterator for RecordMapUpdates<K, C>
where
C: Node,
{
type Item = RecordMapUpdate<K, <C as Node>::Update>;
type IntoIter = RecordMapUpdatesIntoIter<K, <C as Node>::Update>;
fn into_iter(self) -> Self::IntoIter {
RecordMapUpdatesIntoIter(self.updates.into_iter())
}
}
#[derive(Debug)]
pub struct RecordMapUpdatesIntoIter<K, U>(std::vec::IntoIter<RecordMapUpdate<K, U>>);
impl<K, U> Iterator for RecordMapUpdatesIntoIter<K, U> {
type Item = RecordMapUpdate<K, U>;
fn next(&mut self) -> Option<Self::Item> {
self.0.next()
}
}
impl<'a, K, C> IntoIterator for &'a RecordMapUpdates<K, C>
where
C: Node,
{
type Item = &'a RecordMapUpdate<K, <C as Node>::Update>;
type IntoIter = RecordMapUpdatesIter<'a, K, <C as Node>::Update>;
fn into_iter(self) -> Self::IntoIter {
RecordMapUpdatesIter(self.updates.iter())
}
}
#[derive(Debug)]
pub struct RecordMapUpdatesIter<'a, K, U>(std::slice::Iter<'a, RecordMapUpdate<K, U>>);
impl<'a, K, U> Iterator for RecordMapUpdatesIter<'a, K, U> {
type Item = &'a RecordMapUpdate<K, U>;
fn next(&mut self) -> Option<Self::Item> {
self.0.next()
}
}
impl<K, C> Clone for RecordMapUpdates<K, C>
where
K: Clone,
C: Node,
<C as Node>::Update: Clone,
{
fn clone(&self) -> Self {
Self {
updates: self.updates.clone(),
_phantom: PhantomData,
}
}
}
impl<K, C> fmt::Debug for RecordMapUpdates<K, C>
where
K: fmt::Debug,
C: Node,
<C as Node>::Update: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("RecordMapUpdates")
.field("updates", &self.updates)
.finish()
}
}
impl<K, R> PartialEq for RecordMapUpdates<K, R>
where
R: Node,
K: PartialEq,
<R as Node>::Update: PartialEq,
{
fn eq(&self, other: &Self) -> bool {
self.updates == other.updates
}
}
impl<K, R> Serialize for RecordMapUpdates<K, R>
where
R: Node,
K: Serialize,
<R as Node>::Update: Serialize,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut state = serializer.serialize_struct("RecordMapUpdates", 1)?;
state.serialize_field("updates", &self.updates)?;
state.end()
}
}
impl<'de, K, R> Deserialize<'de> for RecordMapUpdates<K, R>
where
R: Node,
K: Deserialize<'de>,
<R as Node>::Update: Deserialize<'de>,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let updates = Vec::<RecordMapUpdate<K, <R as Node>::Update>>::deserialize(deserializer)?;
Ok(Self {
updates,
_phantom: PhantomData,
})
}
}
impl<K, R> Node for RecordMap<K, R>
where
K: PartialEq + Eq + Hash + Clone,
R: Node + PartialEq,
{
type Update = RecordMapUpdates<K, R>;
type Diff = RecordMapDiff<K, R>;
const IS_CONTAINER: bool = true;
fn apply_update(&mut self, updates: Self::Update) {
for update in updates.updates {
match update {
RecordMapUpdate::Del(k) => {
let _ = self.map.remove(&k);
}
RecordMapUpdate::Update {
insert,
key,
update,
} => match self.map.get_mut(&key) {
Some(r) => r.apply_update(update),
None => {
if insert {
let mut r = R::default();
r.apply_update(update);
self.map.insert(key, r);
}
}
},
RecordMapUpdate::Clear => self.map.clear(),
}
}
}
fn as_update(&self) -> Self::Update {
RecordMapUpdates {
updates: self
.map
.clone()
.into_iter()
.map(|(k, v)| RecordMapUpdate::Update {
insert: true,
key: k,
update: v.as_update(),
})
.collect(),
_phantom: PhantomData,
}
}
fn compute_diff(&self, other: &Self) -> Option<Self::Diff> {
if !self.map.is_empty() && other.map.is_empty() {
return Some(RecordMapDiff {
clear: true,
update: HashMap::new(),
del: HashSet::new(),
});
}
let mut update = HashMap::new();
let mut del = HashSet::new();
for (k, r1) in &self.map {
match other.map.get(k) {
Some(r2) => {
if let Some(diff) = r1.compute_diff(r2) {
update.insert(k.to_owned(), diff);
}
}
None => {
del.insert(k.to_owned());
}
}
}
for (k, r2) in &other.map {
if !self.map.contains_key(k) {
update.insert(k.to_owned(), r2.as_diff());
}
}
if update.is_empty() && del.is_empty() {
None
} else {
Some(RecordMapDiff {
clear: false,
update,
del,
})
}
}
fn apply_diff(&mut self, diff: Self::Diff) {
let RecordMapDiff { clear, update, del } = diff;
if clear {
self.map.clear()
}
for (key, diff) in update {
self.map.entry(key).or_default().apply_diff(diff);
}
for key in del {
self.map.remove(&key);
}
}
fn as_diff(&self) -> Self::Diff {
RecordMapDiff {
clear: true,
del: HashSet::new(),
update: self
.map
.iter()
.map(|(k, r)| (k.clone(), r.as_diff()))
.collect(),
}
}
fn merge(&self, merge: &mut Self) {
for (k, val) in &self.map {
match merge.map.entry(k.clone()) {
Entry::Vacant(v) => {
let _ = v.insert(val.clone());
}
Entry::Occupied(mut o) => val.merge(o.get_mut()),
}
}
}
fn is_empty(&self) -> bool {
self.map.is_empty()
}
}
impl<K, C> Default for RecordMapUpdates<K, C>
where
C: Node,
{
fn default() -> Self {
Self {
updates: vec![],
_phantom: PhantomData,
}
}
}
impl<K, R> RecordMapUpdates<K, R>
where
R: Node,
{
pub fn new() -> Self {
Self::default()
}
pub fn clear(&mut self) -> &mut Self {
self.updates.push(RecordMapUpdate::Clear);
self
}
pub fn update(&mut self, key: K, update: <R as Node>::Update, insert: bool) -> &mut Self {
self.updates.push(RecordMapUpdate::Update {
insert,
key,
update,
});
self
}
pub fn del(&mut self, k: K) -> &mut Self {
self.updates.push(RecordMapUpdate::Del(k));
self
}
pub fn replace(&mut self, k: K, r: R) -> &mut Self
where
K: Clone,
{
self.del(k.clone()).update(k, r.as_update(), true)
}
pub fn is_empty(&self) -> bool {
self.updates.is_empty()
}
pub fn iter(&self) -> <&Self as IntoIterator>::IntoIter {
self.into_iter()
}
}