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, *};111213#[derive(Debug, Clone, Trace)]1415#[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<false>>::new(self, mapper))58 }5960 #[must_use]61 pub fn map_with_index(self, mapper: FuncVal) -> Self {62 Self::new(<MappedArray<true>>::new(self, mapper))63 }6465 pub fn filter(self, filter: impl Fn(&Val) -> Result<bool>) -> Result<Self> {66 67 let mut out = Vec::new();68 for i in self.iter() {69 let i = i?;70 if filter(&i)? {71 out.push(i);72 };73 }74 Ok(Self::eager(out))75 }7677 pub fn extended(a: Self, b: Self) -> Self {78 79 const ARR_EXTEND_THRESHOLD: usize = 100;8081 if a.is_empty() {82 b83 } else if b.is_empty() {84 a85 } else if a.len() + b.len() > ARR_EXTEND_THRESHOLD {86 Self::new(ExtendedArray::new(a, b))87 } else if let (Some(a), Some(b)) = (a.iter_cheap(), b.iter_cheap()) {88 let mut out = Vec::with_capacity(a.len() + b.len());89 out.extend(a);90 out.extend(b);91 Self::eager(out)92 } else {93 let mut out = Vec::with_capacity(a.len() + b.len());94 out.extend(a.iter_lazy());95 out.extend(b.iter_lazy());96 Self::lazy(out)97 }98 }99100 pub fn range_exclusive(a: i32, b: i32) -> Self {101 Self::new(RangeArray::new_exclusive(a, b))102 }103 pub fn range_inclusive(a: i32, b: i32) -> Self {104 Self::new(RangeArray::new_inclusive(a, b))105 }106107 #[must_use]108 pub fn slice(self, index: Option<i32>, end: Option<i32>, step: Option<NonZeroU32>) -> Self {109 let get_idx = |pos: Option<i32>, len: usize, default| match pos {110 Some(v) if v < 0 => len.saturating_sub((-v) as usize),111 Some(v) => (v as usize).min(len),112 None => default,113 };114 let index = get_idx(index, self.len(), 0);115 let end = get_idx(end, self.len(), self.len());116 let step = step.unwrap_or_else(|| NonZeroU32::new(1).expect("1 != 0"));117118 if index >= end {119 return Self::empty();120 }121122 Self::new(SliceArray {123 inner: self,124 from: index as u32,125 to: end as u32,126 step: step.get(),127 })128 }129130 131 pub fn len(&self) -> usize {132 self.0.len()133 }134135 136 pub fn is_empty(&self) -> bool {137 self.0.is_empty()138 }139140 141 142 143 pub fn get(&self, index: usize) -> Result<Option<Val>> {144 self.0.get(index)145 }146147 148 fn get_cheap(&self, index: usize) -> Option<Val> {149 self.0.get_cheap(index)150 }151152 153 154 155 pub fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {156 self.0.get_lazy(index)157 }158159 pub fn iter(&self) -> impl ArrayLikeIter<Result<Val>> + '_ {160 (0..self.len()).map(|i| self.get(i).transpose().expect("length checked"))161 }162163 164 pub fn iter_lazy(&self) -> impl ArrayLikeIter<Thunk<Val>> + '_ {165 (0..self.len()).map(|i| self.get_lazy(i).expect("length checked"))166 }167168 pub fn iter_cheap(&self) -> Option<impl ArrayLikeIter<Val> + '_> {169 if self.is_cheap() {170 Some((0..self.len()).map(|i| self.get_cheap(i).expect("length and is_cheap checked")))171 } else {172 None173 }174 }175176 177 #[must_use]178 pub fn reversed(self) -> Self {179 Self::new(ReverseArray(self))180 }181182 pub fn ptr_eq(a: &Self, b: &Self) -> bool {183 Cc::ptr_eq(&a.0, &b.0)184 }185186 187 pub fn is_cheap(&self) -> bool {188 self.0.is_cheap()189 }190191 pub fn as_any(&self) -> &dyn Any {192 &self.0193 }194}195impl From<Vec<Val>> for ArrValue {196 fn from(value: Vec<Val>) -> Self {197 Self::eager(value)198 }199}200impl From<Vec<Thunk<Val>>> for ArrValue {201 fn from(value: Vec<Thunk<Val>>) -> Self {202 Self::lazy(value)203 }204}205impl FromIterator<Val> for ArrValue {206 fn from_iter<T: IntoIterator<Item = Val>>(iter: T) -> Self {207 Self::eager(iter.into_iter().collect())208 }209}210impl ArrayLike for ArrValue {211 fn len(&self) -> usize {212 self.0.len()213 }214215 fn get(&self, index: usize) -> Result<Option<Val>> {216 self.0.get(index)217 }218219 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {220 self.0.get_lazy(index)221 }222223 fn get_cheap(&self, index: usize) -> Option<Val> {224 self.0.get_cheap(index)225 }226227 fn is_cheap(&self) -> bool {228 self.0.is_cheap()229 }230}231232#[cfg(target_pointer_width = "64")]233static_assertions::assert_eq_size!(ArrValue, [u8; 8]);