git.delta.rocks / jrsonnet / refs/commits / f319c3545168

difftreelog

source

crates/jrsonnet-evaluator/src/arr/mod.rs5.3 KiBsourcehistory
1use std::any::Any;23use jrsonnet_gcmodule::{Cc, Trace};4use jrsonnet_interner::IBytes;5use jrsonnet_parser::LocExpr;67use crate::{function::FuncVal, gc::TraceBox, tb, Context, Result, Thunk, Val};89mod spec;10pub use spec::{ArrayLike, *};1112/// Represents a Jsonnet array value.13#[derive(Debug, Clone, Trace)]14// may contrain other ArrValue15#[trace(tracking(force))]16pub struct ArrValue(Cc<TraceBox<dyn ArrayLike>>);1718pub trait ArrayLikeIter<T>: Iterator<Item = T> + DoubleEndedIterator + ExactSizeIterator {}19impl<I, T> ArrayLikeIter<T> for I where20	I: Iterator<Item = T> + DoubleEndedIterator + ExactSizeIterator21{22}2324impl ArrValue {25	pub fn new(v: impl ArrayLike) -> Self {26		Self(Cc::new(tb!(v)))27	}28	pub fn empty() -> Self {29		Self::new(RangeArray::empty())30	}3132	pub fn expr(ctx: Context, exprs: impl IntoIterator<Item = LocExpr>) -> Self {33		Self::new(ExprArray::new(ctx, exprs))34	}3536	pub fn lazy(thunks: Vec<Thunk<Val>>) -> Self {37		Self::new(LazyArray(thunks))38	}3940	pub fn eager(values: Vec<Val>) -> Self {41		Self::new(EagerArray(values))42	}4344	pub fn repeated(data: Self, repeats: usize) -> Option<Self> {45		Some(Self::new(RepeatedArray::new(data, repeats)?))46	}4748	pub fn bytes(bytes: IBytes) -> Self {49		Self::new(BytesArray(bytes))50	}51	pub fn chars(chars: impl Iterator<Item = char>) -> Self {52		Self::new(CharArray(chars.collect()))53	}5455	#[must_use]56	pub fn map(self, mapper: FuncVal) -> Self {57		Self::new(MappedArray::new(self, mapper))58	}5960	pub fn filter(self, filter: impl Fn(&Val) -> Result<bool>) -> Result<Self> {61		// TODO: ArrValue::Picked(inner, indexes) for large arrays62		let mut out = Vec::new();63		for i in self.iter() {64			let i = i?;65			if filter(&i)? {66				out.push(i);67			};68		}69		Ok(Self::eager(out))70	}7172	pub fn extended(a: Self, b: Self) -> Self {73		// TODO: benchmark for an optimal value, currently just a arbitrary choice74		const ARR_EXTEND_THRESHOLD: usize = 100;7576		if a.is_empty() {77			b78		} else if b.is_empty() {79			a80		} else if a.len() + b.len() > ARR_EXTEND_THRESHOLD {81			Self::new(ExtendedArray::new(a, b))82		} else if let (Some(a), Some(b)) = (a.iter_cheap(), b.iter_cheap()) {83			let mut out = Vec::with_capacity(a.len() + b.len());84			out.extend(a);85			out.extend(b);86			Self::eager(out)87		} else {88			let mut out = Vec::with_capacity(a.len() + b.len());89			out.extend(a.iter_lazy());90			out.extend(b.iter_lazy());91			Self::lazy(out)92		}93	}9495	pub fn range_exclusive(a: i32, b: i32) -> Self {96		Self::new(RangeArray::new_exclusive(a, b))97	}98	pub fn range_inclusive(a: i32, b: i32) -> Self {99		Self::new(RangeArray::new_inclusive(a, b))100	}101102	#[must_use]103	pub fn slice(104		self,105		from: Option<usize>,106		to: Option<usize>,107		step: Option<usize>,108	) -> Option<Self> {109		let len = self.len();110		let from = from.unwrap_or(0);111		let to = to.unwrap_or(len).min(len);112		let step = step.unwrap_or(1);113114		if from >= to || step == 0 {115			return None;116		}117118		Some(Self::new(SliceArray {119			inner: self,120			from: from as u32,121			to: to as u32,122			step: step as u32,123		}))124	}125126	/// Array length.127	pub fn len(&self) -> usize {128		self.0.len()129	}130131	/// Is array contains no elements?132	pub fn is_empty(&self) -> bool {133		self.0.is_empty()134	}135136	/// Get array element by index, evaluating it, if it is lazy.137	///138	/// Returns `None` on out-of-bounds condition.139	pub fn get(&self, index: usize) -> Result<Option<Val>> {140		self.0.get(index)141	}142143	/// Returns None if get is either non cheap, or out of bounds144	fn get_cheap(&self, index: usize) -> Option<Val> {145		self.0.get_cheap(index)146	}147148	/// Get array element by index, without evaluation.149	///150	/// Returns `None` on out-of-bounds condition.151	pub fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {152		self.0.get_lazy(index)153	}154155	pub fn iter(&self) -> impl ArrayLikeIter<Result<Val>> + '_ {156		(0..self.len()).map(|i| self.get(i).transpose().expect("length checked"))157	}158159	/// Iterate over elements, returning lazy values.160	pub fn iter_lazy(&self) -> impl ArrayLikeIter<Thunk<Val>> + '_ {161		(0..self.len()).map(|i| self.get_lazy(i).expect("length checked"))162	}163164	pub fn iter_cheap(&self) -> Option<impl ArrayLikeIter<Val> + '_> {165		if self.is_cheap() {166			Some((0..self.len()).map(|i| self.get_cheap(i).expect("length and is_cheap checked")))167		} else {168			None169		}170	}171172	/// Return a reversed view on current array.173	#[must_use]174	pub fn reversed(self) -> Self {175		Self::new(ReverseArray(self))176	}177178	pub fn ptr_eq(a: &Self, b: &Self) -> bool {179		Cc::ptr_eq(&a.0, &b.0)180	}181182	/// Is this vec supports `.get_cheap()?`183	pub fn is_cheap(&self) -> bool {184		self.0.is_cheap()185	}186187	pub fn as_any(&self) -> &dyn Any {188		&self.0189	}190}191impl From<Vec<Val>> for ArrValue {192	fn from(value: Vec<Val>) -> Self {193		Self::eager(value)194	}195}196impl From<Vec<Thunk<Val>>> for ArrValue {197	fn from(value: Vec<Thunk<Val>>) -> Self {198		Self::lazy(value)199	}200}201impl FromIterator<Val> for ArrValue {202	fn from_iter<T: IntoIterator<Item = Val>>(iter: T) -> Self {203		Self::eager(iter.into_iter().collect())204	}205}206impl ArrayLike for ArrValue {207	fn len(&self) -> usize {208		self.0.len()209	}210211	fn get(&self, index: usize) -> Result<Option<Val>> {212		self.0.get(index)213	}214215	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {216		self.0.get_lazy(index)217	}218219	fn get_cheap(&self, index: usize) -> Option<Val> {220		self.0.get_cheap(index)221	}222223	fn is_cheap(&self) -> bool {224		self.0.is_cheap()225	}226}227228#[cfg(target_pointer_width = "64")]229static_assertions::assert_eq_size!(ArrValue, [u8; 8]);