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::new(self, mapper))58 }5960 pub fn filter(self, filter: impl Fn(&Val) -> Result<bool>) -> Result<Self> {61 62 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 74 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 #[must_use]103 pub fn slice(self, index: Option<i32>, end: Option<i32>, step: Option<NonZeroU32>) -> Self {104 let get_idx = |pos: Option<i32>, len: usize, default| match pos {105 Some(v) if v < 0 => len.saturating_sub((-v) as usize),106 Some(v) => (v as usize).min(len),107 None => default,108 };109 let index = get_idx(index, self.len(), 0);110 let end = get_idx(end, self.len(), self.len());111 let step = step.unwrap_or_else(|| NonZeroU32::new(1).expect("1 != 0"));112113 if index >= end {114 return Self::empty();115 }116117 Self::new(SliceArray {118 inner: self,119 from: index as u32,120 to: end as u32,121 step: step.get(),122 })123 }124125 126 pub fn len(&self) -> usize {127 self.0.len()128 }129130 131 pub fn is_empty(&self) -> bool {132 self.0.is_empty()133 }134135 136 137 138 pub fn get(&self, index: usize) -> Result<Option<Val>> {139 self.0.get(index)140 }141142 143 fn get_cheap(&self, index: usize) -> Option<Val> {144 self.0.get_cheap(index)145 }146147 148 149 150 pub fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {151 self.0.get_lazy(index)152 }153154 pub fn iter(&self) -> impl ArrayLikeIter<Result<Val>> + '_ {155 (0..self.len()).map(|i| self.get(i).transpose().expect("length checked"))156 }157158 159 pub fn iter_lazy(&self) -> impl ArrayLikeIter<Thunk<Val>> + '_ {160 (0..self.len()).map(|i| self.get_lazy(i).expect("length checked"))161 }162163 pub fn iter_cheap(&self) -> Option<impl ArrayLikeIter<Val> + '_> {164 if self.is_cheap() {165 Some((0..self.len()).map(|i| self.get_cheap(i).expect("length and is_cheap checked")))166 } else {167 None168 }169 }170171 172 #[must_use]173 pub fn reversed(self) -> Self {174 Self::new(ReverseArray(self))175 }176177 pub fn ptr_eq(a: &Self, b: &Self) -> bool {178 Cc::ptr_eq(&a.0, &b.0)179 }180181 182 pub fn is_cheap(&self) -> bool {183 self.0.is_cheap()184 }185186 pub fn as_any(&self) -> &dyn Any {187 &self.0188 }189}190impl From<Vec<Val>> for ArrValue {191 fn from(value: Vec<Val>) -> Self {192 Self::eager(value)193 }194}195impl From<Vec<Thunk<Val>>> for ArrValue {196 fn from(value: Vec<Thunk<Val>>) -> Self {197 Self::lazy(value)198 }199}200impl FromIterator<Val> for ArrValue {201 fn from_iter<T: IntoIterator<Item = Val>>(iter: T) -> Self {202 Self::eager(iter.into_iter().collect())203 }204}205impl ArrayLike for ArrValue {206 fn len(&self) -> usize {207 self.0.len()208 }209210 fn get(&self, index: usize) -> Result<Option<Val>> {211 self.0.get(index)212 }213214 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {215 self.0.get_lazy(index)216 }217218 fn get_cheap(&self, index: usize) -> Option<Val> {219 self.0.get_cheap(index)220 }221222 fn is_cheap(&self) -> bool {223 self.0.is_cheap()224 }225}226227#[cfg(target_pointer_width = "64")]228static_assertions::assert_eq_size!(ArrValue, [u8; 8]);