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, 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: impl Fn(&Val) -> Result<bool>) -> Result<Self> {75 76 let mut out = Vec::new();77 for i in self.iter() {78 let i = i?;79 if filter(&i)? {80 out.push(i);81 }82 }83 Ok(Self::eager(out))84 }8586 pub fn extended(a: Self, b: Self) -> Self {87 88 const ARR_EXTEND_THRESHOLD: usize = 1000;8990 if a.is_empty() {91 b92 } else if b.is_empty() {93 a94 } else if a.len() + b.len() > ARR_EXTEND_THRESHOLD {95 Self::new(ExtendedArray::new(a, b))96 } else if let (Some(a), Some(b)) = (a.iter_cheap(), b.iter_cheap()) {97 let mut out = Vec::with_capacity(a.len() + b.len());98 out.extend(a);99 out.extend(b);100 Self::eager(out)101 } else {102 let mut out = Vec::with_capacity(a.len() + b.len());103 out.extend(a.iter_lazy());104 out.extend(b.iter_lazy());105 Self::lazy(out)106 }107 }108109 pub fn range_exclusive(a: i32, b: i32) -> Self {110 Self::new(RangeArray::new_exclusive(a, b))111 }112 pub fn range_inclusive(a: i32, b: i32) -> Self {113 Self::new(RangeArray::new_inclusive(a, b))114 }115116 #[must_use]117 pub fn slice(self, index: Option<i32>, end: Option<i32>, step: Option<NonZeroU32>) -> Self {118 let get_idx = |pos: Option<i32>, len: usize, default| match pos {119 Some(v) if v < 0 => len.saturating_sub((-v) as usize),120 Some(v) => (v as usize).min(len),121 None => default,122 };123 let index = get_idx(index, self.len(), 0);124 let end = get_idx(end, self.len(), self.len());125 let step = step.unwrap_or_else(|| NonZeroU32::new(1).expect("1 != 0"));126127 if index >= end {128 return Self::empty();129 }130131 Self::new(SliceArray {132 inner: self,133 from: index as u32,134 to: end as u32,135 step: step.get(),136 })137 }138139 140 pub fn len(&self) -> usize {141 self.0.len()142 }143144 145 pub fn is_empty(&self) -> bool {146 self.0.is_empty()147 }148149 150 151 152 pub fn get(&self, index: usize) -> Result<Option<Val>> {153 self.0.get(index)154 }155156 157 158 159 160 fn get_cheap(&self, index: usize) -> Option<Val> {161 self.0.get_cheap(index)162 }163164 165 166 167 pub fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {168 self.0.get_lazy(index)169 }170171 pub fn iter(&self) -> impl ArrayLikeIter<Result<Val>> + '_ {172 (0..self.len()).map(|i| self.get(i).transpose().expect("length checked"))173 }174175 176 pub fn iter_lazy(&self) -> impl ArrayLikeIter<Thunk<Val>> + '_ {177 (0..self.len()).map(|i| self.get_lazy(i).expect("length checked"))178 }179180 181 pub fn iter_cheap(&self) -> Option<impl ArrayLikeIter<Val> + '_> {182 if self.is_cheap() {183 Some((0..self.len()).map(|i| self.get_cheap(i).expect("length and is_cheap checked")))184 } else {185 None186 }187 }188189 190 #[must_use]191 pub fn reversed(self) -> Self {192 Self::new(ReverseArray(self))193 }194195 pub fn ptr_eq(a: &Self, b: &Self) -> bool {196 Cc::ptr_eq(&a.0, &b.0)197 }198199 200 pub fn is_cheap(&self) -> bool {201 self.0.is_cheap()202 }203204 pub fn as_any(&self) -> &dyn Any {205 &self.0206 }207}208impl From<Vec<Val>> for ArrValue {209 fn from(value: Vec<Val>) -> Self {210 Self::eager(value)211 }212}213impl From<Vec<Thunk<Val>>> for ArrValue {214 fn from(value: Vec<Thunk<Val>>) -> Self {215 Self::lazy(value)216 }217}218impl FromIterator<Val> for ArrValue {219 fn from_iter<T: IntoIterator<Item = Val>>(iter: T) -> Self {220 Self::eager(iter.into_iter().collect())221 }222}223impl ArrayLike for ArrValue {224 fn len(&self) -> usize {225 self.0.len()226 }227228 fn get(&self, index: usize) -> Result<Option<Val>> {229 self.0.get(index)230 }231232 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {233 self.0.get_lazy(index)234 }235236 fn get_cheap(&self, index: usize) -> Option<Val> {237 self.0.get_cheap(index)238 }239240 fn is_cheap(&self) -> bool {241 self.0.is_cheap()242 }243}