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

difftreelog

source

crates/jrsonnet-evaluator/src/arr/mod.rs5.6 KiBsourcehistory
1use std::{2	any::Any,3	num::{NonZeroU32, NonZeroUsize},4};56use jrsonnet_gcmodule::{Cc, Trace};7use jrsonnet_interner::IBytes;8use jrsonnet_parser::LocExpr;910use crate::{function::FuncVal, gc::TraceBox, tb, Context, Result, Thunk, Val};1112mod spec;13pub use spec::{ArrayLike, *};1415/// Represents a Jsonnet array value.16#[derive(Debug, Clone, Trace)]17// may contrain other ArrValue18#[trace(tracking(force))]19pub struct ArrValue(Cc<TraceBox<dyn ArrayLike>>);2021pub trait ArrayLikeIter<T>: Iterator<Item = T> + DoubleEndedIterator + ExactSizeIterator {}22impl<I, T> ArrayLikeIter<T> for I where23	I: Iterator<Item = T> + DoubleEndedIterator + ExactSizeIterator24{25}2627impl ArrValue {28	pub fn new(v: impl ArrayLike) -> Self {29		Self(Cc::new(tb!(v)))30	}31	pub fn empty() -> Self {32		Self::new(RangeArray::empty())33	}3435	pub fn expr(ctx: Context, exprs: impl IntoIterator<Item = LocExpr>) -> Self {36		Self::new(ExprArray::new(ctx, exprs))37	}3839	pub fn lazy(thunks: Vec<Thunk<Val>>) -> Self {40		Self::new(LazyArray(thunks))41	}4243	pub fn eager(values: Vec<Val>) -> Self {44		Self::new(EagerArray(values))45	}4647	pub fn repeated(data: Self, repeats: usize) -> Option<Self> {48		Some(Self::new(RepeatedArray::new(data, repeats)?))49	}5051	pub fn bytes(bytes: IBytes) -> Self {52		Self::new(BytesArray(bytes))53	}54	pub fn chars(chars: impl Iterator<Item = char>) -> Self {55		Self::new(CharArray(chars.collect()))56	}5758	#[must_use]59	pub fn map(self, mapper: FuncVal) -> Self {60		Self::new(MappedArray::new(self, mapper))61	}6263	pub fn filter(self, filter: impl Fn(&Val) -> Result<bool>) -> Result<Self> {64		// TODO: ArrValue::Picked(inner, indexes) for large arrays65		let mut out = Vec::new();66		for i in self.iter() {67			let i = i?;68			if filter(&i)? {69				out.push(i);70			};71		}72		Ok(Self::eager(out))73	}7475	pub fn extended(a: Self, b: Self) -> Self {76		// TODO: benchmark for an optimal value, currently just a arbitrary choice77		const ARR_EXTEND_THRESHOLD: usize = 100;7879		if a.is_empty() {80			b81		} else if b.is_empty() {82			a83		} else if a.len() + b.len() > ARR_EXTEND_THRESHOLD {84			Self::new(ExtendedArray::new(a, b))85		} else if let (Some(a), Some(b)) = (a.iter_cheap(), b.iter_cheap()) {86			let mut out = Vec::with_capacity(a.len() + b.len());87			out.extend(a);88			out.extend(b);89			Self::eager(out)90		} else {91			let mut out = Vec::with_capacity(a.len() + b.len());92			out.extend(a.iter_lazy());93			out.extend(b.iter_lazy());94			Self::lazy(out)95		}96	}9798	pub fn range_exclusive(a: i32, b: i32) -> Self {99		Self::new(RangeArray::new_exclusive(a, b))100	}101	pub fn range_inclusive(a: i32, b: i32) -> Self {102		Self::new(RangeArray::new_inclusive(a, b))103	}104105	/// # Panics106	/// If step == 0107	#[must_use]108	pub fn slice(self, index: Option<i32>, end: Option<i32>, step: Option<NonZeroU32>) -> Self {109		let get_idx = |pos: Option<i32>, len: usize, default| match pos {110			Some(v) if v < 0 => len.saturating_sub((-v) as usize),111			Some(v) => (v as usize).min(len),112			None => default,113		};114		let index = get_idx(index, self.len(), 0);115		let end = get_idx(end, self.len(), self.len());116		let step = step.unwrap_or_else(|| NonZeroU32::new(1).expect("1 != 0"));117118		if index >= end {119			return Self::empty();120		}121122		Self::new(SliceArray {123			inner: self,124			from: index as u32,125			to: end as u32,126			step: step.get(),127		})128	}129130	/// Array length.131	pub fn len(&self) -> usize {132		self.0.len()133	}134135	/// Is array contains no elements?136	pub fn is_empty(&self) -> bool {137		self.0.is_empty()138	}139140	/// Get array element by index, evaluating it, if it is lazy.141	///142	/// Returns `None` on out-of-bounds condition.143	pub fn get(&self, index: usize) -> Result<Option<Val>> {144		self.0.get(index)145	}146147	/// Returns None if get is either non cheap, or out of bounds148	fn get_cheap(&self, index: usize) -> Option<Val> {149		self.0.get_cheap(index)150	}151152	/// Get array element by index, without evaluation.153	///154	/// Returns `None` on out-of-bounds condition.155	pub fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {156		self.0.get_lazy(index)157	}158159	pub fn iter(&self) -> impl ArrayLikeIter<Result<Val>> + '_ {160		(0..self.len()).map(|i| self.get(i).transpose().expect("length checked"))161	}162163	/// Iterate over elements, returning lazy values.164	pub fn iter_lazy(&self) -> impl ArrayLikeIter<Thunk<Val>> + '_ {165		(0..self.len()).map(|i| self.get_lazy(i).expect("length checked"))166	}167168	pub fn iter_cheap(&self) -> Option<impl ArrayLikeIter<Val> + '_> {169		if self.is_cheap() {170			Some((0..self.len()).map(|i| self.get_cheap(i).expect("length and is_cheap checked")))171		} else {172			None173		}174	}175176	/// Return a reversed view on current array.177	#[must_use]178	pub fn reversed(self) -> Self {179		Self::new(ReverseArray(self))180	}181182	pub fn ptr_eq(a: &Self, b: &Self) -> bool {183		Cc::ptr_eq(&a.0, &b.0)184	}185186	/// Is this vec supports `.get_cheap()?`187	pub fn is_cheap(&self) -> bool {188		self.0.is_cheap()189	}190191	pub fn as_any(&self) -> &dyn Any {192		&self.0193	}194}195impl From<Vec<Val>> for ArrValue {196	fn from(value: Vec<Val>) -> Self {197		Self::eager(value)198	}199}200impl From<Vec<Thunk<Val>>> for ArrValue {201	fn from(value: Vec<Thunk<Val>>) -> Self {202		Self::lazy(value)203	}204}205impl FromIterator<Val> for ArrValue {206	fn from_iter<T: IntoIterator<Item = Val>>(iter: T) -> Self {207		Self::eager(iter.into_iter().collect())208	}209}210impl ArrayLike for ArrValue {211	fn len(&self) -> usize {212		self.0.len()213	}214215	fn get(&self, index: usize) -> Result<Option<Val>> {216		self.0.get(index)217	}218219	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {220		self.0.get_lazy(index)221	}222223	fn get_cheap(&self, index: usize) -> Option<Val> {224		self.0.get_cheap(index)225	}226227	fn is_cheap(&self) -> bool {228		self.0.is_cheap()229	}230}231232#[cfg(target_pointer_width = "64")]233static_assertions::assert_eq_size!(ArrValue, [u8; 8]);