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

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;11pub(crate) use spec::*;1213/// Represents a Jsonnet array value.14#[derive(Debug, Clone, Trace)]15// may contrain other ArrValue16#[trace(tracking(force))]17pub struct ArrValue(Cc<TraceBox<dyn ArrayLike>>);1819pub trait ArrayLikeIter<T>: Iterator<Item = T> + DoubleEndedIterator + ExactSizeIterator {}20impl<I, T> ArrayLikeIter<T> for I where21	I: Iterator<Item = T> + DoubleEndedIterator + ExactSizeIterator22{23}2425impl ArrValue {26	pub fn new(v: impl ArrayLike) -> Self {27		Self(Cc::new(tb!(v)))28	}29	pub fn empty() -> Self {30		Self::new(RangeArray::empty())31	}3233	pub fn expr(ctx: Context, exprs: impl IntoIterator<Item = LocExpr>) -> Self {34		Self::new(ExprArray::new(ctx, exprs))35	}3637	pub fn lazy(thunks: Vec<Thunk<Val>>) -> Self {38		Self::new(LazyArray(thunks))39	}4041	pub fn eager(values: Vec<Val>) -> Self {42		Self::new(EagerArray(values))43	}4445	pub fn repeated(data: ArrValue, repeats: usize) -> Option<Self> {46		Some(Self::new(RepeatedArray::new(data, repeats)?))47	}4849	pub fn bytes(bytes: IBytes) -> Self {50		Self::new(BytesArray(bytes))51	}52	pub fn chars(chars: impl Iterator<Item = char>) -> Self {53		Self::new(CharArray(chars.collect()))54	}5556	#[must_use]57	pub fn map(self, mapper: FuncVal) -> Self {58		Self::new(MappedArray::new(self, mapper))59	}6061	pub fn filter(self, filter: impl Fn(&Val) -> Result<bool>) -> Result<Self> {62		// TODO: ArrValue::Picked(inner, indexes) for large arrays63		let mut out = Vec::new();64		for i in self.iter() {65			let i = i?;66			if filter(&i)? {67				out.push(i);68			};69		}70		Ok(Self::eager(out))71	}7273	pub fn extended(a: ArrValue, b: ArrValue) -> Self {74		// TODO: benchmark for an optimal value, currently just a arbitrary choice75		const ARR_EXTEND_THRESHOLD: usize = 100;7677		if a.is_empty() {78			b79		} else if b.is_empty() {80			a81		} else if a.len() + b.len() > ARR_EXTEND_THRESHOLD {82			Self::new(ExtendedArray::new(a, b))83		} else if let (Some(a), Some(b)) = (a.iter_cheap(), b.iter_cheap()) {84			let mut out = Vec::with_capacity(a.len() + b.len());85			out.extend(a);86			out.extend(b);87			Self::eager(out)88		} else {89			let mut out = Vec::with_capacity(a.len() + b.len());90			out.extend(a.iter_lazy());91			out.extend(b.iter_lazy());92			Self::lazy(out)93		}94	}9596	pub fn range_exclusive(a: i32, b: i32) -> Self {97		Self::new(RangeArray::new_exclusive(a, b))98	}99	pub fn range_inclusive(a: i32, b: i32) -> Self {100		Self::new(RangeArray::new_inclusive(a, b))101	}102103	#[must_use]104	pub fn slice(105		self,106		from: Option<usize>,107		to: Option<usize>,108		step: Option<usize>,109	) -> Option<Self> {110		let len = self.len();111		let from = from.unwrap_or(0);112		let to = to.unwrap_or(len).min(len);113		let step = step.unwrap_or(1);114115		if from >= to || step == 0 {116			return None;117		}118119		Some(Self::new(SliceArray {120			inner: self,121			from: from as u32,122			to: to as u32,123			step: step as u32,124		}))125	}126127	/// Array length.128	pub fn len(&self) -> usize {129		self.0.len()130	}131132	/// Is array contains no elements?133	pub fn is_empty(&self) -> bool {134		self.0.is_empty()135	}136137	/// Get array element by index, evaluating it, if it is lazy.138	///139	/// Returns `None` on out-of-bounds condition.140	pub fn get(&self, index: usize) -> Result<Option<Val>> {141		self.0.get(index)142	}143144	/// Returns None if get is either non cheap, or out of bounds145	fn get_cheap(&self, index: usize) -> Option<Val> {146		self.0.get_cheap(index)147	}148149	/// Get array element by index, without evaluation.150	///151	/// Returns `None` on out-of-bounds condition.152	pub fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {153		self.0.get_lazy(index)154	}155156	pub fn iter(&self) -> impl ArrayLikeIter<Result<Val>> + '_ {157		(0..self.len()).map(|i| self.get(i).transpose().expect("length checked"))158	}159160	/// Iterate over elements, returning lazy values.161	pub fn iter_lazy(&self) -> impl ArrayLikeIter<Thunk<Val>> + '_ {162		(0..self.len()).map(|i| self.get_lazy(i).expect("length checked"))163	}164165	pub fn iter_cheap(&self) -> Option<impl ArrayLikeIter<Val> + '_> {166		if self.is_cheap() {167			Some((0..self.len()).map(|i| self.get_cheap(i).expect("length and is_cheap checked")))168		} else {169			None170		}171	}172173	/// Return a reversed view on current array.174	#[must_use]175	pub fn reversed(self) -> Self {176		Self::new(ReverseArray(self))177	}178179	pub fn ptr_eq(a: &Self, b: &Self) -> bool {180		Cc::ptr_eq(&a.0, &b.0)181	}182183	/// Is this vec supports `.get_cheap()?`184	pub fn is_cheap(&self) -> bool {185		self.0.is_cheap()186	}187188	pub fn as_any(&self) -> &dyn Any {189		&self.0190	}191}192impl From<Vec<Val>> for ArrValue {193	fn from(value: Vec<Val>) -> Self {194		Self::eager(value)195	}196}197impl From<Vec<Thunk<Val>>> for ArrValue {198	fn from(value: Vec<Thunk<Val>>) -> Self {199		Self::lazy(value)200	}201}202impl FromIterator<Val> for ArrValue {203	fn from_iter<T: IntoIterator<Item = Val>>(iter: T) -> Self {204		Self::eager(iter.into_iter().collect())205	}206}207impl ArrayLike for ArrValue {208	fn len(&self) -> usize {209		self.0.len()210	}211212	fn get(&self, index: usize) -> Result<Option<Val>> {213		self.0.get(index)214	}215216	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {217		self.0.get_lazy(index)218	}219220	fn get_cheap(&self, index: usize) -> Option<Val> {221		self.0.get_cheap(index)222	}223224	fn is_cheap(&self) -> bool {225		self.0.is_cheap()226	}227}228229#[cfg(target_pointer_width = "64")]230static_assertions::assert_eq_size!(ArrValue, [u8; 8]);