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

difftreelog

source

crates/jrsonnet-evaluator/src/arr/mod.rs5.7 KiBsourcehistory
1use std::{2	any::Any,3	fmt::{self},4	num::NonZeroU32, rc::Rc,5};67use jrsonnet_gcmodule::{cc_dyn, Cc};8use jrsonnet_interner::IBytes;9use jrsonnet_parser::{Expr, Spanned};1011use crate::{function::FuncVal, Context, Result, Thunk, Val};1213mod spec;14pub use spec::{ArrayLike, *};1516cc_dyn!(17	#[doc = "Represents a Jsonnet array value."]18	#[derive(Clone)]19	ArrValue,20	ArrayLike,21	pub fn new() {...}22);23impl fmt::Debug for ArrValue {24	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {25		self.0.fmt(f)26	}27}2829pub trait ArrayLikeIter<T>: Iterator<Item = T> + DoubleEndedIterator + ExactSizeIterator {}30impl<I, T> ArrayLikeIter<T> for I where31	I: Iterator<Item = T> + DoubleEndedIterator + ExactSizeIterator32{33}3435impl ArrValue {36	pub fn empty() -> Self {37		Self::new(RangeArray::empty())38	}3940	pub fn expr(ctx: Context, exprs: Rc<Vec<Spanned<Expr>>>) -> Self {41		Self::new(ExprArray::new(ctx, exprs))42	}4344	pub fn lazy(thunks: Vec<Thunk<Val>>) -> Self {45		Self::new(LazyArray(thunks))46	}4748	pub fn eager(values: Vec<Val>) -> Self {49		Self::new(EagerArray(values))50	}5152	pub fn repeated(data: Self, repeats: usize) -> Option<Self> {53		Some(Self::new(RepeatedArray::new(data, repeats)?))54	}5556	pub fn bytes(bytes: IBytes) -> Self {57		Self::new(BytesArray(bytes))58	}59	pub fn chars(chars: impl Iterator<Item = char>) -> Self {60		Self::new(CharArray(chars.collect()))61	}6263	#[must_use]64	pub fn map(self, mapper: FuncVal) -> Self {65		Self::new(<MappedArray<false>>::new(self, mapper))66	}6768	#[must_use]69	pub fn map_with_index(self, mapper: FuncVal) -> Self {70		Self::new(<MappedArray<true>>::new(self, mapper))71	}7273	pub fn filter(self, filter: impl Fn(&Val) -> Result<bool>) -> Result<Self> {74		// TODO: ArrValue::Picked(inner, indexes) for large arrays75		let mut out = Vec::new();76		for i in self.iter() {77			let i = i?;78			if filter(&i)? {79				out.push(i);80			};81		}82		Ok(Self::eager(out))83	}8485	pub fn extended(a: Self, b: Self) -> Self {86		// TODO: benchmark for an optimal value, currently just a arbitrary choice87		const ARR_EXTEND_THRESHOLD: usize = 100;8889		if a.is_empty() {90			b91		} else if b.is_empty() {92			a93		} else if a.len() + b.len() > ARR_EXTEND_THRESHOLD {94			Self::new(ExtendedArray::new(a, b))95		} else if let (Some(a), Some(b)) = (a.iter_cheap(), b.iter_cheap()) {96			let mut out = Vec::with_capacity(a.len() + b.len());97			out.extend(a);98			out.extend(b);99			Self::eager(out)100		} else {101			let mut out = Vec::with_capacity(a.len() + b.len());102			out.extend(a.iter_lazy());103			out.extend(b.iter_lazy());104			Self::lazy(out)105		}106	}107108	pub fn range_exclusive(a: i32, b: i32) -> Self {109		Self::new(RangeArray::new_exclusive(a, b))110	}111	pub fn range_inclusive(a: i32, b: i32) -> Self {112		Self::new(RangeArray::new_inclusive(a, b))113	}114115	#[must_use]116	pub fn slice(self, index: Option<i32>, end: Option<i32>, step: Option<NonZeroU32>) -> Self {117		let get_idx = |pos: Option<i32>, len: usize, default| match pos {118			Some(v) if v < 0 => len.saturating_sub((-v) as usize),119			Some(v) => (v as usize).min(len),120			None => default,121		};122		let index = get_idx(index, self.len(), 0);123		let end = get_idx(end, self.len(), self.len());124		let step = step.unwrap_or_else(|| NonZeroU32::new(1).expect("1 != 0"));125126		if index >= end {127			return Self::empty();128		}129130		Self::new(SliceArray {131			inner: self,132			from: index as u32,133			to: end as u32,134			step: step.get(),135		})136	}137138	/// Array length.139	pub fn len(&self) -> usize {140		self.0.len()141	}142143	/// Is array contains no elements?144	pub fn is_empty(&self) -> bool {145		self.0.is_empty()146	}147148	/// Get array element by index, evaluating it, if it is lazy.149	///150	/// Returns `None` on out-of-bounds condition.151	pub fn get(&self, index: usize) -> Result<Option<Val>> {152		self.0.get(index)153	}154155	/// Returns None if get is either non cheap, or out of bounds156	/// Note that non-cheap access includes errorable values157	///158	/// Prefer it to `get_lazy`, but use `get` when you can.159	fn get_cheap(&self, index: usize) -> Option<Val> {160		self.0.get_cheap(index)161	}162163	/// Get array element by index, without evaluation.164	///165	/// Returns `None` on out-of-bounds condition.166	pub fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {167		self.0.get_lazy(index)168	}169170	pub fn iter(&self) -> impl ArrayLikeIter<Result<Val>> + '_ {171		(0..self.len()).map(|i| self.get(i).transpose().expect("length checked"))172	}173174	/// Iterate over elements, returning lazy values.175	pub fn iter_lazy(&self) -> impl ArrayLikeIter<Thunk<Val>> + '_ {176		(0..self.len()).map(|i| self.get_lazy(i).expect("length checked"))177	}178179	/// Prefer it over `iter_lazy`, but do not use it where `iter` will do.180	pub fn iter_cheap(&self) -> Option<impl ArrayLikeIter<Val> + '_> {181		if self.is_cheap() {182			Some((0..self.len()).map(|i| self.get_cheap(i).expect("length and is_cheap checked")))183		} else {184			None185		}186	}187188	/// Return a reversed view on current array.189	#[must_use]190	pub fn reversed(self) -> Self {191		Self::new(ReverseArray(self))192	}193194	pub fn ptr_eq(a: &Self, b: &Self) -> bool {195		Cc::ptr_eq(&a.0, &b.0)196	}197198	/// Is this vec supports `.get_cheap()?`199	pub fn is_cheap(&self) -> bool {200		self.0.is_cheap()201	}202203	pub fn as_any(&self) -> &dyn Any {204		&self.0205	}206}207impl From<Vec<Val>> for ArrValue {208	fn from(value: Vec<Val>) -> Self {209		Self::eager(value)210	}211}212impl From<Vec<Thunk<Val>>> for ArrValue {213	fn from(value: Vec<Thunk<Val>>) -> Self {214		Self::lazy(value)215	}216}217impl FromIterator<Val> for ArrValue {218	fn from_iter<T: IntoIterator<Item = Val>>(iter: T) -> Self {219		Self::eager(iter.into_iter().collect())220	}221}222impl ArrayLike for ArrValue {223	fn len(&self) -> usize {224		self.0.len()225	}226227	fn get(&self, index: usize) -> Result<Option<Val>> {228		self.0.get(index)229	}230231	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {232		self.0.get_lazy(index)233	}234235	fn get_cheap(&self, index: usize) -> Option<Val> {236		self.0.get_cheap(index)237	}238239	fn is_cheap(&self) -> bool {240		self.0.is_cheap()241	}242}