// codesnip-guard: SqrtTree #[cfg_attr(any(),rustfmt::skip)]pub use self::sqrt_tree::{SqrtFoldMap,SqrtFoldVec,SqrtIntoIter,SqrtIter,SqrtLazyMap,SqrtLazyVec,SqrtMap,SqrtMultiset,SqrtSet,SqrtVec};#[cfg_attr(any(),rustfmt::skip)]mod sqrt_tree{use super::{LazyMapAct,LazyMapAgg,LazyMapMonoidWithKeyAct,Monoid,RangeBoundsExt};use std::{mem,ops::{Bound,RangeBounds}};pub use self::fold::{SqrtFoldMap,SqrtFoldVec};pub use self::lazy::{SqrtLazyMap,SqrtLazyVec};pub use self::plain::{SqrtIntoIter,SqrtIter,SqrtMap,SqrtMultiset,SqrtSet,SqrtVec};mod fold{use super::{Bucket,BucketState,BucketValue,Buckets,MapValue,Monoid,RangeBoundsExt,SequenceValue,sort_dedup_map};use std::{borrow::Borrow,marker::PhantomData,mem,ops::{Range,RangeBounds}};struct FoldStatewhere M:Monoid{agg:M::T,_marker:PhantomDataP>}implBucketStatefor FoldStatewhere M:Monoid,P:BucketValue{fn new(values:&[T])->Self{let agg=values.iter().fold(M::unit(),|agg,value|M::operate(&agg,P::get(value)));Self{agg,_marker:PhantomData}}fn push(&mut self,_:&mut[T]){}}implBuckets>where M:Monoid,P:BucketValue{fn fold(&self,range:Range)->M::T{assert!(range.start<=range.end);let mut result=M::unit();let mut offset=0;for Bucket{values,state}in&self.buckets{let end=offset+values.len();if range.end<=offset{break;}if range.start<=offset&&end<=range.end{result=M::operate(&result,&state.agg);}else if range.startwhere M:Monoid{inner:Buckets>}implSqrtFoldVecwhere M:Monoid{pub fn new()->Self{Self{inner:Buckets::new()}}pub fn len(&self)->usize{self.inner.len}pub fn is_empty(&self)->bool{self.len()==0}pub fn clear(&mut self){*self=Self::new();}pub fn get(&self,index:usize)->Option<&M::T>{if index>=self.len(){return None;}self.inner.at(self.inner.locate(index))}pub fn modify(&mut self,index:usize,f:impl FnOnce(&M::T)->M::T){assert!(indexM::T{assert!(indexOption{let i=self.inner.buckets.len().checked_sub(1)?;Some(self.inner.remove((i,self.inner.buckets[i].values.len()-1)))}pub fn iter(&self)->impl DoubleEndedIterator{self.inner.buckets.iter().flat_map(|b|b.values.iter())}pub fn fold(&self,range:R)->M::T where R:RangeBounds{let range=range.to_range_bounded(0,self.len()).expect("invalid range");self.inner.fold(range)}}implDefault for SqrtFoldVecwhere M:Monoid{fn default()->Self{Self::new()}}implFromIteratorfor SqrtFoldVecwhere M:Monoid{fn from_iter(iter:I)->Self where I:IntoIterator{let values:Vec<_>=iter.into_iter().collect();Self{inner:Buckets::build(values.len(),values.into_iter())}}}implExtendfor SqrtFoldVecwhere M:Monoid{fn extend(&mut self,iter:I)where I:IntoIterator{for value in iter{self.push(value);}}}#[doc=" An ordered map with value aggregation in key order and no lazy updates."]#[doc=" Key lookup takes O(log N); folds and amortized updates take O(sqrt(N)) for O(1) monoid operations."]pub struct SqrtFoldMapwhere M:Monoid{inner:Buckets<(K,M::T),FoldState>}implSqrtFoldMapwhere M:Monoid{pub fn new()->Self{Self{inner:Buckets::new()}}pub fn len(&self)->usize{self.inner.len}pub fn is_empty(&self)->bool{self.len()==0}pub fn clear(&mut self){*self=Self::new();}pub fn get(&self,key:&Q)->Option<&M::T>where K:Borrow,Q:Ord+?Sized{self.get_key_value(key).map(|(_,v)|v)}pub fn get_key_value(&self,key:&Q)->Option<(&K,&M::T)>where K:Borrow,Q:Ord+?Sized{let p=self.inner.partition_point(|(k,_)|k.borrow()(&self,key:&Q)->bool where K:Borrow,Q:Ord+?Sized{self.get(key).is_some()}pub fn get_key_value_at(&self,index:usize)->Option<(&K,&M::T)>{if index>=self.len(){return None;}self.inner.at(self.inner.locate(index)).map(|(k,v)|(k,v))}pub fn insert(&mut self,key:K,value:M::T)->Optionwhere K:Ord{let(i,j)=self.inner.partition_point(|(k,_)|k<&key);if self.inner.at((i,j)).is_some_and(|(k,_)|k==&key){let Bucket{values,state}=&mut self.inner.buckets[i];let old=mem::replace(&mut values[j].1,value);*state=FoldState::new(values);return Some(old);}self.inner.insert((i,j),(key,value));None}#[doc=" Returns whether the key was present."]pub fn modify(&mut self,key:&Q,f:impl FnOnce(&M::T)->M::T)->bool where K:Borrow,Q:Ord+?Sized{let(i,j)=self.inner.partition_point(|(k,_)|k.borrow()(&mut self,key:&Q)->Optionwhere K:Borrow,Q:Ord+?Sized{self.remove_entry(key).map(|(_,v)|v)}pub fn remove_entry(&mut self,key:&Q)->Option<(K,M::T)>where K:Borrow,Q:Ord+?Sized{let p=self.inner.partition_point(|(k,_)|k.borrow()Option<(K,M::T)>{(index(&self,key:&Q)->usize where K:Borrow,Q:Ord+?Sized{self.inner.position(self.inner.partition_point(|(k,_)|k.borrow()(&self,key:&Q)->usize where K:Borrow,Q:Ord+?Sized{self.inner.position(self.inner.partition_point(|(k,_)|k.borrow()<=key))}pub fn iter(&self)->impl DoubleEndedIterator{self.inner.buckets.iter().flat_map(|b|b.values.iter().map(|(k,v)|(k,v)))}pub fn fold(&self,range:R)->M::T where K:Borrow,Q:Ord+?Sized,R:RangeBounds{let(start,end)=self.inner.bounds(range,|(k,_)|k.borrow());self.inner.fold(self.inner.position(start)..self.inner.position(end))}}implDefault for SqrtFoldMapwhere M:Monoid{fn default()->Self{Self::new()}}implFromIterator<(K,M::T)>for SqrtFoldMapwhere K:Ord,M:Monoid{fn from_iter(iter:I)->Self where I:IntoIterator{let mut values:Vec<_>=iter.into_iter().collect();sort_dedup_map(&mut values);Self{inner:Buckets::build(values.len(),values.into_iter())}}}implExtend<(K,M::T)>for SqrtFoldMapwhere K:Ord,M:Monoid{fn extend(&mut self,iter:I)where I:IntoIterator{for(k,v)in iter{self.insert(k,v);}}}}mod lazy{use super::{Bucket,BucketState,BucketValue,Buckets,LazyMapAct,LazyMapAgg,LazyMapMonoidWithKeyAct,MapValue,RangeBoundsExt,SequenceValue,sort_dedup_map};use std::{borrow::Borrow,marker::PhantomData,mem,ops::{Range,RangeBounds}};struct LazyStatewhere L:LazyMapMonoidWithKeyAct{agg:LazyMapAgg,act:LazyMapAct,_marker:PhantomDataP>}implBucketStatefor LazyStatewhere L:LazyMapMonoidWithKeyAct,P:BucketValue{fn new(values:&[T])->Self{let agg=values.iter().fold(L::agg_unit(),|agg,value|{L::agg_operate(&agg,&L::single_agg(P::get(value)))});Self{agg,act:L::act_unit(),_marker:PhantomData}}fn push(&mut self,values:&mut[T]){if!L::is_act_unit(&self.act){for value in values{let value=P::get_mut(value);*value=L::act_key(value,&self.act);}self.act=L::act_unit();}}}implBuckets>where L:LazyMapMonoidWithKeyAct,P:BucketValue{fn fold(&mut self,range:Range)->LazyMapAgg{let mut result=L::agg_unit();assert!(range.start<=range.end);if range.is_empty(){return result;}let mut offset=0;for Bucket{values,state}in&mut self.buckets{let end=offset+values.len();if range.end<=offset{break;}if range.start<=offset&&end<=range.end{L::agg_operate_assign(&mut result,&state.agg);}else if range.start,act:LazyMapAct){assert!(range.start<=range.end);if range.is_empty()||L::is_act_unit(&act){return;}let mut offset=0;for Bucket{values,state}in&mut self.buckets{let end=offset+values.len();if range.end<=offset{break;}if range.start<=offset&&end<=range.end&&let Some(agg)=L::act_agg(&state.agg,&act){state.agg=agg;L::act_operate_assign(&mut state.act,&act);offset=end;continue;}if range.startwhere L:LazyMapMonoidWithKeyAct{inner:Buckets>}implSqrtLazyVecwhere L:LazyMapMonoidWithKeyAct{pub fn new()->Self{Self{inner:Buckets::new()}}pub fn len(&self)->usize{self.inner.len}pub fn is_empty(&self)->bool{self.len()==0}pub fn clear(&mut self){*self=Self::new();}pub fn get(&mut self,index:usize)->Option<&L::Key>{if index>=self.len(){return None;}let(i,j)=self.inner.locate(index);let Bucket{values,state}=&mut self.inner.buckets[i];state.push(values);Some(&values[j])}pub fn modify(&mut self,index:usize,f:impl FnOnce(&L::Key)->L::Key){assert!(indexL::Key{assert!(indexOption{let i=self.inner.buckets.len().checked_sub(1)?;Some(self.inner.remove((i,self.inner.buckets[i].values.len()-1)))}#[doc=" Materializes pending updates before borrowing the elements."]pub fn iter(&mut self)->impl DoubleEndedIterator{for bucket in&mut self.inner.buckets{bucket.state.push(&mut bucket.values);}self.inner.buckets.iter().flat_map(|b|b.values.iter())}pub fn fold(&mut self,range:R)->LazyMapAggwhere R:RangeBounds{let range=range.to_range_bounded(0,self.len()).expect("invalid range");self.inner.fold(range)}pub fn update(&mut self,range:R,act:LazyMapAct)where R:RangeBounds{let range=range.to_range_bounded(0,self.len()).expect("invalid range");self.inner.update(range,act);}}implDefault for SqrtLazyVecwhere L:LazyMapMonoidWithKeyAct{fn default()->Self{Self::new()}}implFromIteratorfor SqrtLazyVecwhere L:LazyMapMonoidWithKeyAct{fn from_iter(iter:I)->Self where I:IntoIterator{let values:Vec<_>=iter.into_iter().collect();Self{inner:Buckets::build(values.len(),values.into_iter())}}}implExtendfor SqrtLazyVecwhere L:LazyMapMonoidWithKeyAct{fn extend(&mut self,iter:I)where I:IntoIterator{for value in iter{self.push(value);}}}#[doc=" An ordered map aggregating and updating values in key order, without changing keys."]#[doc=" Value access can materialize a bucket and takes O(sqrt(N))."]#[doc=" Range operations have the same costs and `act_agg` fallback as `SqrtLazyVec`."]pub struct SqrtLazyMapwhere L:LazyMapMonoidWithKeyAct{inner:Buckets<(K,L::Key),LazyState>}implSqrtLazyMapwhere L:LazyMapMonoidWithKeyAct{pub fn new()->Self{Self{inner:Buckets::new()}}pub fn len(&self)->usize{self.inner.len}pub fn is_empty(&self)->bool{self.len()==0}pub fn clear(&mut self){*self=Self::new();}pub fn contains_key(&self,key:&Q)->bool where K:Borrow,Q:Ord+?Sized{let p=self.inner.partition_point(|(k,_)|k.borrow()(&mut self,key:&Q)->Option<&L::Key>where K:Borrow,Q:Ord+?Sized{self.get_key_value(key).map(|(_,v)|v)}pub fn get_key_value(&mut self,key:&Q)->Option<(&K,&L::Key)>where K:Borrow,Q:Ord+?Sized{let(i,j)=self.inner.partition_point(|(k,_)|k.borrow()Option<(&K,&L::Key)>{if index>=self.len(){return None;}let(i,j)=self.inner.locate(index);let Bucket{values,state}=&mut self.inner.buckets[i];state.push(values);let(k,v)=&values[j];Some((k,v))}pub fn insert(&mut self,key:K,value:L::Key)->Optionwhere K:Ord{let(i,j)=self.inner.partition_point(|(k,_)|k<&key);if self.inner.at((i,j)).is_some_and(|(k,_)|k==&key){let Bucket{values,state}=&mut self.inner.buckets[i];state.push(values);let old=mem::replace(&mut values[j].1,value);*state=LazyState::new(values);return Some(old);}self.inner.insert((i,j),(key,value));None}#[doc=" Returns whether the key was present."]pub fn modify(&mut self,key:&Q,f:impl FnOnce(&L::Key)->L::Key)->bool where K:Borrow,Q:Ord+?Sized{let(i,j)=self.inner.partition_point(|(k,_)|k.borrow()(&mut self,key:&Q)->Optionwhere K:Borrow,Q:Ord+?Sized{self.remove_entry(key).map(|(_,v)|v)}pub fn remove_entry(&mut self,key:&Q)->Option<(K,L::Key)>where K:Borrow,Q:Ord+?Sized{let p=self.inner.partition_point(|(k,_)|k.borrow()Option<(K,L::Key)>{(index(&self,key:&Q)->usize where K:Borrow,Q:Ord+?Sized{self.inner.position(self.inner.partition_point(|(k,_)|k.borrow()(&self,key:&Q)->usize where K:Borrow,Q:Ord+?Sized{self.inner.position(self.inner.partition_point(|(k,_)|k.borrow()<=key))}#[doc=" Materializes pending updates before borrowing the entries."]pub fn iter(&mut self)->impl DoubleEndedIterator{for bucket in&mut self.inner.buckets{bucket.state.push(&mut bucket.values);}self.inner.buckets.iter().flat_map(|b|b.values.iter().map(|(k,v)|(k,v)))}pub fn fold(&mut self,range:R)->LazyMapAggwhere K:Borrow,Q:Ord+?Sized,R:RangeBounds{let(start,end)=self.inner.bounds(range,|(k,_)|k.borrow());let range=self.inner.position(start)..self.inner.position(end);self.inner.fold(range)}pub fn update(&mut self,range:R,act:LazyMapAct)where K:Borrow,Q:Ord+?Sized,R:RangeBounds{let(start,end)=self.inner.bounds(range,|(k,_)|k.borrow());let range=self.inner.position(start)..self.inner.position(end);self.inner.update(range,act);}}implDefault for SqrtLazyMapwhere L:LazyMapMonoidWithKeyAct{fn default()->Self{Self::new()}}implFromIterator<(K,L::Key)>for SqrtLazyMapwhere K:Ord,L:LazyMapMonoidWithKeyAct{fn from_iter(iter:I)->Self where I:IntoIterator{let mut values:Vec<_>=iter.into_iter().collect();sort_dedup_map(&mut values);Self{inner:Buckets::build(values.len(),values.into_iter())}}}implExtend<(K,L::Key)>for SqrtLazyMapwhere K:Ord,L:LazyMapMonoidWithKeyAct{fn extend(&mut self,iter:I)where I:IntoIterator{for(k,v)in iter{self.insert(k,v);}}}}mod plain{use super::{Bucket,Buckets,sort_dedup_map};use std::{borrow::Borrow,fmt::{self,Debug},iter::FusedIterator,mem,ops::RangeBounds};implBuckets{fn range(&self,range:R,key:impl Fn(&T)->&Q)->SqrtIter<'_,T>where Q:Ord+?Sized,R:RangeBounds{let(front,back)=self.bounds(range,key);SqrtIter{buckets:&self.buckets,front,back}}}#[doc=" A sequence with amortized O(sqrt(N)) insertion/removal and O(sqrt(N)) indexing."]#[doc=" An individual insertion or removal can take O(N) when rebuilding."]#[derive(Clone)]pub struct SqrtVec{inner:Buckets}implSqrtVec{pub fn new()->Self{Self{inner:Buckets::new()}}pub fn len(&self)->usize{self.inner.len}pub fn is_empty(&self)->bool{self.len()==0}pub fn clear(&mut self){*self=Self::new();}pub fn get(&self,index:usize)->Option<&T>{if index>=self.len(){return None;}self.inner.at(self.inner.locate(index))}pub fn get_mut(&mut self,index:usize)->Option<&mut T>{if index>=self.len(){return None;}let(i,j)=self.inner.locate(index);Some(&mut self.inner.buckets[i].values[j])}pub fn first(&self)->Option<&T>{self.inner.buckets.first()?.values.first()}pub fn last(&self)->Option<&T>{self.inner.buckets.last()?.values.last()}pub fn insert(&mut self,index:usize,value:T){assert!(index<=self.len());self.inner.insert(self.inner.locate(index),value);}pub fn remove(&mut self,index:usize)->T{assert!(indexOption{let i=self.inner.buckets.len().checked_sub(1)?;Some(self.inner.remove((i,self.inner.buckets[i].values.len()-1)))}pub fn iter(&self)->SqrtIter<'_,T>{SqrtIter{buckets:&self.inner.buckets,front:(0,0),back:(self.inner.buckets.len(),0)}}pub fn iter_mut(&mut self)->impl DoubleEndedIterator{self.inner.buckets.iter_mut().flat_map(|b|b.values.iter_mut())}}implDefault for SqrtVec{fn default()->Self{Self::new()}}implFromIteratorfor SqrtVec{fn from_iter(iter:I)->Self where I:IntoIterator{let values:Vec<_>=iter.into_iter().collect();Self{inner:Buckets::build(values.len(),values.into_iter())}}}implExtendfor SqrtVec{fn extend(&mut self,iter:I)where I:IntoIterator{for value in iter{self.push(value);}}}implDebug for SqrtVecwhere T:Debug{fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{f.debug_list().entries(self.iter()).finish()}}implPartialEq for SqrtVecwhere T:PartialEq{fn eq(&self,other:&Self)->bool{self.len()==other.len()&&self.iter().eq(other.iter())}}implEq for SqrtVecwhere T:Eq{}implIntoIterator for SqrtVec{type Item=T;type IntoIter=SqrtIntoIter;fn into_iter(self)->Self::IntoIter{SqrtIntoIter{buckets:self.inner.buckets.into_iter(),front:Vec::new().into_iter(),back:Vec::new().into_iter(),remaining:self.inner.len}}}impl<'a,T>IntoIterator for&'a SqrtVec{type Item=&'a T;type IntoIter=SqrtIter<'a,T>;fn into_iter(self)->Self::IntoIter{self.iter()}}#[derive(Debug)]pub struct SqrtIter<'a,T>{buckets:&'a[Bucket],front:(usize,usize),back:(usize,usize)}implClone for SqrtIter<'_,T>{fn clone(&self)->Self{Self{buckets:self.buckets,front:self.front,back:self.back}}}impl<'a,T>Iterator for SqrtIter<'a,T>{type Item=&'a T;fn next(&mut self)->Option{if self.front>=self.back{return None;}let(i,j)=self.front;let values=&self.buckets[i].values;self.front=if j+1==values.len(){(i+1,0)}else{(i,j+1)};Some(&values[j])}}implDoubleEndedIterator for SqrtIter<'_,T>{fn next_back(&mut self)->Option{if self.front>=self.back{return None;}if self.back.1==0{self.back.0-=1;self.back.1=self.buckets[self.back.0].values.len();}self.back.1-=1;Some(&self.buckets[self.back.0].values[self.back.1])}}implFusedIterator for SqrtIter<'_,T>{}#[derive(Clone,Debug)]pub struct SqrtIntoIter{buckets:std::vec::IntoIter>,front:std::vec::IntoIter,back:std::vec::IntoIter,remaining:usize}implIterator for SqrtIntoIter{type Item=T;fn next(&mut self)->Option{let value=loop{if let Some(value)=self.front.next(){break Some(value);}if let Some(bucket)=self.buckets.next(){self.front=bucket.values.into_iter();}else{break self.back.next();}};self.remaining-=usize::from(value.is_some());value}fn size_hint(&self)->(usize,Option){(self.remaining,Some(self.remaining))}}implDoubleEndedIterator for SqrtIntoIter{fn next_back(&mut self)->Option{let value=loop{if let Some(value)=self.back.next_back(){break Some(value);}if let Some(bucket)=self.buckets.next_back(){self.back=bucket.values.into_iter();}else{break self.front.next_back();}};self.remaining-=usize::from(value.is_some());value}}implExactSizeIterator for SqrtIntoIter{}implFusedIterator for SqrtIntoIter{}macro_rules!sqrt_set{($name:ident,$doc:literal)=>{#[doc=$doc]#[derive(Clone,Debug,PartialEq,Eq)]pub struct$name{inner:SqrtVec,}impl$name{pub fn new()->Self{Self{inner:SqrtVec::new(),}}pub fn len(&self)->usize{self.inner.len()}pub fn is_empty(&self)->bool{self.inner.is_empty()}pub fn clear(&mut self){self.inner.clear();}pub fn iter(&self)->SqrtIter<'_,T>{self.inner.iter()}pub fn first(&self)->Option<&T>{self.inner.first()}pub fn last(&self)->Option<&T>{self.inner.last()}pub fn get_at(&self,index:usize)->Option<&T>{self.inner.get(index)}pub fn remove_at(&mut self,index:usize)->Option{(index(&self,key:&Q)->Option<&T>where T:Borrow,Q:Ord+?Sized,{let p=self.inner.inner.partition_point(|v|v.borrow()>::borrow(v)==key)}pub fn contains(&self,key:&Q)->bool where T:Borrow,Q:Ord+?Sized,{self.get(key).is_some()}#[doc=" Removes one occurrence and returns whether it was present."]pub fn remove(&mut self,key:&Q)->bool where T:Borrow,Q:Ord+?Sized,{let p=self.inner.inner.partition_point(|v|v.borrow()(&self,key:&Q)->usize where T:Borrow,Q:Ord+?Sized,{self.inner.inner.position(self.inner.inner.partition_point(|v|v.borrow()(&self,key:&Q)->usize where T:Borrow,Q:Ord+?Sized,{self.inner.inner.position(self.inner.inner.partition_point(|v|v.borrow()<=key))}pub fn range(&self,range:R)->SqrtIter<'_,T>where T:Borrow,Q:Ord+?Sized,R:RangeBounds,{self.inner.inner.range(range,|v|v.borrow())}}implDefault for$name{fn default()->Self{Self::new()}}implExtendfor$namewhere T:Ord,{fn extend(&mut self,iter:I)where I:IntoIterator,{for value in iter{self.insert(value);}}}implIntoIterator for$name{type Item=T;type IntoIter=SqrtIntoIter;fn into_iter(self)->Self::IntoIter{self.inner.into_iter()}}impl<'a,T>IntoIterator for&'a$name{type Item=&'a T;type IntoIter=SqrtIter<'a,T>;fn into_iter(self)->Self::IntoIter{self.iter()}}};}sqrt_set!(SqrtSet,"An ordered set with O(log N) key lookup and amortized O(sqrt(N)) updates. Rank and indexing take O(sqrt(N)).");sqrt_set!(SqrtMultiset,"An ordered multiset. Length, rank and indexing count duplicate elements. Complexity matches `SqrtSet`.");implSqrtSet{pub fn insert(&mut self,value:T)->bool where T:Ord{let p=self.inner.inner.partition_point(|v|v<&value);if self.inner.inner.at(p)==Some(&value){return false;}self.inner.inner.insert(p,value);true}}implFromIteratorfor SqrtSetwhere T:Ord{fn from_iter(iter:I)->Self where I:IntoIterator{let mut values:Vec<_>=iter.into_iter().collect();values.sort_unstable();values.dedup();Self{inner:SqrtVec{inner:Buckets::build(values.len(),values.into_iter())}}}}implSqrtMultiset{pub fn insert(&mut self,value:T)where T:Ord{let p=self.inner.inner.partition_point(|v|v<=&value);self.inner.inner.insert(p,value);}pub fn count(&self,key:&Q)->usize where T:Borrow,Q:Ord+?Sized{self.rank_le(key)-self.rank(key)}}implFromIteratorfor SqrtMultisetwhere T:Ord{fn from_iter(iter:I)->Self where I:IntoIterator{let mut values:Vec<_>=iter.into_iter().collect();values.sort_unstable();Self{inner:SqrtVec{inner:Buckets::build(values.len(),values.into_iter())}}}}#[doc=" An ordered map with O(log N) key lookup and amortized O(sqrt(N)) updates."]#[doc=" Rank and indexing take O(sqrt(N))."]#[derive(Clone,Debug,PartialEq,Eq)]pub struct SqrtMap{inner:SqrtVec<(K,V)>}implSqrtMap{pub fn new()->Self{Self{inner:SqrtVec::new()}}pub fn len(&self)->usize{self.inner.len()}pub fn is_empty(&self)->bool{self.inner.is_empty()}pub fn clear(&mut self){self.inner.clear();}pub fn iter(&self)->impl DoubleEndedIterator{self.inner.iter().map(|(k,v)|(k,v))}pub fn iter_mut(&mut self)->impl DoubleEndedIterator{self.inner.iter_mut().map(|(k,v)|(&*k,v))}pub fn get_key_value_at(&self,index:usize)->Option<(&K,&V)>{self.inner.get(index).map(|(k,v)|(k,v))}pub fn remove_at(&mut self,index:usize)->Option<(K,V)>{(indexOption<(&K,&V)>{self.inner.first().map(|(k,v)|(k,v))}pub fn last_key_value(&self)->Option<(&K,&V)>{self.inner.last().map(|(k,v)|(k,v))}pub fn get(&self,key:&Q)->Option<&V>where K:Borrow,Q:Ord+?Sized{self.get_key_value(key).map(|(_,v)|v)}pub fn get_key_value(&self,key:&Q)->Option<(&K,&V)>where K:Borrow,Q:Ord+?Sized{let p=self.inner.inner.partition_point(|(k,_)|k.borrow()(&mut self,key:&Q)->Option<&mut V>where K:Borrow,Q:Ord+?Sized{let(i,j)=self.inner.inner.partition_point(|(k,_)|k.borrow()>::borrow(k)==key).then_some(v)}pub fn contains_key(&self,key:&Q)->bool where K:Borrow,Q:Ord+?Sized{self.get(key).is_some()}pub fn insert(&mut self,key:K,value:V)->Optionwhere K:Ord{let(i,j)=self.inner.inner.partition_point(|(k,_)|k<&key);if self.inner.inner.at((i,j)).is_some_and(|(k,_)|k==&key){return Some(mem::replace(&mut self.inner.inner.buckets[i].values[j].1,value));}self.inner.inner.insert((i,j),(key,value));None}pub fn remove(&mut self,key:&Q)->Optionwhere K:Borrow,Q:Ord+?Sized{self.remove_entry(key).map(|(_,v)|v)}pub fn remove_entry(&mut self,key:&Q)->Option<(K,V)>where K:Borrow,Q:Ord+?Sized{let p=self.inner.inner.partition_point(|(k,_)|k.borrow()(&self,key:&Q)->usize where K:Borrow,Q:Ord+?Sized{self.inner.inner.position(self.inner.inner.partition_point(|(k,_)|k.borrow()(&self,key:&Q)->usize where K:Borrow,Q:Ord+?Sized{self.inner.inner.position(self.inner.inner.partition_point(|(k,_)|k.borrow()<=key))}pub fn range(&self,range:R)->impl DoubleEndedIteratorwhere K:Borrow,Q:Ord+?Sized,R:RangeBounds{self.inner.inner.range(range,|(k,_)|k.borrow()).map(|(k,v)|(k,v))}}implDefault for SqrtMap{fn default()->Self{Self::new()}}implFromIterator<(K,V)>for SqrtMapwhere K:Ord{fn from_iter(iter:I)->Self where I:IntoIterator{let mut values:Vec<_>=iter.into_iter().collect();sort_dedup_map(&mut values);Self{inner:SqrtVec{inner:Buckets::build(values.len(),values.into_iter())}}}}implExtend<(K,V)>for SqrtMapwhere K:Ord{fn extend(&mut self,iter:I)where I:IntoIterator{for(k,v)in iter{self.insert(k,v);}}}implIntoIterator for SqrtMap{type Item=(K,V);type IntoIter=SqrtIntoIter<(K,V)>;fn into_iter(self)->Self::IntoIter{self.inner.into_iter()}}}trait BucketState:Sized{fn new(values:&[T])->Self;fn push(&mut self,values:&mut[T]);}implBucketStatefor(){fn new(_:&[T])->Self{}fn push(&mut self,_:&mut[T]){}}#[derive(Clone,Debug)]struct Bucket{values:Vec,state:S}#[derive(Clone,Debug)]struct Buckets{buckets:Vec>,sizes:Vec,len:usize,base_len:usize,bucket_size:usize}implBucketswhere S:BucketState{fn new()->Self{Self{buckets:Vec::new(),sizes:Vec::new(),len:0,base_len:0,bucket_size:1}}fn build(len:usize,mut values:impl Iterator)->Self{if len==0{return Self::new();}let bucket_size=(len-1).isqrt()+1;let mut buckets=Vec::with_capacity(len.div_ceil(bucket_size));let mut sizes=Vec::with_capacity(len.div_ceil(bucket_size));while let Some(first)=values.next(){let mut chunk=Vec::with_capacity(bucket_size);chunk.push(first);chunk.extend(values.by_ref().take(bucket_size-1));sizes.push(chunk.len());let state=S::new(&chunk);buckets.push(Bucket{values:chunk,state});}Self{buckets,sizes,len,base_len:len,bucket_size}}fn locate(&self,mut index:usize)->(usize,usize){if index>=self.len/2{index=self.len-index;for(i,&size)in self.sizes.iter().enumerate().rev(){if index<=size{return(i,size-index);}index-=size;}return(0,0);}for(i,&size)in self.sizes.iter().enumerate(){if index2*self.bucket_size{let right=values.split_off(values.len()/2);self.sizes[i]=values.len();self.sizes.insert(i+1,right.len());*state=S::new(values);let state=S::new(&right);self.buckets.insert(i+1,Bucket{values:right,state});}else{*state=S::new(values);}self.len+=1;self.rebuild_if_needed();}fn remove(&mut self,(i,j):(usize,usize))->T{let Bucket{values,state}=&mut self.buckets[i];state.push(values);let value=values.remove(j);self.sizes[i]-=1;if values.is_empty(){self.buckets.remove(i);self.sizes.remove(i);}else{*state=S::new(values);}self.len-=1;self.rebuild_if_needed();value}fn rebuild_if_needed(&mut self){if self.lenself.base_len.saturating_mul(2)||self.buckets.len()>2*self.base_len.div_ceil(self.bucket_size){let values=mem::take(&mut self.buckets).into_iter().flat_map(|mut bucket|{bucket.state.push(&mut bucket.values);bucket.values});*self=Self::build(self.len,values);}}fn partition_point(&self,mut before:impl FnMut(&T)->bool)->(usize,usize){let i=self.buckets.partition_point(|b|before(b.values.last().unwrap()));let j=self.buckets.get(i).map_or(0,|b|b.values.partition_point(before));(i,j)}fn position(&self,(i,j):(usize,usize))->usize{if i()+j}else{self.len-self.sizes[i..].iter().sum::()+j}}fn at(&self,(i,j):(usize,usize))->Option<&T>{self.buckets.get(i).and_then(|b|b.values.get(j))}fn bounds(&self,range:R,key:impl Fn(&T)->&Q)->((usize,usize),(usize,usize))where Q:Ord+?Sized,R:RangeBounds{let start=range.start_bound();let end=range.end_bound();if let(Bound::Included(a)|Bound::Excluded(a),Bound::Included(b)|Bound::Excluded(b))=(start,end){assert!(a<=b&&!(a==b&&matches!((start,end),(Bound::Excluded(_),Bound::Excluded(_)))),"invalid range");}let front=match start{Bound::Unbounded=>(0,0),Bound::Included(x)=>self.partition_point(|v|key(v)self.partition_point(|v|key(v)<=x),};let back=match end{Bound::Unbounded=>(self.buckets.len(),0),Bound::Included(x)=>self.partition_point(|v|key(v)<=x),Bound::Excluded(x)=>self.partition_point(|v|key(v)(values:&mut Vec<(K,V)>)where K:Ord{values.sort_by(|a,b|a.0 .cmp(&b.0));values.dedup_by(|a,b|{if a.0==b.0{mem::swap(&mut a.1,&mut b.1);true}else{false}});}trait BucketValue{type Value;fn get(value:&T)->&Self::Value;fn get_mut(value:&mut T)->&mut Self::Value;}struct SequenceValue;implBucketValuefor SequenceValue{type Value=T;fn get(value:&T)->&T{value}fn get_mut(value:&mut T)->&mut T{value}}struct MapValue;implBucketValue<(K,V)>for MapValue{type Value=V;fn get(value:&(K,V))->&V{&value.1}fn get_mut(value:&mut(K,V))->&mut V{&mut value.1}}} // codesnip-guard: AdditiveOperation #[cfg_attr(any(),rustfmt::skip)]pub use self::additive_operation_impl::AdditiveOperation;#[cfg_attr(any(),rustfmt::skip)]mod additive_operation_impl{use super::*;use std::{marker::PhantomData,ops::{Add,Neg,Sub}};#[doc=" $+$"]pub struct AdditiveOperationwhere T:Clone+Zero+Add{_marker:PhantomDataT>}implMagma for AdditiveOperationwhere T:Clone+Zero+Add{type T=T;#[inline]fn operate(x:&Self::T,y:&Self::T)->Self::T{x.clone()+y.clone()}}implUnital for AdditiveOperationwhere T:Clone+Zero+Add{#[inline]fn unit()->Self::T{Zero::zero()}}implAssociative for AdditiveOperationwhere T:Clone+Zero+Add{}implCommutative for AdditiveOperationwhere T:Clone+Zero+Add{}implInvertible for AdditiveOperationwhere T:Clone+Zero+Add+Sub+Neg{#[inline]fn inverse(x:&Self::T)->Self::T{-x.clone()}#[inline]fn rinv_operate(x:&Self::T,y:&Self::T)->Self::T{x.clone()-y.clone()}}} // codesnip-guard: ArrayOperation #[cfg_attr(any(),rustfmt::skip)]pub use self::array_operation_impl::ArrayOperation;#[cfg_attr(any(),rustfmt::skip)]mod array_operation_impl{use super::*;use crate::array;use std::marker::PhantomData;pub struct ArrayOperation{_marker:PhantomDataM>}implMagma for ArrayOperationwhere M:Magma{type T=[M::T;N];#[inline]fn operate(x:&Self::T,y:&Self::T)->Self::T{array!(|i|M::operate(&x[i],&y[i]);N)}}implUnital for ArrayOperationwhere M:Unital{#[inline]fn unit()->Self::T{array!(||M::unit();N)}}implAssociative for ArrayOperationwhere M:Associative{}implCommutative for ArrayOperationwhere M:Commutative{}implIdempotent for ArrayOperationwhere M:Idempotent{}implInvertible for ArrayOperationwhere M:Invertible{#[inline]fn inverse(x:&Self::T)->Self::T{array!(|i|M::inverse(&x[i]);N)}}} // codesnip-guard: CountingOperation #[cfg_attr(any(),rustfmt::skip)]pub use self::counting_operation_impl::CountingOperation;#[cfg_attr(any(),rustfmt::skip)]mod counting_operation_impl{use super::*;use std::marker::PhantomData;pub struct CountingOperation{_marker:PhantomDataM>}implMagma for CountingOperationwhere M:Magma+Idempotent{type T=(M::T,usize);#[inline]fn operate(x:&Self::T,y:&Self::T)->Self::T{let z=M::operate(&x.0,&y.0);match(z==x.0,z==y.0){(true,true)=>(z,x.1+y.1),(true,false)=>(z,x.1),(false,true)=>(z,y.1),(false,false)=>(z,1),}}}implUnital for CountingOperationwhere M:Unital+Idempotent{#[inline]fn unit()->Self::T{(M::unit(),0)}}implAssociative for CountingOperationwhere M:Associative+Idempotent{}implCommutative for CountingOperationwhere M:Commutative+Idempotent{}} // codesnip-guard: LastOperation #[cfg_attr(any(),rustfmt::skip)]pub use self::last_operation_impl::LastOperation;#[cfg_attr(any(),rustfmt::skip)]mod last_operation_impl{use super::*;use std::marker::PhantomData;#[doc=" retain the last element"]pub struct LastOperationwhere T:Clone{_marker:PhantomDataT>}implMagma for LastOperationwhere T:Clone{type T=Option;#[inline]fn operate(x:&Self::T,y:&Self::T)->Self::T{y.as_ref().or(x.as_ref()).cloned()}}implUnital for LastOperationwhere T:Clone{#[inline]fn unit()->Self::T{None}}implAssociative for LastOperationwhere T:Clone{}implIdempotent for LastOperationwhere T:Clone{}} // codesnip-guard: LazyMapMonoid #[cfg_attr(any(),rustfmt::skip)]pub use self::lazy_map::*;#[cfg_attr(any(),rustfmt::skip)]mod lazy_map{use super::*;use std::{cmp::Ordering,marker::PhantomData,ops::{Add,Mul,Sub}};pub type LazyMapAgg=<::AggMonoid as Magma>::T;pub type LazyMapAct=<::ActMonoid as Magma>::T;pub trait LazyMapMonoid{type Key;type AggMonoid:Monoid;type ActMonoid:Monoid;fn single_agg(key:&Self::Key)->LazyMapAgg;fn toggle(_x:&mut LazyMapAgg){}#[inline]fn is_act_unit(act:&LazyMapAct)->bool{::is_unit(act)}#[doc=" Returns `None` when descent is needed; must succeed on single-key aggregates."]fn act_agg(x:&LazyMapAgg,a:&LazyMapAct)->Option>;#[inline]fn agg_unit()->LazyMapAgg{::unit()}#[inline]fn act_unit()->LazyMapAct{::unit()}#[inline]fn agg_operate(x:&LazyMapAgg,y:&LazyMapAgg)->LazyMapAgg{::operate(x,y)}#[inline]fn act_operate(x:&LazyMapAct,y:&LazyMapAct)->LazyMapAct{::operate(x,y)}#[inline]fn agg_operate_assign(x:&mut LazyMapAgg,y:&LazyMapAgg){*x=::operate(x,y);}#[inline]fn act_operate_assign(x:&mut LazyMapAct,y:&LazyMapAct){*x=::operate(x,y);}}pub trait LazyMapMonoidWithKeyAct:LazyMapMonoid{fn act_key(key:&Self::Key,act:&LazyMapAct)->Self::Key;}pub struct EmptyActLazy{_marker:PhantomDataM>}implLazyMapMonoid for EmptyActLazywhere M:Monoid{type Key=M::T;type AggMonoid=M;type ActMonoid=();fn single_agg(key:&Self::Key)->LazyMapAgg{key.clone()}fn act_agg(x:&LazyMapAgg,_a:&LazyMapAct)->Option>{Some(x.clone())}}implLazyMapMonoidWithKeyAct for EmptyActLazywhere M:Monoid{fn act_key(key:&Self::Key,act:&LazyMapAct)->Self::Key{EmptyAct::act(key,act)}}pub struct EmptyAggActLazy{_marker:PhantomDataT>}implLazyMapMonoid for EmptyAggActLazy{type Key=T;type AggMonoid=();type ActMonoid=();fn single_agg(_key:&Self::Key)->LazyMapAgg{}fn act_agg(_x:&LazyMapAgg,_a:&LazyMapAct)->Option>{Some(())}}implLazyMapMonoidWithKeyAct for EmptyAggActLazywhere T:Clone{fn act_key(key:&Self::Key,act:&LazyMapAct)->Self::Key{EmptyAct::act(key,act)}}pub struct FlattenLazy{_marker:PhantomDataM>}implLazyMapMonoid for FlattenLazywhere M:Monoid,M::T:PartialEq{type Key=M::T;type AggMonoid=M;type ActMonoid=M;fn single_agg(key:&Self::Key)->LazyMapAgg{key.clone()}fn act_agg(x:&LazyMapAgg,a:&LazyMapAct)->Option>{Some(M::operate(x,a))}}implLazyMapMonoidWithKeyAct for FlattenLazywhere M:Monoid,M::T:PartialEq{fn act_key(key:&Self::Key,act:&LazyMapAct)->Self::Key{FlattenAct::::act(key,act)}}pub struct RangeSumRangeAdd{_marker:PhantomDataT>}implLazyMapMonoid for RangeSumRangeAddwhere T:Copy+Zero+One+Add+Mul+PartialEq{type Key=T;type AggMonoid=(AdditiveOperation,AdditiveOperation);type ActMonoid=AdditiveOperation;fn single_agg(key:&Self::Key)->LazyMapAgg{(*key,T::one())}fn act_agg(&(x,y):&LazyMapAgg,a:&LazyMapAct)->Option>{Some(if Self::is_act_unit(a){(x,y)}else{let a=*a;(x+a*y,y)})}}implLazyMapMonoidWithKeyAct for RangeSumRangeAddwhere T:Copy+Zero+One+Add+Mul+PartialEq{fn act_key(key:&Self::Key,act:&LazyMapAct)->Self::Key{FlattenAct::::act(key,act)}}pub struct RangeSumRangeLinear{_marker:PhantomDataT>}implLazyMapMonoid for RangeSumRangeLinearwhere T:Copy+Zero+One+Add+Mul+PartialEq{type Key=T;type AggMonoid=(AdditiveOperation,AdditiveOperation);type ActMonoid=LinearOperation;fn single_agg(key:&Self::Key)->LazyMapAgg{(*key,T::one())}fn act_agg(&(x,y):&LazyMapAgg,&(a,b):&LazyMapAct)->Option>{Some((a*x+b*y,y))}}implLazyMapMonoidWithKeyAct for RangeSumRangeLinearwhere T:Copy+Zero+One+Add+Mul+PartialEq{fn act_key(key:&Self::Key,act:&LazyMapAct)->Self::Key{LinearAct::act(key,act)}}pub struct RangePowerSumRangeLinear{_marker:PhantomDataT>}implLazyMapMonoid for RangePowerSumRangeLinearwhere T:Copy+Zero+One+Add+Mul+PartialEq{type Key=T;type AggMonoid=ArrayOperation,K>;type ActMonoid=LinearOperation;fn single_agg(key:&Self::Key)->LazyMapAgg{let mut power=T::one();std::array::from_fn(|k|{if k!=0{power=power**key;}power})}fn act_agg(x:&LazyMapAgg,&(a,b):&LazyMapAct)->Option>{let mut coefficients=[T::one();K];let mut result=*x;for k in 1..K{coefficients[k]=a*coefficients[k-1];for j in(1..k).rev(){coefficients[j]=b*coefficients[j]+a*coefficients[j-1];}coefficients[0]=b*coefficients[0];result[k]=coefficients[..=k].iter().zip(x).fold(T::zero(),|sum,(&c,&p)|sum+c*p);}Some(result)}}implLazyMapMonoidWithKeyAct for RangePowerSumRangeLinearwhere T:Copy+Zero+One+Add+Mul+PartialEq{fn act_key(key:&Self::Key,act:&LazyMapAct)->Self::Key{LinearAct::act(key,act)}}pub struct RangeSumRangeUpdate{_marker:PhantomDataT>}implLazyMapMonoid for RangeSumRangeUpdatewhere T:Copy+Zero+One+Add+Mul+PartialEq{type Key=T;type AggMonoid=(AdditiveOperation,AdditiveOperation);type ActMonoid=LastOperation;fn single_agg(key:&Self::Key)->LazyMapAgg{(*key,T::one())}fn act_agg(&(x,y):&LazyMapAgg,a:&LazyMapAct)->Option>{Some((a.map(|a|a*y).unwrap_or(x),y))}}implLazyMapMonoidWithKeyAct for RangeSumRangeUpdatewhere T:Copy+Zero+One+Add+Mul+PartialEq{fn act_key(key:&Self::Key,act:&LazyMapAct)->Self::Key{UpdateAct::act(key,act)}}pub struct RangeMaxRangeUpdate{_marker:PhantomDataT>}implLazyMapMonoid for RangeMaxRangeUpdatewhere T:Clone+PartialEq+Ord+Bounded{type Key=T;type AggMonoid=MaxOperation;type ActMonoid=LastOperation;fn single_agg(key:&Self::Key)->LazyMapAgg{key.clone()}fn act_agg(x:&LazyMapAgg,a:&LazyMapAct)->Option>{Some(a.as_ref().unwrap_or(x).clone())}}implLazyMapMonoidWithKeyAct for RangeMaxRangeUpdatewhere T:Clone+PartialEq+Ord+Bounded{fn act_key(key:&Self::Key,act:&LazyMapAct)->Self::Key{UpdateAct::act(key,act)}}pub struct RangeMinRangeUpdate{_marker:PhantomDataT>}implLazyMapMonoid for RangeMinRangeUpdatewhere T:Clone+PartialEq+Ord+Bounded{type Key=T;type AggMonoid=MinOperation;type ActMonoid=LastOperation;fn single_agg(key:&Self::Key)->LazyMapAgg{key.clone()}fn act_agg(x:&LazyMapAgg,a:&LazyMapAct)->Option>{Some(a.as_ref().unwrap_or(x).clone())}}implLazyMapMonoidWithKeyAct for RangeMinRangeUpdatewhere T:Clone+PartialEq+Ord+Bounded{fn act_key(key:&Self::Key,act:&LazyMapAct)->Self::Key{UpdateAct::act(key,act)}}pub struct RangeMaxRangeAdd{_marker:PhantomDataT>}implLazyMapMonoid for RangeMaxRangeAddwhere T:Clone+Ord+Bounded+Zero+Add{type Key=T;type AggMonoid=MaxOperation;type ActMonoid=AdditiveOperation;fn single_agg(key:&Self::Key)->LazyMapAgg{key.clone()}fn act_agg(x:&LazyMapAgg,a:&LazyMapAct)->Option>{Some(if Self::is_act_unit(a){x.clone()}else{x.clone()+a.clone()})}}implLazyMapMonoidWithKeyAct for RangeMaxRangeAddwhere T:Clone+Ord+Bounded+Zero+Add{fn act_key(key:&Self::Key,act:&LazyMapAct)->Self::Key{FlattenAct::::act(key,act)}}pub struct RangeMinRangeAdd{_marker:PhantomDataT>}implLazyMapMonoid for RangeMinRangeAddwhere T:Clone+Ord+Bounded+Zero+Add{type Key=T;type AggMonoid=MinOperation;type ActMonoid=AdditiveOperation;fn single_agg(key:&Self::Key)->LazyMapAgg{key.clone()}fn act_agg(x:&LazyMapAgg,a:&LazyMapAct)->Option>{Some(if Self::is_act_unit(a){x.clone()}else{x.clone()+a.clone()})}}implLazyMapMonoidWithKeyAct for RangeMinRangeAddwhere T:Clone+Ord+Bounded+Zero+Add{fn act_key(key:&Self::Key,act:&LazyMapAct)->Self::Key{FlattenAct::::act(key,act)}}pub struct RangeMinCountRangeAdd{_marker:PhantomDataT>}implLazyMapMonoid for RangeMinCountRangeAddwhere T:Clone+Ord+Bounded+Zero+Add{type Key=T;type AggMonoid=CountingOperation>;type ActMonoid=AdditiveOperation;fn single_agg(key:&Self::Key)->LazyMapAgg{(key.clone(),1)}fn act_agg(x:&LazyMapAgg,a:&LazyMapAct)->Option>{Some(if x.1==0{x.clone()}else{(x.0 .clone()+a.clone(),x.1)})}}implLazyMapMonoidWithKeyAct for RangeMinCountRangeAddwhere T:Clone+Ord+Bounded+Zero+Add{fn act_key(key:&Self::Key,act:&LazyMapAct)->Self::Key{FlattenAct::::act(key,act)}}#[derive(Debug,Clone,Copy,PartialEq,Eq)]pub struct RangeChminChmaxAdd{lb:T,ub:T,bias:T}implRangeChminChmaxAddwhere T:Zero+Bounded{pub fn chmin(x:T)->Self{Self{lb:T::minimum(),ub:x,bias:T::zero()}}pub fn chmax(x:T)->Self{Self{lb:x,ub:T::maximum(),bias:T::zero()}}pub fn add(x:T)->Self where T:Copy+Ord+Add{Self{lb:T::minimum()+x.max(T::zero()),ub:T::maximum()+x.min(T::zero()),bias:x}}}implMagma for RangeChminChmaxAddwhere T:Copy+Zero+Ord+Bounded+Add{type T=Self;fn operate(x:&Self::T,y:&Self::T)->Self::T{Self{lb:(x.lb+y.bias).max(y.lb).min(y.ub),ub:(x.ub+y.bias).max(y.lb).min(y.ub),bias:x.bias+y.bias}}}implAssociative for RangeChminChmaxAddwhere T:Copy+Zero+Ord+Bounded+Add{}implUnital for RangeChminChmaxAddwhere T:Copy+Zero+Ord+Bounded+Add{fn unit()->Self::T{Self{lb:T::minimum(),ub:T::maximum(),bias:T::zero()}}}#[derive(Debug,Clone,PartialEq,Eq)]pub struct RangeSumRangeChminChmaxAdd{min:T,max:T,min2:T,max2:T,pub sum:T,size:T,n_min:T,n_max:T}implRangeSumRangeChminChmaxAddwhere T:Copy+Zero+One+Ord+Bounded+Add+Sub+Mul+PartialEq{pub fn single(key:T,size:T)->Self{Self{min:key,max:key,min2:T::maximum(),max2:T::minimum(),sum:key*size,size,n_min:size,n_max:size}}}implMagma for RangeSumRangeChminChmaxAddwhere T:Copy+Zero+One+Ord+Bounded+Add+Sub+Mul+PartialEq{type T=Self;fn operate(x:&Self::T,y:&Self::T)->Self::T{Self{min:x.min.min(y.min),max:x.max.max(y.max),min2:if x.min==y.min{x.min2.min(y.min2)}else if x.min2<=y.min{x.min2}else if y.min2<=x.min{y.min2}else{x.min.max(y.min)},max2:if x.max==y.max{x.max2.max(y.max2)}else if x.max2>=y.max{x.max2}else if y.max2>=x.max{y.max2}else{x.max.min(y.max)},sum:x.sum+y.sum,size:x.size+y.size,n_min:match x.min.cmp(&y.min){Ordering::Less=>x.n_min,Ordering::Equal=>x.n_min+y.n_min,Ordering::Greater=>y.n_min,},n_max:match x.max.cmp(&y.max){Ordering::Less=>y.n_max,Ordering::Equal=>x.n_max+y.n_max,Ordering::Greater=>x.n_max,}}}}implAssociative for RangeSumRangeChminChmaxAddwhere T:Copy+Zero+One+Ord+Bounded+Add+Sub+Mul+PartialEq{}implUnital for RangeSumRangeChminChmaxAddwhere T:Copy+Zero+One+Ord+Bounded+Add+Sub+Mul+PartialEq{fn unit()->Self::T{Self{min:T::maximum(),max:T::minimum(),min2:T::maximum(),max2:T::minimum(),sum:T::zero(),size:T::zero(),n_min:T::zero(),n_max:T::zero()}}}implMonoidAct for RangeChminChmaxAddwhere T:Copy+Zero+Ord+Bounded+Add{type Key=T;type Act=RangeChminChmaxAdd;type ActMonoid=RangeChminChmaxAdd;fn act(x:&Self::Key,a:&Self::Act)->Self::Key{(*x+a.bias).max(a.lb).min(a.ub)}}implLazyMapMonoid for RangeSumRangeChminChmaxAddwhere T:Copy+Zero+One+Ord+Bounded+Add+Sub+Mul+PartialEq{type Key=T;type AggMonoid=Self;type ActMonoid=RangeChminChmaxAdd;fn single_agg(&key:&Self::Key)->LazyMapAgg{Self::single(key,T::one())}fn act_agg(x:&LazyMapAgg,a:&LazyMapAct)->Option>{if Self::is_act_unit(a){return Some(x.clone());}if x.size.is_zero(){return Some(Self::unit());}let lb=a.lb-a.bias;let ub=a.ub-a.bias;let min=x.min.max(lb);let max=x.max.min(ub);Some(if min>=max{Self::single(RangeChminChmaxAdd::act(&x.min,a),x.size)}else if x.min2==x.max{let mut x=x.clone();let min=min+a.bias;let max=max+a.bias;x.min=min;x.max2=min;x.max=max;x.min2=max;x.sum=min*x.n_min+max*x.n_max;x}else if lbLazyMapMonoidWithKeyAct for RangeSumRangeChminChmaxAddwhere T:Copy+Zero+One+Ord+Bounded+Add+Sub+Mul+PartialEq{fn act_key(key:&Self::Key,act:&LazyMapAct)->Self::Key{RangeChminChmaxAdd::act(key,act)}}} // codesnip-guard: LinearOperation #[cfg_attr(any(),rustfmt::skip)]pub use self::linear_operation_impl::LinearOperation;#[cfg_attr(any(),rustfmt::skip)]mod linear_operation_impl{use super::*;use std::{marker::PhantomData,ops::{Add,Div,Mul,Neg,Sub}};#[doc=" $(a, b) \\circ (c, d) = \\lambda x. c \\times (a \\times x + b) + d$"]pub struct LinearOperationwhere T:Clone+Zero+Add+One+Mul{_marker:PhantomDataT>}implLinearOperationwhere T:Clone+Zero+Add+One+Mul{pub fn apply(f:&(T,T),x:&T)->T{f.0 .clone()*x.clone()+f.1 .clone()}}implMagma for LinearOperationwhere T:Clone+Zero+One+Add+Mul{type T=(T,T);#[inline]fn operate(x:&Self::T,y:&Self::T)->Self::T{(y.0 .clone()*x.0 .clone(),y.0 .clone()*x.1 .clone()+y.1 .clone())}}implUnital for LinearOperationwhere T:Clone+Zero+One+Add+Mul{#[inline]fn unit()->Self::T{(One::one(),Zero::zero())}}implAssociative for LinearOperationwhere T:Clone+Zero+One+Add+Mul{}implInvertible for LinearOperationwhere T:Clone+Zero+One+Add+Sub+Neg+Mul+Div{fn inverse(x:&Self::T)->Self::T{let y=::one().div(x.0 .clone());(y.clone(),-y.mul(x.1 .clone()))}}} // codesnip-guard: MaxOperation #[cfg_attr(any(),rustfmt::skip)]pub use self::max_operation_impl::MaxOperation;#[cfg_attr(any(),rustfmt::skip)]mod max_operation_impl{use super::*;use std::marker::PhantomData;#[doc=" binary operation to select larger element"]pub struct MaxOperationwhere T:Clone+Ord+Bounded{_marker:PhantomDataT>}implMagma for MaxOperationwhere T:Clone+Ord+Bounded{type T=T;#[inline]fn operate(x:&Self::T,y:&Self::T)->Self::T{x.max(y).clone()}}implUnital for MaxOperationwhere T:Clone+Ord+Bounded{#[inline]fn unit()->Self::T{::minimum()}}implAssociative for MaxOperationwhere T:Clone+Ord+Bounded{}implCommutative for MaxOperationwhere T:Clone+Ord+Bounded{}implIdempotent for MaxOperationwhere T:Clone+Ord+Bounded{}} // codesnip-guard: MinOperation #[cfg_attr(any(),rustfmt::skip)]pub use self::min_operation_impl::MinOperation;#[cfg_attr(any(),rustfmt::skip)]mod min_operation_impl{use super::*;use std::marker::PhantomData;#[doc=" binary operation to select smaller element"]pub struct MinOperationwhere T:Clone+Ord+Bounded{_marker:PhantomDataT>}implMagma for MinOperationwhere T:Clone+Ord+Bounded{type T=T;#[inline]fn operate(x:&Self::T,y:&Self::T)->Self::T{x.min(y).clone()}}implUnital for MinOperationwhere T:Clone+Ord+Bounded{#[inline]fn unit()->Self::T{::maximum()}}implAssociative for MinOperationwhere T:Clone+Ord+Bounded{}implCommutative for MinOperationwhere T:Clone+Ord+Bounded{}implIdempotent for MinOperationwhere T:Clone+Ord+Bounded{}} // codesnip-guard: MonoidAct #[cfg_attr(any(),rustfmt::skip)]pub use self::action::*;#[cfg_attr(any(),rustfmt::skip)]mod action{use super::*;use std::{marker::PhantomData,ops::{Add,Mul}};pub trait MonoidAct{type Key;type Act:Clone;type ActMonoid:Monoid;fn act(x:&Self::Key,a:&Self::Act)->Self::Key;fn act_assign(x:&mut Self::Key,a:&Self::Act){*x=Self::act(x,a);}fn unit()->Self::Act{::unit()}fn operate(x:&Self::Act,y:&Self::Act)->Self::Act{::operate(x,y)}fn operate_assign(x:&mut Self::Act,y:&Self::Act){*x=::operate(x,y);}}pub struct EmptyAct{_marker:PhantomDataT>}implMonoidAct for EmptyActwhere T:Clone{type Key=T;type Act=();type ActMonoid=();fn act(x:&Self::Key,_a:&Self::Act)->Self::Key{x.clone()}}pub struct FlattenAct{_marker:PhantomDataM>}implMonoidAct for FlattenActwhere M:Monoid{type Key=M::T;type Act=M::T;type ActMonoid=M;fn act(x:&Self::Key,a:&Self::Act)->Self::Key{M::operate(x,a)}}pub struct LinearAct{_marker:PhantomDataT>}implMonoidAct for LinearActwhere T:Clone+Zero+One+Add+Mul{type Key=T;type Act=(T,T);type ActMonoid=LinearOperation;fn act(x:&Self::Key,(a,b):&Self::Act)->Self::Key{a.clone()*x.clone()+b.clone()}}pub struct UpdateAct{_marker:PhantomDataT>}implMonoidAct for UpdateActwhere T:Clone{type Key=T;type Act=Option;type ActMonoid=LastOperation;fn act(x:&Self::Key,a:&Self::Act)->Self::Key{a.as_ref().unwrap_or(x).clone()}}} // codesnip-guard: TupleOperation #[cfg_attr(any(),rustfmt::skip)]mod tuple_operation_impl{use super::*;macro_rules!impl_tuple_operation{(@impl)=>{impl Magma for(){type T=();fn operate(_x:&Self::T,_y:&Self::T)->Self::T{}}impl Unital for(){fn unit()->Self::T{}}impl Associative for(){}impl Commutative for(){}impl Idempotent for(){}impl Invertible for(){fn inverse(_x:&Self::T)->Self::T{}}};(@impl$($T:ident$i:tt)*)=>{impl<$($T:Magma),*>Magma for($($T,)*){type T=($(<$T as Magma>::T,)*);fn operate(x:&Self::T,y:&Self::T)->Self::T{($(<$T as Magma>::operate(&x.$i,&y.$i),)*)}}impl<$($T:Unital),*>Unital for($($T,)*){fn unit()->Self::T{($(<$T as Unital>::unit(),)*)}}impl<$($T:Associative),*>Associative for($($T,)*){}impl<$($T:Commutative),*>Commutative for($($T,)*){}impl<$($T:Idempotent),*>Idempotent for($($T,)*){}impl<$($T:Invertible),*>Invertible for($($T,)*){fn inverse(x:&Self::T)->Self::T{($(<$T as Invertible>::inverse(&x.$i),)*)}}};(@inner$($T:ident$i:tt)*;$U:ident$j:tt$($t:tt)*)=>{impl_tuple_operation!(@impl$($T$i)*);impl_tuple_operation!(@inner$($T$i)*$U$j;$($t)*);};(@inner$($T:ident$i:tt)*;)=>{impl_tuple_operation!(@impl$($T$i)*);};($($t:tt)*)=>{impl_tuple_operation!(@inner;$($t)*);};}impl_tuple_operation!(A 0 B 1 C 2 D 3 E 4 F 5 G 6 H 7 I 8 J 9);} // codesnip-guard: algebra #[cfg_attr(any(),rustfmt::skip)]pub use self::magma::*;#[cfg_attr(any(),rustfmt::skip)]mod magma{#![doc=" algebraic traits"]#[doc=" binary operaion: $T \\circ T \\to T$"]pub trait Magma{#[doc=" type of operands: $T$"]type T:Clone;#[doc=" binary operaion: $\\circ$"]fn operate(x:&Self::T,y:&Self::T)->Self::T;fn reverse_operate(x:&Self::T,y:&Self::T)->Self::T{Self::operate(y,x)}fn operate_assign(x:&mut Self::T,y:&Self::T){*x=Self::operate(x,y);}}#[doc=" $\\forall a,\\forall b,\\forall c \\in T, (a \\circ b) \\circ c = a \\circ (b \\circ c)$"]pub trait Associative:Magma{}#[doc=" associative binary operation"]pub trait SemiGroup:Magma+Associative{}implSemiGroup for S where S:Magma+Associative{}#[doc=" $\\exists e \\in T, \\forall a \\in T, e \\circ a = a \\circ e = a$"]pub trait Unital:Magma{#[doc=" identity element: $e$"]fn unit()->Self::T;fn is_unit(x:&Self::T)->bool where Self::T:PartialEq{x==&Self::unit()}fn set_unit(x:&mut Self::T){*x=Self::unit();}}pub trait ExpBits{type Iter:Iterator;fn bits(self)->Self::Iter;}pub trait SignedExpBits{type T:ExpBits;fn neg_and_bits(self)->(bool,Self::T);}pub struct Bits{n:T}macro_rules!impl_exp_bits_for_uint{($($t:ty)*)=>{$(impl Iterator for Bits<$t>{type Item=bool;fn next(&mut self)->Option{if self.n==0{None}else{let bit=(self.n&1)==1;self.n>>=1;Some(bit)}}}impl ExpBits for$t{type Iter=Bits<$t>;fn bits(self)->Self::Iter{Bits{n:self}}}impl SignedExpBits for$t{type T=$t;fn neg_and_bits(self)->(bool,Self::T){(false,self)}})*};}impl_exp_bits_for_uint!(u8 u16 u32 u64 u128 usize);macro_rules!impl_signed_exp_bits_for_sint{($($s:ty,$u:ty;)*)=>{$(impl SignedExpBits for$s{type T=$u;fn neg_and_bits(self)->(bool,Self::T){(self<0,self.unsigned_abs())}})*};}impl_signed_exp_bits_for_sint!(i8,u8;i16,u16;i32,u32;i64,u64;i128,u128;isize,usize;);#[doc=" associative binary operation and an identity element"]pub trait Monoid:SemiGroup+Unital{#[doc=" binary exponentiation: $x^n = x\\circ\\ddots\\circ x$"]fn pow(mut x:Self::T,exp:E)->Self::T where E:ExpBits{let mut bits=exp.bits();let Some(first)=bits.next()else{return Self::unit();};let mut res=if first{x.clone()}else{Self::unit()};for bit in bits{x=Self::operate(&x,&x);if bit{res=Self::operate(&res,&x);}}res}fn fold(iter:I)->Self::T where I:IntoIterator{let mut iter=iter.into_iter();if let Some(item)=iter.next(){iter.fold(item,|acc,x|Self::operate(&acc,&x))}else{Self::unit()}}}implMonoid for M where M:SemiGroup+Unital{}#[doc=" $\\exists e \\in T, \\forall a \\in T, \\exists b,c \\in T, b \\circ a = a \\circ c = e$"]pub trait Invertible:Magma+Unital{#[doc=" $a$ where $a \\circ x = e$"]fn inverse(x:&Self::T)->Self::T;fn rinv_operate(x:&Self::T,y:&Self::T)->Self::T{Self::operate(x,&Self::inverse(y))}fn rinv_operate_assign(x:&mut Self::T,y:&Self::T){*x=Self::rinv_operate(x,y);}}#[doc=" associative binary operation and an identity element and inverse elements"]pub trait Group:Monoid+Invertible{fn signed_pow(x:Self::T,exp:E)->Self::T where E:SignedExpBits{let(neg,exp)=E::neg_and_bits(exp);let res=Self::pow(x,exp);if neg{Self::inverse(&res)}else{res}}}implGroup for G where G:Monoid+Invertible{}#[doc=" $\\forall a,\\forall b \\in T, a \\circ b = b \\circ a$"]pub trait Commutative:Magma{}#[doc=" commutative monoid"]pub trait AbelianMonoid:Monoid+Commutative{}implAbelianMonoid for M where M:Monoid+Commutative{}#[doc=" commutative group"]pub trait AbelianGroup:Group+Commutative{}implAbelianGroup for G where G:Group+Commutative{}#[doc=" $\\forall a \\in T, a \\circ a = a$"]pub trait Idempotent:Magma{}#[doc=" idempotent monoid"]pub trait IdempotentMonoid:Monoid+Idempotent{}implIdempotentMonoid for M where M:Monoid+Idempotent{}#[macro_export]macro_rules!monoid_fold{($m:ty)=>{<$m as Unital>::unit()};($m:ty,)=>{<$m as Unital>::unit()};($m:ty,$f:expr)=>{$f};($m:ty,$f:expr,$($ff:expr),*)=>{<$m as Magma>::operate(&($f),&monoid_fold!($m,$($ff),*))};}#[macro_export]macro_rules!define_monoid{($Name:ident,$t:ty,|$x:ident,$y:ident|$op:expr,$unit:expr)=>{struct$Name;impl Magma for$Name{type T=$t;fn operate($x:&Self::T,$y:&Self::T)->Self::T{$op}}impl Unital for$Name{fn unit()->Self::T{$unit}}impl Associative for$Name{}};}} // codesnip-guard: array #[cfg_attr(any(),rustfmt::skip)]mod array{#[macro_export]macro_rules!array{[@inner$data:ident=[$init:expr;$len:expr]]=>{{use::std::mem::{ManuallyDrop,MaybeUninit};let mut$data:[MaybeUninit<_>;$len]=unsafe{MaybeUninit::uninit().assume_init()};$init;#[repr(C)]union __Transmuter{src:ManuallyDrop<[MaybeUninit;N]>,dst:ManuallyDrop<[T;N]>,}ManuallyDrop::into_inner(unsafe{__Transmuter{src:ManuallyDrop::new($data)}.dst})}};[||$e:expr;$len:expr]=>{$crate::array![@inner data=[data.iter_mut().for_each(|item|*item=MaybeUninit::new($e));$len]]};[|$i:pat_param|$e:expr;$len:expr]=>{$crate::array![@inner data=[data.iter_mut().enumerate().for_each(|($i,item)|*item=MaybeUninit::new($e));$len]]};[$e:expr;$len:expr]=>{{let e=$e;$crate::array![||Clone::clone(&e);$len]}};}} // codesnip-guard: bounded #[cfg_attr(any(),rustfmt::skip)]pub use self::bounded::Bounded;#[cfg_attr(any(),rustfmt::skip)]mod bounded{#[doc=" Trait for max/min bounds"]pub trait Bounded:Sized+PartialOrd{fn maximum()->Self;fn minimum()->Self;fn is_maximum(&self)->bool{self==&Self::maximum()}fn is_minimum(&self)->bool{self==&Self::minimum()}fn set_maximum(&mut self){*self=Self::maximum()}fn set_minimum(&mut self){*self=Self::minimum()}}macro_rules!impl_bounded_num{($($t:ident)*)=>{$(impl Bounded for$t{fn maximum()->Self{$t::MAX}fn minimum()->Self{$t::MIN}})*};}impl_bounded_num!(u8 u16 u32 u64 u128 usize i8 i16 i32 i64 i128 isize f32 f64);macro_rules!impl_bounded_tuple{(@impl$($T:ident)*)=>{impl<$($T:Bounded),*>Bounded for($($T,)*){fn maximum()->Self{($(<$T as Bounded>::maximum(),)*)}fn minimum()->Self{($(<$T as Bounded>::minimum(),)*)}}};(@inner$($T:ident)*,)=>{impl_bounded_tuple!(@impl$($T)*);};(@inner$($T:ident)*,$U:ident$($Rest:ident)*)=>{impl_bounded_tuple!(@impl$($T)*);impl_bounded_tuple!(@inner$($T)*$U,$($Rest)*);};($T:ident$($Rest:ident)*)=>{impl_bounded_tuple!(@inner$T,$($Rest)*);};}impl_bounded_tuple!(A B C D E F G H I J);impl Bounded for(){fn maximum()->Self{}fn minimum()->Self{}}impl Bounded for bool{fn maximum()->Self{true}fn minimum()->Self{false}}implBounded for Optionwhere T:Bounded{fn maximum()->Self{Some(::maximum())}fn minimum()->Self{None}}implBounded for std::cmp::Reversewhere T:Bounded{fn maximum()->Self{std::cmp::Reverse(::minimum())}fn minimum()->Self{std::cmp::Reverse(::maximum())}}} // codesnip-guard: discrete_steps #[cfg_attr(any(),rustfmt::skip)]pub use self::discrete_steps::{DiscreteSteps,RangeBoundsExt};#[cfg_attr(any(),rustfmt::skip)]mod discrete_steps{use super::Bounded;use std::{convert::TryFrom,ops::{Bound,Range,RangeBounds,RangeInclusive}};pub trait DiscreteSteps:Clone{fn delta()->Delta;fn steps_between(start:&Self,end:&Self)->Option;fn forward_checked(start:Self,delta:Delta)->Option;fn backward_checked(start:Self,delta:Delta)->Option;fn forward(start:Self,delta:Delta)->Self{Self::forward_checked(start,delta).expect("overflow in `DiscreteSteps::forward`")}fn backward(start:Self,delta:Delta)->Self{Self::backward_checked(start,delta).expect("overflow in `DiscreteSteps::backward`")}fn forward_delta_checked(start:Self)->Option{Self::forward_checked(start,Self::delta())}fn backward_delta_checked(start:Self)->Option{Self::backward_checked(start,Self::delta())}fn forward_delta(start:Self)->Self{Self::forward(start,Self::delta())}fn backward_delta(start:Self)->Self{Self::backward(start,Self::delta())}}macro_rules!impl_discrete_steps_integer{(@common$u_source:ident)=>{fn delta()->$u_source{1}fn forward(start:Self,delta:$u_source)->Self{assert!(Self::forward_checked(start,delta).is_some(),"attempt to add with overflow");start.wrapping_add(delta as Self)}fn backward(start:Self,delta:$u_source)->Self{assert!(Self::backward_checked(start,delta).is_some(),"attempt to subtract with overflow");start.wrapping_sub(delta as Self)}};($u_source:ident$i_source:ident;$($u_narrower:ident$i_narrower:ident),*;$($u_wider:ident$i_wider:ident),*)=>{$(impl DiscreteSteps<$u_source>for$u_narrower{impl_discrete_steps_integer!(@common$u_source);fn steps_between(start:&Self,end:&Self)->Option<$u_source>{if*start<=*end{$u_source::try_from(*end-*start).ok()}else{None}}fn forward_checked(start:Self,delta:$u_source)->Option{Self::try_from(delta).ok().and_then(|delta|start.checked_add(delta))}fn backward_checked(start:Self,delta:$u_source)->Option{Self::try_from(delta).ok().and_then(|delta|start.checked_sub(delta))}}impl DiscreteSteps<$u_source>for$i_narrower{impl_discrete_steps_integer!(@common$u_source);fn steps_between(start:&Self,end:&Self)->Option<$u_source>{if*start<=*end{$u_source::try_from(end.abs_diff(*start)).ok()}else{None}}fn forward_checked(start:Self,delta:$u_source)->Option{$u_narrower::try_from(delta).ok().and_then(|delta|{let wrapped=start.wrapping_add(delta as Self);if wrapped>=start{Some(wrapped)}else{None}})}fn backward_checked(start:Self,delta:$u_source)->Option{$u_narrower::try_from(delta).ok().and_then(|delta|{let wrapped=start.wrapping_sub(delta as Self);if wrapped<=start{Some(wrapped)}else{None}})}})*$(impl DiscreteSteps<$u_source>for$u_wider{impl_discrete_steps_integer!(@common$u_source);fn steps_between(start:&Self,end:&Self)->Option<$u_source>{if*start<=*end{$u_source::try_from(*end-*start).ok()}else{None}}fn forward_checked(start:Self,delta:$u_source)->Option{start.checked_add(delta as Self)}fn backward_checked(start:Self,delta:$u_source)->Option{start.checked_sub(delta as Self)}}impl DiscreteSteps<$u_source>for$i_wider{impl_discrete_steps_integer!(@common$u_source);fn steps_between(start:&Self,end:&Self)->Option<$u_source>{if*start<=*end{end.checked_sub(*start).and_then(|result|$u_source::try_from(result).ok())}else{None}}fn forward_checked(start:Self,delta:$u_source)->Option{start.checked_add(delta as Self)}fn backward_checked(start:Self,delta:$u_source)->Option{start.checked_sub(delta as Self)}})*};}impl_discrete_steps_integer!(u16 i16;u8 i8,u16 i16,usize isize;u32 i32,u64 i64,u128 i128);impl_discrete_steps_integer!(u32 i32;u8 i8,u16 i16,u32 i32,usize isize;u64 i64,u128 i128);impl_discrete_steps_integer!(u64 i64;u8 i8,u16 i16,u32 i32,u64 i64,usize isize;u128 i128);impl_discrete_steps_integer!(u128 i128;u8 i8,u16 i16,u32 i32,u64 i64,u128 i128,usize isize;);impl_discrete_steps_integer!(usize isize;u8 i8,u16 i16,u32 i32,u64 i64,usize isize;u128 i128);pub trait RangeBoundsExt{fn start_bound_included_checked(&self)->Option;fn start_bound_excluded_checked(&self)->Option;fn end_bound_included_checked(&self)->Option;fn end_bound_excluded_checked(&self)->Option;fn start_bound_included(&self)->T;fn start_bound_excluded(&self)->T;fn end_bound_included(&self)->T;fn end_bound_excluded(&self)->T;fn start_bound_included_bounded(&self,lb:T)->Optionwhere T:Ord;fn start_bound_excluded_bounded(&self,lb:T)->Optionwhere T:Ord;fn end_bound_included_bounded(&self,ub:T)->Optionwhere T:Ord;fn end_bound_excluded_bounded(&self,ub:T)->Optionwhere T:Ord;fn to_range_checked(&self)->Option>{match(self.start_bound_included_checked(),self.end_bound_excluded_checked()){(Some(start),Some(end))=>Some(start..end),_=>None,}}fn to_range(&self)->Range{self.start_bound_included()..self.end_bound_excluded()}fn to_range_bounded(&self,min:T,max:T)->Option>where T:Ord{Some(self.start_bound_included_bounded(min)?..self.end_bound_excluded_bounded(max)?)}fn to_range_inclusive_checked(&self)->Option>{match(self.start_bound_included_checked(),self.end_bound_included_checked()){(Some(start),Some(end))=>Some(start..=end),_=>None,}}fn to_range_inclusive(&self)->RangeInclusive{self.start_bound_included()..=self.end_bound_included()}fn to_range_inclusive_bounded(&self,min:T,max:T)->Option>where T:Ord{Some(self.start_bound_included_bounded(min)?..=self.end_bound_included_bounded(max)?)}}macro_rules!impl_range_bounds_ext{($($source:ident=>$($target:ident)+);*$(;)?)=>{$($(implRangeBoundsExt<$target>for R where R:RangeBounds<$target>,{fn start_bound_included_checked(&self)->Option<$target>{match self.start_bound(){Bound::Included(x)=>Some(*x),Bound::Excluded(x)=>DiscreteSteps::<$source>::forward_delta_checked(*x),Bound::Unbounded=>Some(Bounded::minimum()),}}fn start_bound_excluded_checked(&self)->Option<$target>{match self.start_bound(){Bound::Included(x)=>DiscreteSteps::<$source>::backward_delta_checked(*x),Bound::Excluded(x)=>Some(*x),Bound::Unbounded=>None,}}fn end_bound_included_checked(&self)->Option<$target>{match self.end_bound(){Bound::Included(x)=>Some(*x),Bound::Excluded(x)=>DiscreteSteps::<$source>::backward_delta_checked(*x),Bound::Unbounded=>Some(Bounded::maximum()),}}fn end_bound_excluded_checked(&self)->Option<$target>{match self.end_bound(){Bound::Included(x)=>DiscreteSteps::<$source>::forward_delta_checked(*x),Bound::Excluded(x)=>Some(*x),Bound::Unbounded=>None,}}fn start_bound_included(&self)->$target{match self.start_bound(){Bound::Included(x)=>*x,Bound::Excluded(x)=>DiscreteSteps::<$source>::forward_delta(*x),Bound::Unbounded=>Bounded::minimum(),}}fn start_bound_excluded(&self)->$target{match self.start_bound(){Bound::Included(x)=>DiscreteSteps::<$source>::backward_delta(*x),Bound::Excluded(x)=>*x,Bound::Unbounded=>DiscreteSteps::<$source>::backward_delta(Bounded::minimum()),}}fn end_bound_included(&self)->$target{match self.end_bound(){Bound::Included(x)=>*x,Bound::Excluded(x)=>DiscreteSteps::<$source>::backward_delta(*x),Bound::Unbounded=>Bounded::maximum(),}}fn end_bound_excluded(&self)->$target{match self.end_bound(){Bound::Included(x)=>DiscreteSteps::<$source>::forward_delta(*x),Bound::Excluded(x)=>*x,Bound::Unbounded=>DiscreteSteps::<$source>::forward_delta(Bounded::maximum()),}}fn start_bound_included_bounded(&self,lb:$target)->Option<$target>where$target:Ord{match self.start_bound(){Bound::Included(x)=>Some(*x).filter(|&x|lb<=x),Bound::Excluded(x)=>DiscreteSteps::<$source>::forward_delta_checked(*x).filter(|&x|lb<=x),Bound::Unbounded=>Some(lb),}}fn start_bound_excluded_bounded(&self,lb:$target)->Option<$target>where$target:Ord{match self.start_bound(){Bound::Included(x)=>DiscreteSteps::<$source>::backward_delta_checked(*x).filter(|&x|lb<=x),Bound::Excluded(x)=>Some(*x).filter(|&x|lb<=x),Bound::Unbounded=>Some(lb),}}fn end_bound_included_bounded(&self,ub:$target)->Option<$target>where$target:Ord{match self.end_bound(){Bound::Included(x)=>Some(*x).filter(|&x|x<=ub),Bound::Excluded(x)=>DiscreteSteps::<$source>::backward_delta_checked(*x).filter(|&x|x<=ub),Bound::Unbounded=>Some(ub),}}fn end_bound_excluded_bounded(&self,ub:$target)->Option<$target>where$target:Ord{match self.end_bound(){Bound::Included(x)=>DiscreteSteps::<$source>::forward_delta_checked(*x).filter(|&x|x<=ub),Bound::Excluded(x)=>Some(*x).filter(|&x|x<=ub),Bound::Unbounded=>Some(ub),}}})+)*};}impl_range_bounds_ext!(u16=>u8 i8 u16 i16;u32=>u32 i32;u64=>u64 i64;u128=>u128 i128;usize=>isize usize;);} // codesnip-guard: zero_one #[cfg_attr(any(),rustfmt::skip)]pub use self::zero_one::{One,Zero};#[cfg_attr(any(),rustfmt::skip)]mod zero_one{pub trait Zero:Sized{fn zero()->Self;#[inline]fn is_zero(&self)->bool where Self:PartialEq{self==&Self::zero()}#[inline]fn set_zero(&mut self){*self=Self::zero();}}pub trait One:Sized{fn one()->Self;#[inline]fn is_one(&self)->bool where Self:PartialEq{self==&Self::one()}#[inline]fn set_one(&mut self){*self=Self::one();}}macro_rules!impl_zero_one{($({$(<$T:ident:$Bound:ident>)?$Trait:ident$method:ident$($t:ty)*,$e:expr})*)=>{$(impl_zero_one!(@impl[$(<$T:$Bound>)?]$Trait$method[$($t)*],$e);)*};(@impl[<$T:ident:$Bound:ident>]$Trait:ident$method:ident[$($t:ty)*],$e:expr)=>{$(impl<$T:$Bound>$Trait for$t{fn$method()->Self{$e}})*};(@impl[]$Trait:ident$method:ident[$($t:ty)*],$e:expr)=>{$(impl$Trait for$t{fn$method()->Self{$e}})*};}impl_zero_one!({Zero zero u8 u16 u32 u64 usize i8 i16 i32 i64 isize u128 i128,0}{Zero zero f32 f64,0.}{One one u8 u16 u32 u64 usize i8 i16 i32 i64 isize u128 i128,1}{One one f32 f64,1.}{Zero zero std::num::Wrapping,Self(T::zero())}{One one std::num::Wrapping,Self(T::one())});}