git.delta.rocks / jrsonnet / refs/commits / 1bfba233fc03

difftreelog

source

crates/jrsonnet-evaluator/src/arr/mod.rs6.4 KiBsourcehistory
1use std::{2	any::Any,3	fmt::{self},4	num::NonZeroU32,5	rc::Rc,6};78use jrsonnet_gcmodule::{Cc, cc_dyn};9use jrsonnet_interner::IBytes;10use jrsonnet_ir::Expr;1112use crate::{Context, Result, Thunk, Val, function::NativeFn, typed::IntoUntyped};1314mod spec;15pub use spec::{ArrayLike, *};1617cc_dyn!(18	#[doc = "Represents a Jsonnet array value."]19	#[derive(Clone)]20	ArrValue,21	ArrayLike,22	pub fn new() {...}23);24impl fmt::Debug for ArrValue {25	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {26		self.0.fmt(f)27	}28}2930pub trait ArrayLikeIter<T>: Iterator<Item = T> + DoubleEndedIterator + ExactSizeIterator {}31impl<I, T> ArrayLikeIter<T> for I where32	I: Iterator<Item = T> + DoubleEndedIterator + ExactSizeIterator33{34}3536impl ArrValue {37	pub fn empty() -> Self {38		Self::new(RangeArray::empty())39	}4041	pub fn expr(ctx: Context, exprs: Rc<Vec<Expr>>) -> Self {42		Self::new(ExprArray::new(ctx, exprs))43	}4445	pub fn lazy(thunks: Vec<Thunk<Val>>) -> Self {46		Self::new(LazyArray(thunks))47	}4849	pub fn eager(values: Vec<Val>) -> Self {50		Self::new(EagerArray(values))51	}5253	pub fn repeated(data: Self, repeats: usize) -> Option<Self> {54		Some(Self::new(RepeatedArray::new(data, repeats)?))55	}5657	pub fn bytes(bytes: IBytes) -> Self {58		Self::new(BytesArray(bytes))59	}60	pub fn chars(chars: impl Iterator<Item = char>) -> Self {61		Self::new(CharArray(chars.collect()))62	}6364	#[must_use]65	pub fn map(self, mapper: NativeFn!((Val) -> Val)) -> Self {66		Self::new(<MappedArray>::new(self, ArrayMapper::Plain(mapper)))67	}6869	#[must_use]70	pub fn map_with_index(self, mapper: NativeFn!((u32, Val) -> Val)) -> Self {71		Self::new(<MappedArray>::new(self, ArrayMapper::WithIndex(mapper)))72	}7374	pub fn filter(self, filter: NativeFn!((Thunk<Val>) -> bool)) -> Result<Self> {75		// TODO: ArrValue::Picked(inner, indexes) for large arrays76		'eager: {77			let mut out = Vec::new();78			for i in self.iter() {79				let Ok(i) = i else {80					break 'eager;81				};82				if filter.call(IntoUntyped::into_lazy_untyped(i.clone()))? {83					out.push(i);84				}85			}86			return Ok(Self::eager(out));87		};8889		let mut out = Vec::new();90		for i in self.iter_lazy() {91			if filter.call(i.clone())? {92				out.push(i);93			}94		}95		Ok(Self::lazy(out))96	}9798	pub fn extended(a: Self, b: Self) -> Self {99		// TODO: benchmark for an optimal value, currently just a arbitrary choice100		const ARR_EXTEND_THRESHOLD: usize = 1000;101102		if a.is_empty() {103			b104		} else if b.is_empty() {105			a106		} else if a.len() + b.len() > ARR_EXTEND_THRESHOLD {107			Self::new(ExtendedArray::new(a, b))108		} else if let (Some(a), Some(b)) = (a.iter_cheap(), b.iter_cheap()) {109			let mut out = Vec::with_capacity(a.len() + b.len());110			out.extend(a);111			out.extend(b);112			Self::eager(out)113		} else {114			let mut out = Vec::with_capacity(a.len() + b.len());115			out.extend(a.iter_lazy());116			out.extend(b.iter_lazy());117			Self::lazy(out)118		}119	}120121	pub fn range_exclusive(a: i32, b: i32) -> Self {122		Self::new(RangeArray::new_exclusive(a, b))123	}124	pub fn range_inclusive(a: i32, b: i32) -> Self {125		Self::new(RangeArray::new_inclusive(a, b))126	}127128	#[must_use]129	pub fn slice(self, index: Option<i32>, end: Option<i32>, step: Option<NonZeroU32>) -> Self {130		let get_idx = |pos: Option<i32>, len: usize, default| match pos {131			#[expect(132				clippy::cast_sign_loss,133				reason = "abs value is used, len is limited to u31"134			)]135			Some(v) if v < 0 => len.saturating_sub((-v) as usize),136			#[expect(clippy::cast_sign_loss, reason = "abs value is used")]137			Some(v) => (v as usize).min(len),138			None => default,139		};140		let index = get_idx(index, self.len(), 0);141		let end = get_idx(end, self.len(), self.len());142		let step = step.unwrap_or_else(|| NonZeroU32::new(1).expect("1 != 0"));143144		if index >= end {145			return Self::empty();146		}147148		Self::new(SliceArray {149			inner: self,150			#[expect(clippy::cast_possible_truncation, reason = "len is limited to u31")]151			from: index as u32,152			#[expect(clippy::cast_possible_truncation, reason = "len is limited to u31")]153			to: end as u32,154			step: step.get(),155		})156	}157158	/// Array length.159	pub fn len(&self) -> usize {160		self.0.len()161	}162163	/// Is array contains no elements?164	pub fn is_empty(&self) -> bool {165		self.0.is_empty()166	}167168	/// Get array element by index, evaluating it, if it is lazy.169	///170	/// Returns `None` on out-of-bounds condition.171	pub fn get(&self, index: usize) -> Result<Option<Val>> {172		self.0.get(index)173	}174175	/// Returns None if get is either non cheap, or out of bounds176	/// Note that non-cheap access includes errorable values177	///178	/// Prefer it to `get_lazy`, but use `get` when you can.179	fn get_cheap(&self, index: usize) -> Option<Val> {180		self.0.get_cheap(index)181	}182183	/// Get array element by index, without evaluation.184	///185	/// Returns `None` on out-of-bounds condition.186	pub fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {187		self.0.get_lazy(index)188	}189190	pub fn iter(&self) -> impl ArrayLikeIter<Result<Val>> + '_ {191		(0..self.len()).map(|i| self.get(i).transpose().expect("length checked"))192	}193194	/// Iterate over elements, returning lazy values.195	pub fn iter_lazy(&self) -> impl ArrayLikeIter<Thunk<Val>> + '_ {196		(0..self.len()).map(|i| self.get_lazy(i).expect("length checked"))197	}198199	/// Prefer it over `iter_lazy`, but do not use it where `iter` will do.200	pub fn iter_cheap(&self) -> Option<impl ArrayLikeIter<Val> + '_> {201		if self.is_cheap() {202			Some((0..self.len()).map(|i| self.get_cheap(i).expect("length and is_cheap checked")))203		} else {204			None205		}206	}207208	/// Return a reversed view on current array.209	#[must_use]210	pub fn reversed(self) -> Self {211		Self::new(ReverseArray(self))212	}213214	pub fn ptr_eq(a: &Self, b: &Self) -> bool {215		Cc::ptr_eq(&a.0, &b.0)216	}217218	/// Is this vec supports `.get_cheap()?`219	pub fn is_cheap(&self) -> bool {220		self.0.is_cheap()221	}222223	pub fn as_any(&self) -> &dyn Any {224		&self.0225	}226}227impl From<Vec<Val>> for ArrValue {228	fn from(value: Vec<Val>) -> Self {229		Self::eager(value)230	}231}232impl From<Vec<Thunk<Val>>> for ArrValue {233	fn from(value: Vec<Thunk<Val>>) -> Self {234		Self::lazy(value)235	}236}237impl FromIterator<Val> for ArrValue {238	fn from_iter<T: IntoIterator<Item = Val>>(iter: T) -> Self {239		Self::eager(iter.into_iter().collect())240	}241}242impl ArrayLike for ArrValue {243	fn len(&self) -> usize {244		self.0.len()245	}246247	fn get(&self, index: usize) -> Result<Option<Val>> {248		self.0.get(index)249	}250251	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {252		self.0.get_lazy(index)253	}254255	fn get_cheap(&self, index: usize) -> Option<Val> {256		self.0.get_cheap(index)257	}258259	fn is_cheap(&self) -> bool {260		self.0.is_cheap()261	}262}