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

difftreelog

doc: outdated panic reason

Yaroslav Bolyukin2024-05-17parent: #4fe0b2f.patch.diff
in: master

1 file changed

modifiedcrates/jrsonnet-evaluator/src/arr/mod.rsdiffbeforeafterboth
before · crates/jrsonnet-evaluator/src/arr/mod.rs
1use std::{any::Any, num::NonZeroU32};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	/// # Panics103	/// If step == 0104	#[must_use]105	pub fn slice(self, index: Option<i32>, end: Option<i32>, step: Option<NonZeroU32>) -> Self {106		let get_idx = |pos: Option<i32>, len: usize, default| match pos {107			Some(v) if v < 0 => len.saturating_sub((-v) as usize),108			Some(v) => (v as usize).min(len),109			None => default,110		};111		let index = get_idx(index, self.len(), 0);112		let end = get_idx(end, self.len(), self.len());113		let step = step.unwrap_or_else(|| NonZeroU32::new(1).expect("1 != 0"));114115		if index >= end {116			return Self::empty();117		}118119		Self::new(SliceArray {120			inner: self,121			from: index as u32,122			to: end as u32,123			step: step.get(),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]);