1use std::{2 any::Any,3 fmt::{self},4 num::NonZeroU32,5 rc::Rc,6};78use jrsonnet_gcmodule::{cc_dyn, Cc};9use jrsonnet_interner::IBytes;10use jrsonnet_ir::Expr;1112use crate::{function::NativeFn, typed::IntoUntyped, Context, Result, Thunk, Val};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 76 '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 100 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 Some(v) if v < 0 => len.saturating_sub((-v) as usize),132 Some(v) => (v as usize).min(len),133 None => default,134 };135 let index = get_idx(index, self.len(), 0);136 let end = get_idx(end, self.len(), self.len());137 let step = step.unwrap_or_else(|| NonZeroU32::new(1).expect("1 != 0"));138139 if index >= end {140 return Self::empty();141 }142143 Self::new(SliceArray {144 inner: self,145 from: index as u32,146 to: end as u32,147 step: step.get(),148 })149 }150151 152 pub fn len(&self) -> usize {153 self.0.len()154 }155156 157 pub fn is_empty(&self) -> bool {158 self.0.is_empty()159 }160161 162 163 164 pub fn get(&self, index: usize) -> Result<Option<Val>> {165 self.0.get(index)166 }167168 169 170 171 172 fn get_cheap(&self, index: usize) -> Option<Val> {173 self.0.get_cheap(index)174 }175176 177 178 179 pub fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {180 self.0.get_lazy(index)181 }182183 pub fn iter(&self) -> impl ArrayLikeIter<Result<Val>> + '_ {184 (0..self.len()).map(|i| self.get(i).transpose().expect("length checked"))185 }186187 188 pub fn iter_lazy(&self) -> impl ArrayLikeIter<Thunk<Val>> + '_ {189 (0..self.len()).map(|i| self.get_lazy(i).expect("length checked"))190 }191192 193 pub fn iter_cheap(&self) -> Option<impl ArrayLikeIter<Val> + '_> {194 if self.is_cheap() {195 Some((0..self.len()).map(|i| self.get_cheap(i).expect("length and is_cheap checked")))196 } else {197 None198 }199 }200201 202 #[must_use]203 pub fn reversed(self) -> Self {204 Self::new(ReverseArray(self))205 }206207 pub fn ptr_eq(a: &Self, b: &Self) -> bool {208 Cc::ptr_eq(&a.0, &b.0)209 }210211 212 pub fn is_cheap(&self) -> bool {213 self.0.is_cheap()214 }215216 pub fn as_any(&self) -> &dyn Any {217 &self.0218 }219}220impl From<Vec<Val>> for ArrValue {221 fn from(value: Vec<Val>) -> Self {222 Self::eager(value)223 }224}225impl From<Vec<Thunk<Val>>> for ArrValue {226 fn from(value: Vec<Thunk<Val>>) -> Self {227 Self::lazy(value)228 }229}230impl FromIterator<Val> for ArrValue {231 fn from_iter<T: IntoIterator<Item = Val>>(iter: T) -> Self {232 Self::eager(iter.into_iter().collect())233 }234}235impl ArrayLike for ArrValue {236 fn len(&self) -> usize {237 self.0.len()238 }239240 fn get(&self, index: usize) -> Result<Option<Val>> {241 self.0.get(index)242 }243244 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {245 self.0.get_lazy(index)246 }247248 fn get_cheap(&self, index: usize) -> Option<Val> {249 self.0.get_cheap(index)250 }251252 fn is_cheap(&self) -> bool {253 self.0.is_cheap()254 }255}