1use crossbeam::channel::{Receiver, Sender};
2use indexmap::IndexMap;
3use parking_lot::{Mutex, RwLock};
4use std::cmp::Ordering;
5use std::collections::VecDeque;
6use std::fmt;
7use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering};
8use std::sync::Arc;
9use std::sync::Barrier;
10
11use crate::ast::{Block, ClassDef, EnumDef, StructDef, SubSigParam};
12use crate::error::PerlResult;
13use crate::nanbox;
14use crate::perl_decode::decode_utf8_or_latin1;
15use crate::perl_regex::PerlCompiledRegex;
16
17#[derive(Debug)]
19pub struct PerlAsyncTask {
20 pub(crate) result: Arc<Mutex<Option<PerlResult<PerlValue>>>>,
21 pub(crate) join: Arc<Mutex<Option<std::thread::JoinHandle<()>>>>,
22}
23
24impl Clone for PerlAsyncTask {
25 fn clone(&self) -> Self {
26 Self {
27 result: self.result.clone(),
28 join: self.join.clone(),
29 }
30 }
31}
32
33impl PerlAsyncTask {
34 pub fn await_result(&self) -> PerlResult<PerlValue> {
36 if let Some(h) = self.join.lock().take() {
37 let _ = h.join();
38 }
39 self.result
40 .lock()
41 .clone()
42 .unwrap_or_else(|| Ok(PerlValue::UNDEF))
43 }
44}
45
46pub trait PerlIterator: Send + Sync {
51 fn next_item(&self) -> Option<PerlValue>;
53
54 fn collect_all(&self) -> Vec<PerlValue> {
56 let mut out = Vec::new();
57 while let Some(v) = self.next_item() {
58 out.push(v);
59 }
60 out
61 }
62}
63
64impl fmt::Debug for dyn PerlIterator {
65 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66 f.write_str("PerlIterator")
67 }
68}
69
70pub struct FsWalkIterator {
72 stack: Mutex<Vec<(std::path::PathBuf, String)>>,
74 buf: Mutex<Vec<(String, bool)>>, pending_dirs: Mutex<Vec<(std::path::PathBuf, String)>>,
78 files_only: bool,
79}
80
81impl FsWalkIterator {
82 pub fn new(dir: &str, files_only: bool) -> Self {
83 Self {
84 stack: Mutex::new(vec![(std::path::PathBuf::from(dir), String::new())]),
85 buf: Mutex::new(Vec::new()),
86 pending_dirs: Mutex::new(Vec::new()),
87 files_only,
88 }
89 }
90
91 fn refill(&self) -> bool {
94 loop {
95 let mut stack = self.stack.lock();
96 let mut pending = self.pending_dirs.lock();
98 while let Some(d) = pending.pop() {
99 stack.push(d);
100 }
101 drop(pending);
102
103 let (base, rel) = match stack.pop() {
104 Some(v) => v,
105 None => return false,
106 };
107 drop(stack);
108
109 let entries = match std::fs::read_dir(&base) {
110 Ok(e) => e,
111 Err(_) => continue, };
113 let mut children: Vec<(std::ffi::OsString, String, bool, bool)> = Vec::new();
114 for entry in entries.flatten() {
115 let ft = match entry.file_type() {
116 Ok(ft) => ft,
117 Err(_) => continue,
118 };
119 let os_name = entry.file_name();
120 let name = match os_name.to_str() {
121 Some(n) => n.to_string(),
122 None => continue,
123 };
124 let child_rel = if rel.is_empty() {
125 name.clone()
126 } else {
127 format!("{rel}/{name}")
128 };
129 children.push((os_name, child_rel, ft.is_file(), ft.is_dir()));
130 }
131 children.sort_by(|a, b| a.0.cmp(&b.0));
132
133 let mut buf = self.buf.lock();
134 let mut pending = self.pending_dirs.lock();
135 let mut subdirs = Vec::new();
136 for (os_name, child_rel, is_file, is_dir) in children {
137 if is_dir {
138 if !self.files_only {
139 buf.push((child_rel.clone(), true));
140 }
141 subdirs.push((base.join(os_name), child_rel));
142 } else if is_file && self.files_only {
143 buf.push((child_rel, false));
144 }
145 }
146 for s in subdirs.into_iter().rev() {
147 pending.push(s);
148 }
149 buf.reverse();
150 if !buf.is_empty() {
151 return true;
152 }
153 }
155 }
156}
157
158impl PerlIterator for FsWalkIterator {
159 fn next_item(&self) -> Option<PerlValue> {
160 loop {
161 {
162 let mut buf = self.buf.lock();
163 if let Some((path, _)) = buf.pop() {
164 return Some(PerlValue::string(path));
165 }
166 }
167 if !self.refill() {
168 return None;
169 }
170 }
171 }
172}
173
174pub struct ScalarReverseIterator {
176 source: Arc<dyn PerlIterator>,
177}
178
179impl ScalarReverseIterator {
180 pub fn new(source: Arc<dyn PerlIterator>) -> Self {
181 Self { source }
182 }
183}
184
185impl PerlIterator for ScalarReverseIterator {
186 fn next_item(&self) -> Option<PerlValue> {
187 let item = self.source.next_item()?;
188 let s = item.to_string();
189 Some(PerlValue::string(s.chars().rev().collect()))
190 }
191}
192
193#[derive(Debug)]
195pub struct PerlGenerator {
196 pub(crate) block: Block,
197 pub(crate) pc: Mutex<usize>,
198 pub(crate) scope_started: Mutex<bool>,
199 pub(crate) exhausted: Mutex<bool>,
200}
201
202pub type PerlSet = IndexMap<String, PerlValue>;
204
205#[derive(Debug, Clone)]
207pub struct PerlHeap {
208 pub items: Vec<PerlValue>,
209 pub cmp: Arc<PerlSub>,
210}
211
212#[derive(Debug, Clone)]
220pub struct RemoteSlot {
221 pub host: String,
223 pub pe_path: String,
225}
226
227#[cfg(test)]
228mod cluster_parsing_tests {
229 use super::*;
230
231 fn s(v: &str) -> PerlValue {
232 PerlValue::string(v.to_string())
233 }
234
235 #[test]
236 fn parses_simple_host() {
237 let c = RemoteCluster::from_list_args(&[s("host1")]).expect("parse");
238 assert_eq!(c.slots.len(), 1);
239 assert_eq!(c.slots[0].host, "host1");
240 assert_eq!(c.slots[0].pe_path, "stryke");
241 }
242
243 #[test]
244 fn parses_host_with_slot_count() {
245 let c = RemoteCluster::from_list_args(&[s("host1:4")]).expect("parse");
246 assert_eq!(c.slots.len(), 4);
247 assert!(c.slots.iter().all(|s| s.host == "host1"));
248 }
249
250 #[test]
251 fn parses_user_at_host_with_slots() {
252 let c = RemoteCluster::from_list_args(&[s("alice@build1:2")]).expect("parse");
253 assert_eq!(c.slots.len(), 2);
254 assert_eq!(c.slots[0].host, "alice@build1");
255 }
256
257 #[test]
258 fn parses_host_slots_fo_path_triple() {
259 let c =
260 RemoteCluster::from_list_args(&[s("build1:3:/usr/local/bin/stryke")]).expect("parse");
261 assert_eq!(c.slots.len(), 3);
262 assert!(c.slots.iter().all(|sl| sl.host == "build1"));
263 assert!(c
264 .slots
265 .iter()
266 .all(|sl| sl.pe_path == "/usr/local/bin/stryke"));
267 }
268
269 #[test]
270 fn parses_multiple_hosts_in_one_call() {
271 let c = RemoteCluster::from_list_args(&[s("host1:2"), s("host2:1")]).expect("parse");
272 assert_eq!(c.slots.len(), 3);
273 assert_eq!(c.slots[0].host, "host1");
274 assert_eq!(c.slots[1].host, "host1");
275 assert_eq!(c.slots[2].host, "host2");
276 }
277
278 #[test]
279 fn parses_hashref_slot_form() {
280 let mut h = indexmap::IndexMap::new();
281 h.insert("host".to_string(), s("data1"));
282 h.insert("slots".to_string(), PerlValue::integer(2));
283 h.insert("stryke".to_string(), s("/opt/stryke"));
284 let c = RemoteCluster::from_list_args(&[PerlValue::hash(h)]).expect("parse");
285 assert_eq!(c.slots.len(), 2);
286 assert_eq!(c.slots[0].host, "data1");
287 assert_eq!(c.slots[0].pe_path, "/opt/stryke");
288 }
289
290 #[test]
291 fn parses_trailing_tunables_hashref() {
292 let mut tun = indexmap::IndexMap::new();
293 tun.insert("timeout".to_string(), PerlValue::integer(30));
294 tun.insert("retries".to_string(), PerlValue::integer(2));
295 tun.insert("connect_timeout".to_string(), PerlValue::integer(5));
296 let c = RemoteCluster::from_list_args(&[s("h1:1"), PerlValue::hash(tun)]).expect("parse");
297 assert_eq!(c.slots.len(), 1);
299 assert_eq!(c.job_timeout_ms, 30_000);
300 assert_eq!(c.max_attempts, 3); assert_eq!(c.connect_timeout_ms, 5_000);
302 }
303
304 #[test]
305 fn defaults_when_no_tunables() {
306 let c = RemoteCluster::from_list_args(&[s("h1")]).expect("parse");
307 assert_eq!(c.job_timeout_ms, RemoteCluster::DEFAULT_JOB_TIMEOUT_MS);
308 assert_eq!(c.max_attempts, RemoteCluster::DEFAULT_MAX_ATTEMPTS);
309 assert_eq!(
310 c.connect_timeout_ms,
311 RemoteCluster::DEFAULT_CONNECT_TIMEOUT_MS
312 );
313 }
314
315 #[test]
316 fn rejects_empty_cluster() {
317 assert!(RemoteCluster::from_list_args(&[]).is_err());
318 }
319
320 #[test]
321 fn slot_count_minimum_one() {
322 let c = RemoteCluster::from_list_args(&[s("h1:0")]).expect("parse");
323 assert_eq!(c.slots.len(), 1);
326 }
327}
328
329#[derive(Debug, Clone)]
338pub struct RemoteCluster {
339 pub slots: Vec<RemoteSlot>,
340 pub job_timeout_ms: u64,
341 pub max_attempts: u32,
342 pub connect_timeout_ms: u64,
343}
344
345impl RemoteCluster {
346 pub const DEFAULT_JOB_TIMEOUT_MS: u64 = 60_000;
347 pub const DEFAULT_MAX_ATTEMPTS: u32 = 3;
348 pub const DEFAULT_CONNECT_TIMEOUT_MS: u64 = 10_000;
349
350 pub fn from_list_args(items: &[PerlValue]) -> Result<Self, String> {
364 let mut slots: Vec<RemoteSlot> = Vec::new();
365 let mut job_timeout_ms = Self::DEFAULT_JOB_TIMEOUT_MS;
366 let mut max_attempts = Self::DEFAULT_MAX_ATTEMPTS;
367 let mut connect_timeout_ms = Self::DEFAULT_CONNECT_TIMEOUT_MS;
368
369 let (slot_items, tunables) = if let Some(last) = items.last() {
371 let h = last
372 .as_hash_map()
373 .or_else(|| last.as_hash_ref().map(|r| r.read().clone()));
374 if let Some(map) = h {
375 let known = |k: &str| {
376 matches!(k, "timeout" | "retries" | "connect_timeout" | "job_timeout")
377 };
378 if !map.is_empty() && map.keys().all(|k| known(k.as_str())) {
379 (&items[..items.len() - 1], Some(map))
380 } else {
381 (items, None)
382 }
383 } else {
384 (items, None)
385 }
386 } else {
387 (items, None)
388 };
389
390 if let Some(map) = tunables {
391 if let Some(v) = map.get("timeout").or_else(|| map.get("job_timeout")) {
392 job_timeout_ms = (v.to_number() * 1000.0) as u64;
393 }
394 if let Some(v) = map.get("retries") {
395 max_attempts = v.to_int().max(0) as u32 + 1;
397 }
398 if let Some(v) = map.get("connect_timeout") {
399 connect_timeout_ms = (v.to_number() * 1000.0) as u64;
400 }
401 }
402
403 for it in slot_items {
404 if let Some(map) = it
406 .as_hash_map()
407 .or_else(|| it.as_hash_ref().map(|r| r.read().clone()))
408 {
409 let host = map
410 .get("host")
411 .map(|v| v.to_string())
412 .ok_or_else(|| "cluster: hashref slot needs `host`".to_string())?;
413 let n = map.get("slots").map(|v| v.to_int().max(1)).unwrap_or(1) as usize;
414 let stryke = map
415 .get("stryke")
416 .or_else(|| map.get("pe_path"))
417 .map(|v| v.to_string())
418 .unwrap_or_else(|| "stryke".to_string());
419 for _ in 0..n {
420 slots.push(RemoteSlot {
421 host: host.clone(),
422 pe_path: stryke.clone(),
423 });
424 }
425 continue;
426 }
427
428 let s = it.to_string();
434 let (left, pe_path) = if let Some(idx) = s.find(':') {
436 let rest = &s[idx + 1..];
438 if let Some(jdx) = rest.find(':') {
439 let count_seg = &rest[..jdx];
441 if count_seg.parse::<usize>().is_ok() {
442 (
443 format!("{}:{}", &s[..idx], count_seg),
444 Some(rest[jdx + 1..].to_string()),
445 )
446 } else {
447 (s.clone(), None)
448 }
449 } else {
450 (s.clone(), None)
451 }
452 } else {
453 (s.clone(), None)
454 };
455 let pe_path = pe_path.unwrap_or_else(|| "stryke".to_string());
456
457 let (host, n) = if let Some((h, nstr)) = left.rsplit_once(':') {
460 if let Ok(n) = nstr.parse::<usize>() {
461 (h.to_string(), n.max(1))
462 } else {
463 (left.clone(), 1)
464 }
465 } else {
466 (left.clone(), 1)
467 };
468 for _ in 0..n {
469 slots.push(RemoteSlot {
470 host: host.clone(),
471 pe_path: pe_path.clone(),
472 });
473 }
474 }
475
476 if slots.is_empty() {
477 return Err("cluster: need at least one host".into());
478 }
479 Ok(RemoteCluster {
480 slots,
481 job_timeout_ms,
482 max_attempts,
483 connect_timeout_ms,
484 })
485 }
486}
487
488#[derive(Clone)]
490pub struct PerlBarrier(pub Arc<Barrier>);
491
492impl fmt::Debug for PerlBarrier {
493 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
494 f.write_str("Barrier")
495 }
496}
497
498#[derive(Debug, Clone)]
500pub struct CaptureResult {
501 pub stdout: String,
502 pub stderr: String,
503 pub exitcode: i64,
504}
505
506#[derive(Debug, Clone)]
508pub struct PerlDataFrame {
509 pub columns: Vec<String>,
510 pub cols: Vec<Vec<PerlValue>>,
511 pub group_by: Option<String>,
513}
514
515impl PerlDataFrame {
516 #[inline]
517 pub fn nrows(&self) -> usize {
518 self.cols.first().map(|c| c.len()).unwrap_or(0)
519 }
520
521 #[inline]
522 pub fn ncols(&self) -> usize {
523 self.columns.len()
524 }
525
526 #[inline]
527 pub fn col_index(&self, name: &str) -> Option<usize> {
528 self.columns.iter().position(|c| c == name)
529 }
530}
531
532#[derive(Debug, Clone)]
534pub(crate) enum HeapObject {
535 Integer(i64),
536 Float(f64),
537 String(String),
538 Bytes(Arc<Vec<u8>>),
539 Array(Vec<PerlValue>),
540 Hash(IndexMap<String, PerlValue>),
541 ArrayRef(Arc<RwLock<Vec<PerlValue>>>),
542 HashRef(Arc<RwLock<IndexMap<String, PerlValue>>>),
543 ScalarRef(Arc<RwLock<PerlValue>>),
544 ScalarBindingRef(String),
546 ArrayBindingRef(String),
548 HashBindingRef(String),
550 CodeRef(Arc<PerlSub>),
551 Regex(Arc<PerlCompiledRegex>, String, String),
553 Blessed(Arc<BlessedRef>),
554 IOHandle(String),
555 Atomic(Arc<Mutex<PerlValue>>),
556 Set(Arc<PerlSet>),
557 ChannelTx(Arc<Sender<PerlValue>>),
558 ChannelRx(Arc<Receiver<PerlValue>>),
559 AsyncTask(Arc<PerlAsyncTask>),
560 Generator(Arc<PerlGenerator>),
561 Deque(Arc<Mutex<VecDeque<PerlValue>>>),
562 Heap(Arc<Mutex<PerlHeap>>),
563 Pipeline(Arc<Mutex<PipelineInner>>),
564 Capture(Arc<CaptureResult>),
565 Ppool(PerlPpool),
566 RemoteCluster(Arc<RemoteCluster>),
567 Barrier(PerlBarrier),
568 SqliteConn(Arc<Mutex<rusqlite::Connection>>),
569 StructInst(Arc<StructInstance>),
570 DataFrame(Arc<Mutex<PerlDataFrame>>),
571 EnumInst(Arc<EnumInstance>),
572 ClassInst(Arc<ClassInstance>),
573 Iterator(Arc<dyn PerlIterator>),
575 ErrnoDual {
577 code: i32,
578 msg: String,
579 },
580}
581
582#[repr(transparent)]
584pub struct PerlValue(pub(crate) u64);
585
586impl Default for PerlValue {
587 fn default() -> Self {
588 Self::UNDEF
589 }
590}
591
592impl Clone for PerlValue {
593 fn clone(&self) -> Self {
594 if nanbox::is_heap(self.0) {
595 let arc = self.heap_arc();
596 match &*arc {
597 HeapObject::Array(v) => {
598 PerlValue::from_heap(Arc::new(HeapObject::Array(v.clone())))
599 }
600 HeapObject::Hash(h) => PerlValue::from_heap(Arc::new(HeapObject::Hash(h.clone()))),
601 HeapObject::String(s) => {
602 PerlValue::from_heap(Arc::new(HeapObject::String(s.clone())))
603 }
604 HeapObject::Integer(n) => PerlValue::integer(*n),
605 HeapObject::Float(f) => PerlValue::float(*f),
606 _ => PerlValue::from_heap(Arc::clone(&arc)),
607 }
608 } else {
609 PerlValue(self.0)
610 }
611 }
612}
613
614impl PerlValue {
615 #[inline]
618 pub fn dup_stack(&self) -> Self {
619 if nanbox::is_heap(self.0) {
620 let arc = self.heap_arc();
621 match &*arc {
622 HeapObject::Array(_) | HeapObject::Hash(_) => {
623 PerlValue::from_heap(Arc::clone(&arc))
624 }
625 _ => self.clone(),
626 }
627 } else {
628 PerlValue(self.0)
629 }
630 }
631
632 #[inline]
643 pub fn shallow_clone(&self) -> Self {
644 if nanbox::is_heap(self.0) {
645 PerlValue::from_heap(self.heap_arc())
646 } else {
647 PerlValue(self.0)
648 }
649 }
650}
651
652impl Drop for PerlValue {
653 fn drop(&mut self) {
654 if nanbox::is_heap(self.0) {
655 unsafe {
656 let p = nanbox::decode_heap_ptr::<HeapObject>(self.0) as *mut HeapObject;
657 drop(Arc::from_raw(p));
658 }
659 }
660 }
661}
662
663impl fmt::Debug for PerlValue {
664 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
665 write!(f, "{self}")
666 }
667}
668
669#[derive(Clone)]
672pub struct PerlPpool(pub(crate) Arc<crate::ppool::PpoolInner>);
673
674impl fmt::Debug for PerlPpool {
675 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
676 f.write_str("PerlPpool")
677 }
678}
679
680#[derive(Debug, Clone, PartialEq, Eq)]
683pub struct FibLikeRecAddPattern {
684 pub param: String,
686 pub base_k: i64,
688 pub left_k: i64,
690 pub right_k: i64,
692}
693
694#[derive(Debug, Clone)]
695pub struct PerlSub {
696 pub name: String,
697 pub params: Vec<SubSigParam>,
698 pub body: Block,
699 pub closure_env: Option<Vec<(String, PerlValue)>>,
701 pub prototype: Option<String>,
703 pub fib_like: Option<FibLikeRecAddPattern>,
706}
707
708#[derive(Debug, Clone)]
710pub enum PipelineOp {
711 Filter(Arc<PerlSub>),
712 Map(Arc<PerlSub>),
713 Tap(Arc<PerlSub>),
715 Take(i64),
716 PMap {
718 sub: Arc<PerlSub>,
719 progress: bool,
720 },
721 PGrep {
723 sub: Arc<PerlSub>,
724 progress: bool,
725 },
726 PFor {
728 sub: Arc<PerlSub>,
729 progress: bool,
730 },
731 PMapChunked {
733 chunk: i64,
734 sub: Arc<PerlSub>,
735 progress: bool,
736 },
737 PSort {
739 cmp: Option<Arc<PerlSub>>,
740 progress: bool,
741 },
742 PCache {
744 sub: Arc<PerlSub>,
745 progress: bool,
746 },
747 PReduce {
749 sub: Arc<PerlSub>,
750 progress: bool,
751 },
752 PReduceInit {
754 init: PerlValue,
755 sub: Arc<PerlSub>,
756 progress: bool,
757 },
758 PMapReduce {
760 map: Arc<PerlSub>,
761 reduce: Arc<PerlSub>,
762 progress: bool,
763 },
764}
765
766#[derive(Debug)]
767pub struct PipelineInner {
768 pub source: Vec<PerlValue>,
769 pub ops: Vec<PipelineOp>,
770 pub has_scalar_terminal: bool,
772 pub par_stream: bool,
774 pub streaming: bool,
777 pub streaming_workers: usize,
779 pub streaming_buffer: usize,
781}
782
783#[derive(Debug)]
784pub struct BlessedRef {
785 pub class: String,
786 pub data: RwLock<PerlValue>,
787 pub(crate) suppress_destroy_queue: AtomicBool,
789}
790
791impl BlessedRef {
792 pub(crate) fn new_blessed(class: String, data: PerlValue) -> Self {
793 Self {
794 class,
795 data: RwLock::new(data),
796 suppress_destroy_queue: AtomicBool::new(false),
797 }
798 }
799
800 pub(crate) fn new_for_destroy_invocant(class: String, data: PerlValue) -> Self {
802 Self {
803 class,
804 data: RwLock::new(data),
805 suppress_destroy_queue: AtomicBool::new(true),
806 }
807 }
808}
809
810impl Clone for BlessedRef {
811 fn clone(&self) -> Self {
812 Self {
813 class: self.class.clone(),
814 data: RwLock::new(self.data.read().clone()),
815 suppress_destroy_queue: AtomicBool::new(false),
816 }
817 }
818}
819
820impl Drop for BlessedRef {
821 fn drop(&mut self) {
822 if self.suppress_destroy_queue.load(AtomicOrdering::Acquire) {
823 return;
824 }
825 let inner = {
826 let mut g = self.data.write();
827 std::mem::take(&mut *g)
828 };
829 crate::pending_destroy::enqueue(self.class.clone(), inner);
830 }
831}
832
833#[derive(Debug)]
835pub struct StructInstance {
836 pub def: Arc<StructDef>,
837 pub values: RwLock<Vec<PerlValue>>,
838}
839
840impl StructInstance {
841 pub fn new(def: Arc<StructDef>, values: Vec<PerlValue>) -> Self {
843 Self {
844 def,
845 values: RwLock::new(values),
846 }
847 }
848
849 #[inline]
851 pub fn get_field(&self, idx: usize) -> Option<PerlValue> {
852 self.values.read().get(idx).cloned()
853 }
854
855 #[inline]
857 pub fn set_field(&self, idx: usize, val: PerlValue) {
858 if let Some(slot) = self.values.write().get_mut(idx) {
859 *slot = val;
860 }
861 }
862
863 #[inline]
865 pub fn get_values(&self) -> Vec<PerlValue> {
866 self.values.read().clone()
867 }
868}
869
870impl Clone for StructInstance {
871 fn clone(&self) -> Self {
872 Self {
873 def: Arc::clone(&self.def),
874 values: RwLock::new(self.values.read().clone()),
875 }
876 }
877}
878
879#[derive(Debug)]
881pub struct EnumInstance {
882 pub def: Arc<EnumDef>,
883 pub variant_idx: usize,
884 pub data: PerlValue,
886}
887
888impl EnumInstance {
889 pub fn new(def: Arc<EnumDef>, variant_idx: usize, data: PerlValue) -> Self {
890 Self {
891 def,
892 variant_idx,
893 data,
894 }
895 }
896
897 pub fn variant_name(&self) -> &str {
898 &self.def.variants[self.variant_idx].name
899 }
900}
901
902impl Clone for EnumInstance {
903 fn clone(&self) -> Self {
904 Self {
905 def: Arc::clone(&self.def),
906 variant_idx: self.variant_idx,
907 data: self.data.clone(),
908 }
909 }
910}
911
912#[derive(Debug)]
914pub struct ClassInstance {
915 pub def: Arc<ClassDef>,
916 pub values: RwLock<Vec<PerlValue>>,
917}
918
919impl ClassInstance {
920 pub fn new(def: Arc<ClassDef>, values: Vec<PerlValue>) -> Self {
921 Self {
922 def,
923 values: RwLock::new(values),
924 }
925 }
926
927 #[inline]
928 pub fn get_field(&self, idx: usize) -> Option<PerlValue> {
929 self.values.read().get(idx).cloned()
930 }
931
932 #[inline]
933 pub fn set_field(&self, idx: usize, val: PerlValue) {
934 if let Some(slot) = self.values.write().get_mut(idx) {
935 *slot = val;
936 }
937 }
938
939 #[inline]
940 pub fn get_values(&self) -> Vec<PerlValue> {
941 self.values.read().clone()
942 }
943
944 pub fn get_field_by_name(&self, name: &str) -> Option<PerlValue> {
946 self.def
947 .field_index(name)
948 .and_then(|idx| self.get_field(idx))
949 }
950
951 pub fn set_field_by_name(&self, name: &str, val: PerlValue) -> bool {
953 if let Some(idx) = self.def.field_index(name) {
954 self.set_field(idx, val);
955 true
956 } else {
957 false
958 }
959 }
960}
961
962impl Clone for ClassInstance {
963 fn clone(&self) -> Self {
964 Self {
965 def: Arc::clone(&self.def),
966 values: RwLock::new(self.values.read().clone()),
967 }
968 }
969}
970
971impl PerlValue {
972 pub const UNDEF: PerlValue = PerlValue(nanbox::encode_imm_undef());
973
974 #[inline]
975 fn from_heap(arc: Arc<HeapObject>) -> PerlValue {
976 let ptr = Arc::into_raw(arc);
977 PerlValue(nanbox::encode_heap_ptr(ptr))
978 }
979
980 #[inline]
981 pub(crate) fn heap_arc(&self) -> Arc<HeapObject> {
982 debug_assert!(nanbox::is_heap(self.0));
983 unsafe {
984 let p = nanbox::decode_heap_ptr::<HeapObject>(self.0);
985 Arc::increment_strong_count(p);
986 Arc::from_raw(p as *mut HeapObject)
987 }
988 }
989
990 #[inline]
995 pub(crate) unsafe fn heap_ref(&self) -> &HeapObject {
996 &*nanbox::decode_heap_ptr::<HeapObject>(self.0)
997 }
998
999 #[inline]
1000 pub(crate) fn with_heap<R>(&self, f: impl FnOnce(&HeapObject) -> R) -> Option<R> {
1001 if !nanbox::is_heap(self.0) {
1002 return None;
1003 }
1004 Some(f(unsafe { self.heap_ref() }))
1006 }
1007
1008 #[inline]
1010 pub(crate) fn raw_bits(&self) -> u64 {
1011 self.0
1012 }
1013
1014 #[inline]
1016 pub(crate) fn from_raw_bits(bits: u64) -> Self {
1017 Self(bits)
1018 }
1019
1020 #[inline]
1022 pub fn is_integer_like(&self) -> bool {
1023 nanbox::as_imm_int32(self.0).is_some()
1024 || matches!(
1025 self.with_heap(|h| matches!(h, HeapObject::Integer(_))),
1026 Some(true)
1027 )
1028 }
1029
1030 #[inline]
1032 pub fn is_float_like(&self) -> bool {
1033 nanbox::is_raw_float_bits(self.0)
1034 || matches!(
1035 self.with_heap(|h| matches!(h, HeapObject::Float(_))),
1036 Some(true)
1037 )
1038 }
1039
1040 #[inline]
1042 pub fn is_string_like(&self) -> bool {
1043 matches!(
1044 self.with_heap(|h| matches!(h, HeapObject::String(_))),
1045 Some(true)
1046 )
1047 }
1048
1049 #[inline]
1050 pub fn integer(n: i64) -> Self {
1051 if n >= i32::MIN as i64 && n <= i32::MAX as i64 {
1052 PerlValue(nanbox::encode_imm_int32(n as i32))
1053 } else {
1054 Self::from_heap(Arc::new(HeapObject::Integer(n)))
1055 }
1056 }
1057
1058 #[inline]
1059 pub fn float(f: f64) -> Self {
1060 if nanbox::float_needs_box(f) {
1061 Self::from_heap(Arc::new(HeapObject::Float(f)))
1062 } else {
1063 PerlValue(f.to_bits())
1064 }
1065 }
1066
1067 #[inline]
1068 pub fn string(s: String) -> Self {
1069 Self::from_heap(Arc::new(HeapObject::String(s)))
1070 }
1071
1072 #[inline]
1073 pub fn bytes(b: Arc<Vec<u8>>) -> Self {
1074 Self::from_heap(Arc::new(HeapObject::Bytes(b)))
1075 }
1076
1077 #[inline]
1078 pub fn array(v: Vec<PerlValue>) -> Self {
1079 Self::from_heap(Arc::new(HeapObject::Array(v)))
1080 }
1081
1082 #[inline]
1084 pub fn iterator(it: Arc<dyn PerlIterator>) -> Self {
1085 Self::from_heap(Arc::new(HeapObject::Iterator(it)))
1086 }
1087
1088 #[inline]
1090 pub fn is_iterator(&self) -> bool {
1091 if !nanbox::is_heap(self.0) {
1092 return false;
1093 }
1094 matches!(unsafe { self.heap_ref() }, HeapObject::Iterator(_))
1095 }
1096
1097 pub fn into_iterator(&self) -> Arc<dyn PerlIterator> {
1099 if nanbox::is_heap(self.0) {
1100 if let HeapObject::Iterator(it) = &*self.heap_arc() {
1101 return Arc::clone(it);
1102 }
1103 }
1104 panic!("into_iterator on non-iterator value");
1105 }
1106
1107 #[inline]
1108 pub fn hash(h: IndexMap<String, PerlValue>) -> Self {
1109 Self::from_heap(Arc::new(HeapObject::Hash(h)))
1110 }
1111
1112 #[inline]
1113 pub fn array_ref(a: Arc<RwLock<Vec<PerlValue>>>) -> Self {
1114 Self::from_heap(Arc::new(HeapObject::ArrayRef(a)))
1115 }
1116
1117 #[inline]
1118 pub fn hash_ref(h: Arc<RwLock<IndexMap<String, PerlValue>>>) -> Self {
1119 Self::from_heap(Arc::new(HeapObject::HashRef(h)))
1120 }
1121
1122 #[inline]
1123 pub fn scalar_ref(r: Arc<RwLock<PerlValue>>) -> Self {
1124 Self::from_heap(Arc::new(HeapObject::ScalarRef(r)))
1125 }
1126
1127 #[inline]
1128 pub fn scalar_binding_ref(name: String) -> Self {
1129 Self::from_heap(Arc::new(HeapObject::ScalarBindingRef(name)))
1130 }
1131
1132 #[inline]
1133 pub fn array_binding_ref(name: String) -> Self {
1134 Self::from_heap(Arc::new(HeapObject::ArrayBindingRef(name)))
1135 }
1136
1137 #[inline]
1138 pub fn hash_binding_ref(name: String) -> Self {
1139 Self::from_heap(Arc::new(HeapObject::HashBindingRef(name)))
1140 }
1141
1142 #[inline]
1143 pub fn code_ref(c: Arc<PerlSub>) -> Self {
1144 Self::from_heap(Arc::new(HeapObject::CodeRef(c)))
1145 }
1146
1147 #[inline]
1148 pub fn as_code_ref(&self) -> Option<Arc<PerlSub>> {
1149 self.with_heap(|h| match h {
1150 HeapObject::CodeRef(sub) => Some(Arc::clone(sub)),
1151 _ => None,
1152 })
1153 .flatten()
1154 }
1155
1156 #[inline]
1157 pub fn as_regex(&self) -> Option<Arc<PerlCompiledRegex>> {
1158 self.with_heap(|h| match h {
1159 HeapObject::Regex(re, _, _) => Some(Arc::clone(re)),
1160 _ => None,
1161 })
1162 .flatten()
1163 }
1164
1165 #[inline]
1166 pub fn as_blessed_ref(&self) -> Option<Arc<BlessedRef>> {
1167 self.with_heap(|h| match h {
1168 HeapObject::Blessed(b) => Some(Arc::clone(b)),
1169 _ => None,
1170 })
1171 .flatten()
1172 }
1173
1174 #[inline]
1176 pub fn hash_get(&self, key: &str) -> Option<PerlValue> {
1177 self.with_heap(|h| match h {
1178 HeapObject::Hash(h) => h.get(key).cloned(),
1179 _ => None,
1180 })
1181 .flatten()
1182 }
1183
1184 #[inline]
1185 pub fn is_undef(&self) -> bool {
1186 nanbox::is_imm_undef(self.0)
1187 }
1188
1189 pub fn is_simple_scalar(&self) -> bool {
1194 if self.is_undef() {
1195 return true;
1196 }
1197 if !nanbox::is_heap(self.0) {
1198 return true; }
1200 matches!(
1201 unsafe { self.heap_ref() },
1202 HeapObject::Integer(_)
1203 | HeapObject::Float(_)
1204 | HeapObject::String(_)
1205 | HeapObject::Bytes(_)
1206 )
1207 }
1208
1209 #[inline]
1211 pub fn as_integer(&self) -> Option<i64> {
1212 if let Some(n) = nanbox::as_imm_int32(self.0) {
1213 return Some(n as i64);
1214 }
1215 if nanbox::is_raw_float_bits(self.0) {
1216 return None;
1217 }
1218 self.with_heap(|h| match h {
1219 HeapObject::Integer(n) => Some(*n),
1220 _ => None,
1221 })
1222 .flatten()
1223 }
1224
1225 #[inline]
1226 pub fn as_float(&self) -> Option<f64> {
1227 if nanbox::is_raw_float_bits(self.0) {
1228 return Some(f64::from_bits(self.0));
1229 }
1230 self.with_heap(|h| match h {
1231 HeapObject::Float(f) => Some(*f),
1232 _ => None,
1233 })
1234 .flatten()
1235 }
1236
1237 #[inline]
1238 pub fn as_array_vec(&self) -> Option<Vec<PerlValue>> {
1239 self.with_heap(|h| match h {
1240 HeapObject::Array(v) => Some(v.clone()),
1241 _ => None,
1242 })
1243 .flatten()
1244 }
1245
1246 pub fn map_flatten_outputs(&self, peel_array_ref: bool) -> Vec<PerlValue> {
1250 if let Some(a) = self.as_array_vec() {
1251 return a;
1252 }
1253 if peel_array_ref {
1254 if let Some(r) = self.as_array_ref() {
1255 return r.read().clone();
1256 }
1257 }
1258 if self.is_iterator() {
1259 return self.into_iterator().collect_all();
1260 }
1261 vec![self.clone()]
1262 }
1263
1264 #[inline]
1265 pub fn as_hash_map(&self) -> Option<IndexMap<String, PerlValue>> {
1266 self.with_heap(|h| match h {
1267 HeapObject::Hash(h) => Some(h.clone()),
1268 _ => None,
1269 })
1270 .flatten()
1271 }
1272
1273 #[inline]
1274 pub fn as_bytes_arc(&self) -> Option<Arc<Vec<u8>>> {
1275 self.with_heap(|h| match h {
1276 HeapObject::Bytes(b) => Some(Arc::clone(b)),
1277 _ => None,
1278 })
1279 .flatten()
1280 }
1281
1282 #[inline]
1283 pub fn as_async_task(&self) -> Option<Arc<PerlAsyncTask>> {
1284 self.with_heap(|h| match h {
1285 HeapObject::AsyncTask(t) => Some(Arc::clone(t)),
1286 _ => None,
1287 })
1288 .flatten()
1289 }
1290
1291 #[inline]
1292 pub fn as_generator(&self) -> Option<Arc<PerlGenerator>> {
1293 self.with_heap(|h| match h {
1294 HeapObject::Generator(g) => Some(Arc::clone(g)),
1295 _ => None,
1296 })
1297 .flatten()
1298 }
1299
1300 #[inline]
1301 pub fn as_atomic_arc(&self) -> Option<Arc<Mutex<PerlValue>>> {
1302 self.with_heap(|h| match h {
1303 HeapObject::Atomic(a) => Some(Arc::clone(a)),
1304 _ => None,
1305 })
1306 .flatten()
1307 }
1308
1309 #[inline]
1310 pub fn as_io_handle_name(&self) -> Option<String> {
1311 self.with_heap(|h| match h {
1312 HeapObject::IOHandle(n) => Some(n.clone()),
1313 _ => None,
1314 })
1315 .flatten()
1316 }
1317
1318 #[inline]
1319 pub fn as_sqlite_conn(&self) -> Option<Arc<Mutex<rusqlite::Connection>>> {
1320 self.with_heap(|h| match h {
1321 HeapObject::SqliteConn(c) => Some(Arc::clone(c)),
1322 _ => None,
1323 })
1324 .flatten()
1325 }
1326
1327 #[inline]
1328 pub fn as_struct_inst(&self) -> Option<Arc<StructInstance>> {
1329 self.with_heap(|h| match h {
1330 HeapObject::StructInst(s) => Some(Arc::clone(s)),
1331 _ => None,
1332 })
1333 .flatten()
1334 }
1335
1336 #[inline]
1337 pub fn as_enum_inst(&self) -> Option<Arc<EnumInstance>> {
1338 self.with_heap(|h| match h {
1339 HeapObject::EnumInst(e) => Some(Arc::clone(e)),
1340 _ => None,
1341 })
1342 .flatten()
1343 }
1344
1345 #[inline]
1346 pub fn as_class_inst(&self) -> Option<Arc<ClassInstance>> {
1347 self.with_heap(|h| match h {
1348 HeapObject::ClassInst(c) => Some(Arc::clone(c)),
1349 _ => None,
1350 })
1351 .flatten()
1352 }
1353
1354 #[inline]
1355 pub fn as_dataframe(&self) -> Option<Arc<Mutex<PerlDataFrame>>> {
1356 self.with_heap(|h| match h {
1357 HeapObject::DataFrame(d) => Some(Arc::clone(d)),
1358 _ => None,
1359 })
1360 .flatten()
1361 }
1362
1363 #[inline]
1364 pub fn as_deque(&self) -> Option<Arc<Mutex<VecDeque<PerlValue>>>> {
1365 self.with_heap(|h| match h {
1366 HeapObject::Deque(d) => Some(Arc::clone(d)),
1367 _ => None,
1368 })
1369 .flatten()
1370 }
1371
1372 #[inline]
1373 pub fn as_heap_pq(&self) -> Option<Arc<Mutex<PerlHeap>>> {
1374 self.with_heap(|h| match h {
1375 HeapObject::Heap(h) => Some(Arc::clone(h)),
1376 _ => None,
1377 })
1378 .flatten()
1379 }
1380
1381 #[inline]
1382 pub fn as_pipeline(&self) -> Option<Arc<Mutex<PipelineInner>>> {
1383 self.with_heap(|h| match h {
1384 HeapObject::Pipeline(p) => Some(Arc::clone(p)),
1385 _ => None,
1386 })
1387 .flatten()
1388 }
1389
1390 #[inline]
1391 pub fn as_capture(&self) -> Option<Arc<CaptureResult>> {
1392 self.with_heap(|h| match h {
1393 HeapObject::Capture(c) => Some(Arc::clone(c)),
1394 _ => None,
1395 })
1396 .flatten()
1397 }
1398
1399 #[inline]
1400 pub fn as_ppool(&self) -> Option<PerlPpool> {
1401 self.with_heap(|h| match h {
1402 HeapObject::Ppool(p) => Some(p.clone()),
1403 _ => None,
1404 })
1405 .flatten()
1406 }
1407
1408 #[inline]
1409 pub fn as_remote_cluster(&self) -> Option<Arc<RemoteCluster>> {
1410 self.with_heap(|h| match h {
1411 HeapObject::RemoteCluster(c) => Some(Arc::clone(c)),
1412 _ => None,
1413 })
1414 .flatten()
1415 }
1416
1417 #[inline]
1418 pub fn as_barrier(&self) -> Option<PerlBarrier> {
1419 self.with_heap(|h| match h {
1420 HeapObject::Barrier(b) => Some(b.clone()),
1421 _ => None,
1422 })
1423 .flatten()
1424 }
1425
1426 #[inline]
1427 pub fn as_channel_tx(&self) -> Option<Arc<Sender<PerlValue>>> {
1428 self.with_heap(|h| match h {
1429 HeapObject::ChannelTx(t) => Some(Arc::clone(t)),
1430 _ => None,
1431 })
1432 .flatten()
1433 }
1434
1435 #[inline]
1436 pub fn as_channel_rx(&self) -> Option<Arc<Receiver<PerlValue>>> {
1437 self.with_heap(|h| match h {
1438 HeapObject::ChannelRx(r) => Some(Arc::clone(r)),
1439 _ => None,
1440 })
1441 .flatten()
1442 }
1443
1444 #[inline]
1445 pub fn as_scalar_ref(&self) -> Option<Arc<RwLock<PerlValue>>> {
1446 self.with_heap(|h| match h {
1447 HeapObject::ScalarRef(r) => Some(Arc::clone(r)),
1448 _ => None,
1449 })
1450 .flatten()
1451 }
1452
1453 #[inline]
1455 pub fn as_scalar_binding_name(&self) -> Option<String> {
1456 self.with_heap(|h| match h {
1457 HeapObject::ScalarBindingRef(s) => Some(s.clone()),
1458 _ => None,
1459 })
1460 .flatten()
1461 }
1462
1463 #[inline]
1465 pub fn as_array_binding_name(&self) -> Option<String> {
1466 self.with_heap(|h| match h {
1467 HeapObject::ArrayBindingRef(s) => Some(s.clone()),
1468 _ => None,
1469 })
1470 .flatten()
1471 }
1472
1473 #[inline]
1475 pub fn as_hash_binding_name(&self) -> Option<String> {
1476 self.with_heap(|h| match h {
1477 HeapObject::HashBindingRef(s) => Some(s.clone()),
1478 _ => None,
1479 })
1480 .flatten()
1481 }
1482
1483 #[inline]
1484 pub fn as_array_ref(&self) -> Option<Arc<RwLock<Vec<PerlValue>>>> {
1485 self.with_heap(|h| match h {
1486 HeapObject::ArrayRef(r) => Some(Arc::clone(r)),
1487 _ => None,
1488 })
1489 .flatten()
1490 }
1491
1492 #[inline]
1493 pub fn as_hash_ref(&self) -> Option<Arc<RwLock<IndexMap<String, PerlValue>>>> {
1494 self.with_heap(|h| match h {
1495 HeapObject::HashRef(r) => Some(Arc::clone(r)),
1496 _ => None,
1497 })
1498 .flatten()
1499 }
1500
1501 #[inline]
1503 pub fn is_mysync_deque_or_heap(&self) -> bool {
1504 matches!(
1505 self.with_heap(|h| matches!(h, HeapObject::Deque(_) | HeapObject::Heap(_))),
1506 Some(true)
1507 )
1508 }
1509
1510 #[inline]
1511 pub fn regex(rx: Arc<PerlCompiledRegex>, pattern_src: String, flags: String) -> Self {
1512 Self::from_heap(Arc::new(HeapObject::Regex(rx, pattern_src, flags)))
1513 }
1514
1515 #[inline]
1517 pub fn regex_src_and_flags(&self) -> Option<(String, String)> {
1518 self.with_heap(|h| match h {
1519 HeapObject::Regex(_, pat, fl) => Some((pat.clone(), fl.clone())),
1520 _ => None,
1521 })
1522 .flatten()
1523 }
1524
1525 #[inline]
1526 pub fn blessed(b: Arc<BlessedRef>) -> Self {
1527 Self::from_heap(Arc::new(HeapObject::Blessed(b)))
1528 }
1529
1530 #[inline]
1531 pub fn io_handle(name: String) -> Self {
1532 Self::from_heap(Arc::new(HeapObject::IOHandle(name)))
1533 }
1534
1535 #[inline]
1536 pub fn atomic(a: Arc<Mutex<PerlValue>>) -> Self {
1537 Self::from_heap(Arc::new(HeapObject::Atomic(a)))
1538 }
1539
1540 #[inline]
1541 pub fn set(s: Arc<PerlSet>) -> Self {
1542 Self::from_heap(Arc::new(HeapObject::Set(s)))
1543 }
1544
1545 #[inline]
1546 pub fn channel_tx(tx: Arc<Sender<PerlValue>>) -> Self {
1547 Self::from_heap(Arc::new(HeapObject::ChannelTx(tx)))
1548 }
1549
1550 #[inline]
1551 pub fn channel_rx(rx: Arc<Receiver<PerlValue>>) -> Self {
1552 Self::from_heap(Arc::new(HeapObject::ChannelRx(rx)))
1553 }
1554
1555 #[inline]
1556 pub fn async_task(t: Arc<PerlAsyncTask>) -> Self {
1557 Self::from_heap(Arc::new(HeapObject::AsyncTask(t)))
1558 }
1559
1560 #[inline]
1561 pub fn generator(g: Arc<PerlGenerator>) -> Self {
1562 Self::from_heap(Arc::new(HeapObject::Generator(g)))
1563 }
1564
1565 #[inline]
1566 pub fn deque(d: Arc<Mutex<VecDeque<PerlValue>>>) -> Self {
1567 Self::from_heap(Arc::new(HeapObject::Deque(d)))
1568 }
1569
1570 #[inline]
1571 pub fn heap(h: Arc<Mutex<PerlHeap>>) -> Self {
1572 Self::from_heap(Arc::new(HeapObject::Heap(h)))
1573 }
1574
1575 #[inline]
1576 pub fn pipeline(p: Arc<Mutex<PipelineInner>>) -> Self {
1577 Self::from_heap(Arc::new(HeapObject::Pipeline(p)))
1578 }
1579
1580 #[inline]
1581 pub fn capture(c: Arc<CaptureResult>) -> Self {
1582 Self::from_heap(Arc::new(HeapObject::Capture(c)))
1583 }
1584
1585 #[inline]
1586 pub fn ppool(p: PerlPpool) -> Self {
1587 Self::from_heap(Arc::new(HeapObject::Ppool(p)))
1588 }
1589
1590 #[inline]
1591 pub fn remote_cluster(c: Arc<RemoteCluster>) -> Self {
1592 Self::from_heap(Arc::new(HeapObject::RemoteCluster(c)))
1593 }
1594
1595 #[inline]
1596 pub fn barrier(b: PerlBarrier) -> Self {
1597 Self::from_heap(Arc::new(HeapObject::Barrier(b)))
1598 }
1599
1600 #[inline]
1601 pub fn sqlite_conn(c: Arc<Mutex<rusqlite::Connection>>) -> Self {
1602 Self::from_heap(Arc::new(HeapObject::SqliteConn(c)))
1603 }
1604
1605 #[inline]
1606 pub fn struct_inst(s: Arc<StructInstance>) -> Self {
1607 Self::from_heap(Arc::new(HeapObject::StructInst(s)))
1608 }
1609
1610 #[inline]
1611 pub fn enum_inst(e: Arc<EnumInstance>) -> Self {
1612 Self::from_heap(Arc::new(HeapObject::EnumInst(e)))
1613 }
1614
1615 #[inline]
1616 pub fn class_inst(c: Arc<ClassInstance>) -> Self {
1617 Self::from_heap(Arc::new(HeapObject::ClassInst(c)))
1618 }
1619
1620 #[inline]
1621 pub fn dataframe(df: Arc<Mutex<PerlDataFrame>>) -> Self {
1622 Self::from_heap(Arc::new(HeapObject::DataFrame(df)))
1623 }
1624
1625 #[inline]
1627 pub fn errno_dual(code: i32, msg: String) -> Self {
1628 Self::from_heap(Arc::new(HeapObject::ErrnoDual { code, msg }))
1629 }
1630
1631 #[inline]
1633 pub(crate) fn errno_dual_parts(&self) -> Option<(i32, String)> {
1634 if !nanbox::is_heap(self.0) {
1635 return None;
1636 }
1637 match unsafe { self.heap_ref() } {
1638 HeapObject::ErrnoDual { code, msg } => Some((*code, msg.clone())),
1639 _ => None,
1640 }
1641 }
1642
1643 #[inline]
1645 pub fn as_str(&self) -> Option<String> {
1646 if !nanbox::is_heap(self.0) {
1647 return None;
1648 }
1649 match unsafe { self.heap_ref() } {
1650 HeapObject::String(s) => Some(s.clone()),
1651 _ => None,
1652 }
1653 }
1654
1655 #[inline]
1656 pub fn append_to(&self, buf: &mut String) {
1657 if nanbox::is_imm_undef(self.0) {
1658 return;
1659 }
1660 if let Some(n) = nanbox::as_imm_int32(self.0) {
1661 let mut b = itoa::Buffer::new();
1662 buf.push_str(b.format(n));
1663 return;
1664 }
1665 if nanbox::is_raw_float_bits(self.0) {
1666 buf.push_str(&format_float(f64::from_bits(self.0)));
1667 return;
1668 }
1669 match unsafe { self.heap_ref() } {
1670 HeapObject::String(s) => buf.push_str(s),
1671 HeapObject::ErrnoDual { msg, .. } => buf.push_str(msg),
1672 HeapObject::Bytes(b) => buf.push_str(&decode_utf8_or_latin1(b)),
1673 HeapObject::Atomic(arc) => arc.lock().append_to(buf),
1674 HeapObject::Set(s) => {
1675 buf.push('{');
1676 let mut first = true;
1677 for v in s.values() {
1678 if !first {
1679 buf.push(',');
1680 }
1681 first = false;
1682 v.append_to(buf);
1683 }
1684 buf.push('}');
1685 }
1686 HeapObject::ChannelTx(_) => buf.push_str("PCHANNEL::Tx"),
1687 HeapObject::ChannelRx(_) => buf.push_str("PCHANNEL::Rx"),
1688 HeapObject::AsyncTask(_) => buf.push_str("AsyncTask"),
1689 HeapObject::Generator(_) => buf.push_str("Generator"),
1690 HeapObject::Pipeline(_) => buf.push_str("Pipeline"),
1691 HeapObject::DataFrame(d) => {
1692 let g = d.lock();
1693 buf.push_str(&format!("DataFrame({}x{})", g.nrows(), g.ncols()));
1694 }
1695 HeapObject::Capture(_) => buf.push_str("Capture"),
1696 HeapObject::Ppool(_) => buf.push_str("Ppool"),
1697 HeapObject::RemoteCluster(_) => buf.push_str("Cluster"),
1698 HeapObject::Barrier(_) => buf.push_str("Barrier"),
1699 HeapObject::SqliteConn(_) => buf.push_str("SqliteConn"),
1700 HeapObject::StructInst(s) => buf.push_str(&s.def.name),
1701 _ => buf.push_str(&self.to_string()),
1702 }
1703 }
1704
1705 #[inline]
1706 pub fn unwrap_atomic(&self) -> PerlValue {
1707 if !nanbox::is_heap(self.0) {
1708 return self.clone();
1709 }
1710 match unsafe { self.heap_ref() } {
1711 HeapObject::Atomic(a) => a.lock().clone(),
1712 _ => self.clone(),
1713 }
1714 }
1715
1716 #[inline]
1717 pub fn is_atomic(&self) -> bool {
1718 if !nanbox::is_heap(self.0) {
1719 return false;
1720 }
1721 matches!(unsafe { self.heap_ref() }, HeapObject::Atomic(_))
1722 }
1723
1724 #[inline]
1725 pub fn is_true(&self) -> bool {
1726 if nanbox::is_imm_undef(self.0) {
1727 return false;
1728 }
1729 if let Some(n) = nanbox::as_imm_int32(self.0) {
1730 return n != 0;
1731 }
1732 if nanbox::is_raw_float_bits(self.0) {
1733 return f64::from_bits(self.0) != 0.0;
1734 }
1735 match unsafe { self.heap_ref() } {
1736 HeapObject::ErrnoDual { code, msg } => *code != 0 || !msg.is_empty(),
1737 HeapObject::String(s) => !s.is_empty() && s != "0",
1738 HeapObject::Bytes(b) => !b.is_empty(),
1739 HeapObject::Array(a) => !a.is_empty(),
1740 HeapObject::Hash(h) => !h.is_empty(),
1741 HeapObject::Atomic(arc) => arc.lock().is_true(),
1742 HeapObject::Set(s) => !s.is_empty(),
1743 HeapObject::Deque(d) => !d.lock().is_empty(),
1744 HeapObject::Heap(h) => !h.lock().items.is_empty(),
1745 HeapObject::DataFrame(d) => d.lock().nrows() > 0,
1746 HeapObject::Pipeline(_) | HeapObject::Capture(_) => true,
1747 _ => true,
1748 }
1749 }
1750
1751 #[inline]
1754 pub(crate) fn concat_append_owned(self, rhs: &PerlValue) -> PerlValue {
1755 let mut s = self.into_string();
1756 rhs.append_to(&mut s);
1757 PerlValue::string(s)
1758 }
1759
1760 #[inline]
1766 pub(crate) fn try_concat_repeat_inplace(&mut self, rhs: &str, n: usize) -> bool {
1767 if !nanbox::is_heap(self.0) || n == 0 {
1768 return n == 0 && nanbox::is_heap(self.0);
1770 }
1771 unsafe {
1772 if !matches!(self.heap_ref(), HeapObject::String(_)) {
1773 return false;
1774 }
1775 let raw = nanbox::decode_heap_ptr::<HeapObject>(self.0) as *mut HeapObject
1776 as *const HeapObject;
1777 let mut arc: Arc<HeapObject> = Arc::from_raw(raw);
1778 let did = if let Some(HeapObject::String(s)) = Arc::get_mut(&mut arc) {
1779 if !rhs.is_empty() {
1780 s.reserve(rhs.len().saturating_mul(n));
1781 for _ in 0..n {
1782 s.push_str(rhs);
1783 }
1784 }
1785 true
1786 } else {
1787 false
1788 };
1789 let restored = Arc::into_raw(arc);
1790 self.0 = nanbox::encode_heap_ptr(restored);
1791 did
1792 }
1793 }
1794
1795 #[inline]
1805 pub(crate) fn try_concat_append_inplace(&mut self, rhs: &PerlValue) -> bool {
1806 if !nanbox::is_heap(self.0) {
1807 return false;
1808 }
1809 unsafe {
1813 if !matches!(self.heap_ref(), HeapObject::String(_)) {
1814 return false;
1815 }
1816 let raw = nanbox::decode_heap_ptr::<HeapObject>(self.0) as *mut HeapObject
1819 as *const HeapObject;
1820 let mut arc: Arc<HeapObject> = Arc::from_raw(raw);
1821 let did_append = if let Some(HeapObject::String(s)) = Arc::get_mut(&mut arc) {
1822 rhs.append_to(s);
1823 true
1824 } else {
1825 false
1826 };
1827 let restored = Arc::into_raw(arc);
1830 self.0 = nanbox::encode_heap_ptr(restored);
1831 did_append
1832 }
1833 }
1834
1835 #[inline]
1836 pub fn into_string(self) -> String {
1837 let bits = self.0;
1838 std::mem::forget(self);
1839 if nanbox::is_imm_undef(bits) {
1840 return String::new();
1841 }
1842 if let Some(n) = nanbox::as_imm_int32(bits) {
1843 let mut buf = itoa::Buffer::new();
1844 return buf.format(n).to_owned();
1845 }
1846 if nanbox::is_raw_float_bits(bits) {
1847 return format_float(f64::from_bits(bits));
1848 }
1849 if nanbox::is_heap(bits) {
1850 unsafe {
1851 let arc =
1852 Arc::from_raw(nanbox::decode_heap_ptr::<HeapObject>(bits) as *mut HeapObject);
1853 match Arc::try_unwrap(arc) {
1854 Ok(HeapObject::String(s)) => return s,
1855 Ok(o) => return PerlValue::from_heap(Arc::new(o)).to_string(),
1856 Err(arc) => {
1857 return match &*arc {
1858 HeapObject::String(s) => s.clone(),
1859 _ => PerlValue::from_heap(Arc::clone(&arc)).to_string(),
1860 };
1861 }
1862 }
1863 }
1864 }
1865 String::new()
1866 }
1867
1868 #[inline]
1869 pub fn as_str_or_empty(&self) -> String {
1870 if !nanbox::is_heap(self.0) {
1871 return String::new();
1872 }
1873 match unsafe { self.heap_ref() } {
1874 HeapObject::String(s) => s.clone(),
1875 HeapObject::ErrnoDual { msg, .. } => msg.clone(),
1876 _ => String::new(),
1877 }
1878 }
1879
1880 #[inline]
1881 pub fn to_number(&self) -> f64 {
1882 if nanbox::is_imm_undef(self.0) {
1883 return 0.0;
1884 }
1885 if let Some(n) = nanbox::as_imm_int32(self.0) {
1886 return n as f64;
1887 }
1888 if nanbox::is_raw_float_bits(self.0) {
1889 return f64::from_bits(self.0);
1890 }
1891 match unsafe { self.heap_ref() } {
1892 HeapObject::Integer(n) => *n as f64,
1893 HeapObject::Float(f) => *f,
1894 HeapObject::ErrnoDual { code, .. } => *code as f64,
1895 HeapObject::String(s) => parse_number(s),
1896 HeapObject::Bytes(b) => b.len() as f64,
1897 HeapObject::Array(a) => a.len() as f64,
1898 HeapObject::Atomic(arc) => arc.lock().to_number(),
1899 HeapObject::Set(s) => s.len() as f64,
1900 HeapObject::ChannelTx(_)
1901 | HeapObject::ChannelRx(_)
1902 | HeapObject::AsyncTask(_)
1903 | HeapObject::Generator(_) => 1.0,
1904 HeapObject::Deque(d) => d.lock().len() as f64,
1905 HeapObject::Heap(h) => h.lock().items.len() as f64,
1906 HeapObject::Pipeline(p) => p.lock().source.len() as f64,
1907 HeapObject::DataFrame(d) => d.lock().nrows() as f64,
1908 HeapObject::Capture(_)
1909 | HeapObject::Ppool(_)
1910 | HeapObject::RemoteCluster(_)
1911 | HeapObject::Barrier(_)
1912 | HeapObject::SqliteConn(_)
1913 | HeapObject::StructInst(_)
1914 | HeapObject::IOHandle(_) => 1.0,
1915 _ => 0.0,
1916 }
1917 }
1918
1919 #[inline]
1920 pub fn to_int(&self) -> i64 {
1921 if nanbox::is_imm_undef(self.0) {
1922 return 0;
1923 }
1924 if let Some(n) = nanbox::as_imm_int32(self.0) {
1925 return n as i64;
1926 }
1927 if nanbox::is_raw_float_bits(self.0) {
1928 return f64::from_bits(self.0) as i64;
1929 }
1930 match unsafe { self.heap_ref() } {
1931 HeapObject::Integer(n) => *n,
1932 HeapObject::Float(f) => *f as i64,
1933 HeapObject::ErrnoDual { code, .. } => *code as i64,
1934 HeapObject::String(s) => parse_number(s) as i64,
1935 HeapObject::Bytes(b) => b.len() as i64,
1936 HeapObject::Array(a) => a.len() as i64,
1937 HeapObject::Atomic(arc) => arc.lock().to_int(),
1938 HeapObject::Set(s) => s.len() as i64,
1939 HeapObject::ChannelTx(_)
1940 | HeapObject::ChannelRx(_)
1941 | HeapObject::AsyncTask(_)
1942 | HeapObject::Generator(_) => 1,
1943 HeapObject::Deque(d) => d.lock().len() as i64,
1944 HeapObject::Heap(h) => h.lock().items.len() as i64,
1945 HeapObject::Pipeline(p) => p.lock().source.len() as i64,
1946 HeapObject::DataFrame(d) => d.lock().nrows() as i64,
1947 HeapObject::Capture(_)
1948 | HeapObject::Ppool(_)
1949 | HeapObject::RemoteCluster(_)
1950 | HeapObject::Barrier(_)
1951 | HeapObject::SqliteConn(_)
1952 | HeapObject::StructInst(_)
1953 | HeapObject::IOHandle(_) => 1,
1954 _ => 0,
1955 }
1956 }
1957
1958 pub fn type_name(&self) -> String {
1959 if nanbox::is_imm_undef(self.0) {
1960 return "undef".to_string();
1961 }
1962 if nanbox::as_imm_int32(self.0).is_some() {
1963 return "INTEGER".to_string();
1964 }
1965 if nanbox::is_raw_float_bits(self.0) {
1966 return "FLOAT".to_string();
1967 }
1968 match unsafe { self.heap_ref() } {
1969 HeapObject::String(_) => "STRING".to_string(),
1970 HeapObject::Bytes(_) => "BYTES".to_string(),
1971 HeapObject::Array(_) => "ARRAY".to_string(),
1972 HeapObject::Hash(_) => "HASH".to_string(),
1973 HeapObject::ArrayRef(_) | HeapObject::ArrayBindingRef(_) => "ARRAY".to_string(),
1974 HeapObject::HashRef(_) | HeapObject::HashBindingRef(_) => "HASH".to_string(),
1975 HeapObject::ScalarRef(_) | HeapObject::ScalarBindingRef(_) => "SCALAR".to_string(),
1976 HeapObject::CodeRef(_) => "CODE".to_string(),
1977 HeapObject::Regex(_, _, _) => "Regexp".to_string(),
1978 HeapObject::Blessed(b) => b.class.clone(),
1979 HeapObject::IOHandle(_) => "GLOB".to_string(),
1980 HeapObject::Atomic(_) => "ATOMIC".to_string(),
1981 HeapObject::Set(_) => "Set".to_string(),
1982 HeapObject::ChannelTx(_) => "PCHANNEL::Tx".to_string(),
1983 HeapObject::ChannelRx(_) => "PCHANNEL::Rx".to_string(),
1984 HeapObject::AsyncTask(_) => "ASYNCTASK".to_string(),
1985 HeapObject::Generator(_) => "Generator".to_string(),
1986 HeapObject::Deque(_) => "Deque".to_string(),
1987 HeapObject::Heap(_) => "Heap".to_string(),
1988 HeapObject::Pipeline(_) => "Pipeline".to_string(),
1989 HeapObject::DataFrame(_) => "DataFrame".to_string(),
1990 HeapObject::Capture(_) => "Capture".to_string(),
1991 HeapObject::Ppool(_) => "Ppool".to_string(),
1992 HeapObject::RemoteCluster(_) => "Cluster".to_string(),
1993 HeapObject::Barrier(_) => "Barrier".to_string(),
1994 HeapObject::SqliteConn(_) => "SqliteConn".to_string(),
1995 HeapObject::StructInst(s) => s.def.name.to_string(),
1996 HeapObject::EnumInst(e) => e.def.name.to_string(),
1997 HeapObject::ClassInst(c) => c.def.name.to_string(),
1998 HeapObject::Iterator(_) => "Iterator".to_string(),
1999 HeapObject::ErrnoDual { .. } => "Errno".to_string(),
2000 HeapObject::Integer(_) => "INTEGER".to_string(),
2001 HeapObject::Float(_) => "FLOAT".to_string(),
2002 }
2003 }
2004
2005 pub fn ref_type(&self) -> PerlValue {
2006 if !nanbox::is_heap(self.0) {
2007 return PerlValue::string(String::new());
2008 }
2009 match unsafe { self.heap_ref() } {
2010 HeapObject::ArrayRef(_) | HeapObject::ArrayBindingRef(_) => {
2011 PerlValue::string("ARRAY".into())
2012 }
2013 HeapObject::HashRef(_) | HeapObject::HashBindingRef(_) => {
2014 PerlValue::string("HASH".into())
2015 }
2016 HeapObject::ScalarRef(_) | HeapObject::ScalarBindingRef(_) => {
2017 PerlValue::string("SCALAR".into())
2018 }
2019 HeapObject::CodeRef(_) => PerlValue::string("CODE".into()),
2020 HeapObject::Regex(_, _, _) => PerlValue::string("Regexp".into()),
2021 HeapObject::Atomic(_) => PerlValue::string("ATOMIC".into()),
2022 HeapObject::Set(_) => PerlValue::string("Set".into()),
2023 HeapObject::ChannelTx(_) => PerlValue::string("PCHANNEL::Tx".into()),
2024 HeapObject::ChannelRx(_) => PerlValue::string("PCHANNEL::Rx".into()),
2025 HeapObject::AsyncTask(_) => PerlValue::string("ASYNCTASK".into()),
2026 HeapObject::Generator(_) => PerlValue::string("Generator".into()),
2027 HeapObject::Deque(_) => PerlValue::string("Deque".into()),
2028 HeapObject::Heap(_) => PerlValue::string("Heap".into()),
2029 HeapObject::Pipeline(_) => PerlValue::string("Pipeline".into()),
2030 HeapObject::DataFrame(_) => PerlValue::string("DataFrame".into()),
2031 HeapObject::Capture(_) => PerlValue::string("Capture".into()),
2032 HeapObject::Ppool(_) => PerlValue::string("Ppool".into()),
2033 HeapObject::RemoteCluster(_) => PerlValue::string("Cluster".into()),
2034 HeapObject::Barrier(_) => PerlValue::string("Barrier".into()),
2035 HeapObject::SqliteConn(_) => PerlValue::string("SqliteConn".into()),
2036 HeapObject::StructInst(s) => PerlValue::string(s.def.name.clone()),
2037 HeapObject::EnumInst(e) => PerlValue::string(e.def.name.clone()),
2038 HeapObject::Bytes(_) => PerlValue::string("BYTES".into()),
2039 HeapObject::Blessed(b) => PerlValue::string(b.class.clone()),
2040 _ => PerlValue::string(String::new()),
2041 }
2042 }
2043
2044 pub fn num_cmp(&self, other: &PerlValue) -> Ordering {
2045 let a = self.to_number();
2046 let b = other.to_number();
2047 a.partial_cmp(&b).unwrap_or(Ordering::Equal)
2048 }
2049
2050 #[inline]
2052 pub fn str_eq(&self, other: &PerlValue) -> bool {
2053 if nanbox::is_heap(self.0) && nanbox::is_heap(other.0) {
2054 if let (HeapObject::String(a), HeapObject::String(b)) =
2055 unsafe { (self.heap_ref(), other.heap_ref()) }
2056 {
2057 return a == b;
2058 }
2059 }
2060 self.to_string() == other.to_string()
2061 }
2062
2063 pub fn str_cmp(&self, other: &PerlValue) -> Ordering {
2064 if nanbox::is_heap(self.0) && nanbox::is_heap(other.0) {
2065 if let (HeapObject::String(a), HeapObject::String(b)) =
2066 unsafe { (self.heap_ref(), other.heap_ref()) }
2067 {
2068 return a.cmp(b);
2069 }
2070 }
2071 self.to_string().cmp(&other.to_string())
2072 }
2073
2074 pub fn struct_field_eq(&self, other: &PerlValue) -> bool {
2076 if nanbox::is_imm_undef(self.0) && nanbox::is_imm_undef(other.0) {
2077 return true;
2078 }
2079 if let (Some(a), Some(b)) = (nanbox::as_imm_int32(self.0), nanbox::as_imm_int32(other.0)) {
2080 return a == b;
2081 }
2082 if nanbox::is_raw_float_bits(self.0) && nanbox::is_raw_float_bits(other.0) {
2083 return f64::from_bits(self.0) == f64::from_bits(other.0);
2084 }
2085 if !nanbox::is_heap(self.0) || !nanbox::is_heap(other.0) {
2086 return self.to_number() == other.to_number();
2087 }
2088 match (unsafe { self.heap_ref() }, unsafe { other.heap_ref() }) {
2089 (HeapObject::String(a), HeapObject::String(b)) => a == b,
2090 (HeapObject::Integer(a), HeapObject::Integer(b)) => a == b,
2091 (HeapObject::Float(a), HeapObject::Float(b)) => a == b,
2092 (HeapObject::Array(a), HeapObject::Array(b)) => {
2093 a.len() == b.len() && a.iter().zip(b.iter()).all(|(x, y)| x.struct_field_eq(y))
2094 }
2095 (HeapObject::ArrayRef(a), HeapObject::ArrayRef(b)) => {
2096 let ag = a.read();
2097 let bg = b.read();
2098 ag.len() == bg.len() && ag.iter().zip(bg.iter()).all(|(x, y)| x.struct_field_eq(y))
2099 }
2100 (HeapObject::Hash(a), HeapObject::Hash(b)) => {
2101 a.len() == b.len()
2102 && a.iter()
2103 .all(|(k, v)| b.get(k).is_some_and(|bv| v.struct_field_eq(bv)))
2104 }
2105 (HeapObject::HashRef(a), HeapObject::HashRef(b)) => {
2106 let ag = a.read();
2107 let bg = b.read();
2108 ag.len() == bg.len()
2109 && ag
2110 .iter()
2111 .all(|(k, v)| bg.get(k).is_some_and(|bv| v.struct_field_eq(bv)))
2112 }
2113 (HeapObject::StructInst(a), HeapObject::StructInst(b)) => {
2114 if a.def.name != b.def.name {
2115 false
2116 } else {
2117 let av = a.get_values();
2118 let bv = b.get_values();
2119 av.len() == bv.len()
2120 && av.iter().zip(bv.iter()).all(|(x, y)| x.struct_field_eq(y))
2121 }
2122 }
2123 _ => self.to_string() == other.to_string(),
2124 }
2125 }
2126
2127 pub fn deep_clone(&self) -> PerlValue {
2129 if !nanbox::is_heap(self.0) {
2130 return self.clone();
2131 }
2132 match unsafe { self.heap_ref() } {
2133 HeapObject::Array(a) => PerlValue::array(a.iter().map(|v| v.deep_clone()).collect()),
2134 HeapObject::ArrayRef(a) => {
2135 let cloned: Vec<PerlValue> = a.read().iter().map(|v| v.deep_clone()).collect();
2136 PerlValue::array_ref(Arc::new(RwLock::new(cloned)))
2137 }
2138 HeapObject::Hash(h) => {
2139 let mut cloned = IndexMap::new();
2140 for (k, v) in h.iter() {
2141 cloned.insert(k.clone(), v.deep_clone());
2142 }
2143 PerlValue::hash(cloned)
2144 }
2145 HeapObject::HashRef(h) => {
2146 let mut cloned = IndexMap::new();
2147 for (k, v) in h.read().iter() {
2148 cloned.insert(k.clone(), v.deep_clone());
2149 }
2150 PerlValue::hash_ref(Arc::new(RwLock::new(cloned)))
2151 }
2152 HeapObject::StructInst(s) => {
2153 let new_values = s.get_values().iter().map(|v| v.deep_clone()).collect();
2154 PerlValue::struct_inst(Arc::new(StructInstance::new(
2155 Arc::clone(&s.def),
2156 new_values,
2157 )))
2158 }
2159 _ => self.clone(),
2160 }
2161 }
2162
2163 pub fn to_list(&self) -> Vec<PerlValue> {
2164 if nanbox::is_imm_undef(self.0) {
2165 return vec![];
2166 }
2167 if !nanbox::is_heap(self.0) {
2168 return vec![self.clone()];
2169 }
2170 match unsafe { self.heap_ref() } {
2171 HeapObject::Array(a) => a.clone(),
2172 HeapObject::Hash(h) => h
2173 .iter()
2174 .flat_map(|(k, v)| vec![PerlValue::string(k.clone()), v.clone()])
2175 .collect(),
2176 HeapObject::Atomic(arc) => arc.lock().to_list(),
2177 HeapObject::Set(s) => s.values().cloned().collect(),
2178 HeapObject::Deque(d) => d.lock().iter().cloned().collect(),
2179 HeapObject::Iterator(it) => {
2180 let mut out = Vec::new();
2181 while let Some(v) = it.next_item() {
2182 out.push(v);
2183 }
2184 out
2185 }
2186 _ => vec![self.clone()],
2187 }
2188 }
2189
2190 pub fn scalar_context(&self) -> PerlValue {
2191 if !nanbox::is_heap(self.0) {
2192 return self.clone();
2193 }
2194 if let Some(arc) = self.as_atomic_arc() {
2195 return arc.lock().scalar_context();
2196 }
2197 match unsafe { self.heap_ref() } {
2198 HeapObject::Array(a) => PerlValue::integer(a.len() as i64),
2199 HeapObject::Hash(h) => {
2200 if h.is_empty() {
2201 PerlValue::integer(0)
2202 } else {
2203 PerlValue::string(format!("{}/{}", h.len(), h.capacity()))
2204 }
2205 }
2206 HeapObject::Set(s) => PerlValue::integer(s.len() as i64),
2207 HeapObject::Deque(d) => PerlValue::integer(d.lock().len() as i64),
2208 HeapObject::Heap(h) => PerlValue::integer(h.lock().items.len() as i64),
2209 HeapObject::Pipeline(p) => PerlValue::integer(p.lock().source.len() as i64),
2210 HeapObject::Capture(_)
2211 | HeapObject::Ppool(_)
2212 | HeapObject::RemoteCluster(_)
2213 | HeapObject::Barrier(_) => PerlValue::integer(1),
2214 HeapObject::Generator(_) => PerlValue::integer(1),
2215 _ => self.clone(),
2216 }
2217 }
2218}
2219
2220impl fmt::Display for PerlValue {
2221 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2222 if nanbox::is_imm_undef(self.0) {
2223 return Ok(());
2224 }
2225 if let Some(n) = nanbox::as_imm_int32(self.0) {
2226 return write!(f, "{n}");
2227 }
2228 if nanbox::is_raw_float_bits(self.0) {
2229 return write!(f, "{}", format_float(f64::from_bits(self.0)));
2230 }
2231 match unsafe { self.heap_ref() } {
2232 HeapObject::Integer(n) => write!(f, "{n}"),
2233 HeapObject::Float(val) => write!(f, "{}", format_float(*val)),
2234 HeapObject::ErrnoDual { msg, .. } => f.write_str(msg),
2235 HeapObject::String(s) => f.write_str(s),
2236 HeapObject::Bytes(b) => f.write_str(&decode_utf8_or_latin1(b)),
2237 HeapObject::Array(a) => {
2238 for v in a {
2239 write!(f, "{v}")?;
2240 }
2241 Ok(())
2242 }
2243 HeapObject::Hash(h) => write!(f, "{}/{}", h.len(), h.capacity()),
2244 HeapObject::ArrayRef(_) | HeapObject::ArrayBindingRef(_) => f.write_str("ARRAY(0x...)"),
2245 HeapObject::HashRef(_) | HeapObject::HashBindingRef(_) => f.write_str("HASH(0x...)"),
2246 HeapObject::ScalarRef(_) | HeapObject::ScalarBindingRef(_) => {
2247 f.write_str("SCALAR(0x...)")
2248 }
2249 HeapObject::CodeRef(sub) => write!(f, "CODE({})", sub.name),
2250 HeapObject::Regex(_, src, _) => write!(f, "(?:{src})"),
2251 HeapObject::Blessed(b) => write!(f, "{}=HASH(0x...)", b.class),
2252 HeapObject::IOHandle(name) => f.write_str(name),
2253 HeapObject::Atomic(arc) => write!(f, "{}", arc.lock()),
2254 HeapObject::Set(s) => {
2255 f.write_str("{")?;
2256 if !s.is_empty() {
2257 let mut iter = s.values();
2258 if let Some(v) = iter.next() {
2259 write!(f, "{v}")?;
2260 }
2261 for v in iter {
2262 write!(f, ",{v}")?;
2263 }
2264 }
2265 f.write_str("}")
2266 }
2267 HeapObject::ChannelTx(_) => f.write_str("PCHANNEL::Tx"),
2268 HeapObject::ChannelRx(_) => f.write_str("PCHANNEL::Rx"),
2269 HeapObject::AsyncTask(_) => f.write_str("AsyncTask"),
2270 HeapObject::Generator(g) => write!(f, "Generator({} stmts)", g.block.len()),
2271 HeapObject::Deque(d) => write!(f, "Deque({})", d.lock().len()),
2272 HeapObject::Heap(h) => write!(f, "Heap({})", h.lock().items.len()),
2273 HeapObject::Pipeline(p) => {
2274 let g = p.lock();
2275 write!(f, "Pipeline({} ops)", g.ops.len())
2276 }
2277 HeapObject::Capture(c) => write!(f, "Capture(exit={})", c.exitcode),
2278 HeapObject::Ppool(_) => f.write_str("Ppool"),
2279 HeapObject::RemoteCluster(c) => write!(f, "Cluster({} slots)", c.slots.len()),
2280 HeapObject::Barrier(_) => f.write_str("Barrier"),
2281 HeapObject::SqliteConn(_) => f.write_str("SqliteConn"),
2282 HeapObject::StructInst(s) => {
2283 write!(f, "{}(", s.def.name)?;
2285 let values = s.values.read();
2286 for (i, field) in s.def.fields.iter().enumerate() {
2287 if i > 0 {
2288 f.write_str(", ")?;
2289 }
2290 write!(
2291 f,
2292 "{} => {}",
2293 field.name,
2294 values.get(i).cloned().unwrap_or(PerlValue::UNDEF)
2295 )?;
2296 }
2297 f.write_str(")")
2298 }
2299 HeapObject::EnumInst(e) => {
2300 write!(f, "{}::{}", e.def.name, e.variant_name())?;
2302 if e.def.variants[e.variant_idx].ty.is_some() {
2303 write!(f, "({})", e.data)?;
2304 }
2305 Ok(())
2306 }
2307 HeapObject::ClassInst(c) => {
2308 write!(f, "{}(", c.def.name)?;
2310 let values = c.values.read();
2311 for (i, field) in c.def.fields.iter().enumerate() {
2312 if i > 0 {
2313 f.write_str(", ")?;
2314 }
2315 write!(
2316 f,
2317 "{} => {}",
2318 field.name,
2319 values.get(i).cloned().unwrap_or(PerlValue::UNDEF)
2320 )?;
2321 }
2322 f.write_str(")")
2323 }
2324 HeapObject::DataFrame(d) => {
2325 let g = d.lock();
2326 write!(f, "DataFrame({} rows)", g.nrows())
2327 }
2328 HeapObject::Iterator(_) => f.write_str("Iterator"),
2329 }
2330 }
2331}
2332
2333pub fn set_member_key(v: &PerlValue) -> String {
2335 if nanbox::is_imm_undef(v.0) {
2336 return "u:".to_string();
2337 }
2338 if let Some(n) = nanbox::as_imm_int32(v.0) {
2339 return format!("i:{n}");
2340 }
2341 if nanbox::is_raw_float_bits(v.0) {
2342 return format!("f:{}", f64::from_bits(v.0).to_bits());
2343 }
2344 match unsafe { v.heap_ref() } {
2345 HeapObject::String(s) => format!("s:{s}"),
2346 HeapObject::Bytes(b) => {
2347 use std::fmt::Write as _;
2348 let mut h = String::with_capacity(b.len() * 2);
2349 for &x in b.iter() {
2350 let _ = write!(&mut h, "{:02x}", x);
2351 }
2352 format!("by:{h}")
2353 }
2354 HeapObject::Array(a) => {
2355 let parts: Vec<_> = a.iter().map(set_member_key).collect();
2356 format!("a:{}", parts.join(","))
2357 }
2358 HeapObject::Hash(h) => {
2359 let mut keys: Vec<_> = h.keys().cloned().collect();
2360 keys.sort();
2361 let parts: Vec<_> = keys
2362 .iter()
2363 .map(|k| format!("{}={}", k, set_member_key(h.get(k).unwrap())))
2364 .collect();
2365 format!("h:{}", parts.join(","))
2366 }
2367 HeapObject::Set(inner) => {
2368 let mut keys: Vec<_> = inner.keys().cloned().collect();
2369 keys.sort();
2370 format!("S:{}", keys.join(","))
2371 }
2372 HeapObject::ArrayRef(a) => {
2373 let g = a.read();
2374 let parts: Vec<_> = g.iter().map(set_member_key).collect();
2375 format!("ar:{}", parts.join(","))
2376 }
2377 HeapObject::HashRef(h) => {
2378 let g = h.read();
2379 let mut keys: Vec<_> = g.keys().cloned().collect();
2380 keys.sort();
2381 let parts: Vec<_> = keys
2382 .iter()
2383 .map(|k| format!("{}={}", k, set_member_key(g.get(k).unwrap())))
2384 .collect();
2385 format!("hr:{}", parts.join(","))
2386 }
2387 HeapObject::Blessed(b) => {
2388 let d = b.data.read();
2389 format!("b:{}:{}", b.class, set_member_key(&d))
2390 }
2391 HeapObject::ScalarRef(_) | HeapObject::ScalarBindingRef(_) => format!("sr:{v}"),
2392 HeapObject::ArrayBindingRef(n) => format!("abind:{n}"),
2393 HeapObject::HashBindingRef(n) => format!("hbind:{n}"),
2394 HeapObject::CodeRef(_) => format!("c:{v}"),
2395 HeapObject::Regex(_, src, _) => format!("r:{src}"),
2396 HeapObject::IOHandle(s) => format!("io:{s}"),
2397 HeapObject::Atomic(arc) => format!("at:{}", set_member_key(&arc.lock())),
2398 HeapObject::ChannelTx(tx) => format!("chtx:{:p}", Arc::as_ptr(tx)),
2399 HeapObject::ChannelRx(rx) => format!("chrx:{:p}", Arc::as_ptr(rx)),
2400 HeapObject::AsyncTask(t) => format!("async:{:p}", Arc::as_ptr(t)),
2401 HeapObject::Generator(g) => format!("gen:{:p}", Arc::as_ptr(g)),
2402 HeapObject::Deque(d) => format!("dq:{:p}", Arc::as_ptr(d)),
2403 HeapObject::Heap(h) => format!("hp:{:p}", Arc::as_ptr(h)),
2404 HeapObject::Pipeline(p) => format!("pl:{:p}", Arc::as_ptr(p)),
2405 HeapObject::Capture(c) => format!("cap:{:p}", Arc::as_ptr(c)),
2406 HeapObject::Ppool(p) => format!("pp:{:p}", Arc::as_ptr(&p.0)),
2407 HeapObject::RemoteCluster(c) => format!("rcl:{:p}", Arc::as_ptr(c)),
2408 HeapObject::Barrier(b) => format!("br:{:p}", Arc::as_ptr(&b.0)),
2409 HeapObject::SqliteConn(c) => format!("sql:{:p}", Arc::as_ptr(c)),
2410 HeapObject::StructInst(s) => format!("st:{}:{:?}", s.def.name, s.values),
2411 HeapObject::EnumInst(e) => {
2412 format!("en:{}::{}:{}", e.def.name, e.variant_name(), e.data)
2413 }
2414 HeapObject::ClassInst(c) => format!("cl:{}:{:?}", c.def.name, c.values),
2415 HeapObject::DataFrame(d) => format!("df:{:p}", Arc::as_ptr(d)),
2416 HeapObject::Iterator(_) => "iter".to_string(),
2417 HeapObject::ErrnoDual { code, msg } => format!("e:{code}:{msg}"),
2418 HeapObject::Integer(n) => format!("i:{n}"),
2419 HeapObject::Float(fl) => format!("f:{}", fl.to_bits()),
2420 }
2421}
2422
2423pub fn set_from_elements<I: IntoIterator<Item = PerlValue>>(items: I) -> PerlValue {
2424 let mut map = PerlSet::new();
2425 for v in items {
2426 let k = set_member_key(&v);
2427 map.insert(k, v);
2428 }
2429 PerlValue::set(Arc::new(map))
2430}
2431
2432#[inline]
2434pub fn set_payload(v: &PerlValue) -> Option<Arc<PerlSet>> {
2435 if !nanbox::is_heap(v.0) {
2436 return None;
2437 }
2438 match unsafe { v.heap_ref() } {
2439 HeapObject::Set(s) => Some(Arc::clone(s)),
2440 HeapObject::Atomic(a) => set_payload(&a.lock()),
2441 _ => None,
2442 }
2443}
2444
2445pub fn set_union(a: &PerlValue, b: &PerlValue) -> Option<PerlValue> {
2446 let ia = set_payload(a)?;
2447 let ib = set_payload(b)?;
2448 let mut m = (*ia).clone();
2449 for (k, v) in ib.iter() {
2450 m.entry(k.clone()).or_insert_with(|| v.clone());
2451 }
2452 Some(PerlValue::set(Arc::new(m)))
2453}
2454
2455pub fn set_intersection(a: &PerlValue, b: &PerlValue) -> Option<PerlValue> {
2456 let ia = set_payload(a)?;
2457 let ib = set_payload(b)?;
2458 let mut m = PerlSet::new();
2459 for (k, v) in ia.iter() {
2460 if ib.contains_key(k) {
2461 m.insert(k.clone(), v.clone());
2462 }
2463 }
2464 Some(PerlValue::set(Arc::new(m)))
2465}
2466fn parse_number(s: &str) -> f64 {
2467 let s = s.trim();
2468 if s.is_empty() {
2469 return 0.0;
2470 }
2471 let mut end = 0;
2473 let bytes = s.as_bytes();
2474 if end < bytes.len() && (bytes[end] == b'+' || bytes[end] == b'-') {
2475 end += 1;
2476 }
2477 while end < bytes.len() && bytes[end].is_ascii_digit() {
2478 end += 1;
2479 }
2480 if end < bytes.len() && bytes[end] == b'.' {
2481 end += 1;
2482 while end < bytes.len() && bytes[end].is_ascii_digit() {
2483 end += 1;
2484 }
2485 }
2486 if end < bytes.len() && (bytes[end] == b'e' || bytes[end] == b'E') {
2487 end += 1;
2488 if end < bytes.len() && (bytes[end] == b'+' || bytes[end] == b'-') {
2489 end += 1;
2490 }
2491 while end < bytes.len() && bytes[end].is_ascii_digit() {
2492 end += 1;
2493 }
2494 }
2495 if end == 0 {
2496 return 0.0;
2497 }
2498 s[..end].parse::<f64>().unwrap_or(0.0)
2499}
2500
2501fn format_float(f: f64) -> String {
2502 if f.fract() == 0.0 && f.abs() < 1e16 {
2503 format!("{}", f as i64)
2504 } else {
2505 let mut buf = [0u8; 64];
2507 unsafe {
2508 libc::snprintf(
2509 buf.as_mut_ptr() as *mut libc::c_char,
2510 buf.len(),
2511 c"%.15g".as_ptr(),
2512 f,
2513 );
2514 std::ffi::CStr::from_ptr(buf.as_ptr() as *const libc::c_char)
2515 .to_string_lossy()
2516 .into_owned()
2517 }
2518 }
2519}
2520
2521#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2523pub(crate) enum PerlListRangeIncOutcome {
2524 Continue,
2525 BecameNumeric,
2527}
2528
2529fn perl_str_looks_like_number_for_range(s: &str) -> bool {
2532 let t = s.trim();
2533 if t.is_empty() {
2534 return s.is_empty();
2535 }
2536 let b = t.as_bytes();
2537 let mut i = 0usize;
2538 if i < b.len() && (b[i] == b'+' || b[i] == b'-') {
2539 i += 1;
2540 }
2541 if i >= b.len() {
2542 return false;
2543 }
2544 let mut saw_digit = false;
2545 while i < b.len() && b[i].is_ascii_digit() {
2546 saw_digit = true;
2547 i += 1;
2548 }
2549 if i < b.len() && b[i] == b'.' {
2550 i += 1;
2551 while i < b.len() && b[i].is_ascii_digit() {
2552 saw_digit = true;
2553 i += 1;
2554 }
2555 }
2556 if !saw_digit {
2557 return false;
2558 }
2559 if i < b.len() && (b[i] == b'e' || b[i] == b'E') {
2560 i += 1;
2561 if i < b.len() && (b[i] == b'+' || b[i] == b'-') {
2562 i += 1;
2563 }
2564 let exp0 = i;
2565 while i < b.len() && b[i].is_ascii_digit() {
2566 i += 1;
2567 }
2568 if i == exp0 {
2569 return false;
2570 }
2571 }
2572 i == b.len()
2573}
2574
2575pub(crate) fn perl_list_range_pair_is_numeric(left: &PerlValue, right: &PerlValue) -> bool {
2577 if left.is_integer_like() || left.is_float_like() {
2578 return true;
2579 }
2580 if !left.is_undef() && !left.is_string_like() {
2581 return true;
2582 }
2583 if right.is_integer_like() || right.is_float_like() {
2584 return true;
2585 }
2586 if !right.is_undef() && !right.is_string_like() {
2587 return true;
2588 }
2589
2590 let left_ok = !left.is_undef();
2591 let right_ok = !right.is_undef();
2592 let left_pok = left.is_string_like();
2593 let left_pv = left.as_str_or_empty();
2594 let right_pv = right.as_str_or_empty();
2595
2596 let left_n = perl_str_looks_like_number_for_range(&left_pv);
2597 let right_n = perl_str_looks_like_number_for_range(&right_pv);
2598
2599 let left_zero_prefix =
2600 left_pok && left_pv.len() > 1 && left_pv.as_bytes().first() == Some(&b'0');
2601
2602 let clause5_left =
2603 (!left_ok && right_ok) || ((!left_ok || left_n) && left_pok && !left_zero_prefix);
2604 clause5_left && (!right_ok || right_n)
2605}
2606
2607pub(crate) fn perl_magic_string_increment_for_range(s: &mut String) -> PerlListRangeIncOutcome {
2609 if s.is_empty() {
2610 return PerlListRangeIncOutcome::BecameNumeric;
2611 }
2612 let b = s.as_bytes();
2613 let mut i = 0usize;
2614 while i < b.len() && b[i].is_ascii_alphabetic() {
2615 i += 1;
2616 }
2617 while i < b.len() && b[i].is_ascii_digit() {
2618 i += 1;
2619 }
2620 if i < b.len() {
2621 let n = parse_number(s) + 1.0;
2622 *s = format_float(n);
2623 return PerlListRangeIncOutcome::BecameNumeric;
2624 }
2625
2626 let bytes = unsafe { s.as_mut_vec() };
2627 let mut idx = bytes.len() - 1;
2628 loop {
2629 if bytes[idx].is_ascii_digit() {
2630 bytes[idx] += 1;
2631 if bytes[idx] <= b'9' {
2632 return PerlListRangeIncOutcome::Continue;
2633 }
2634 bytes[idx] = b'0';
2635 if idx == 0 {
2636 bytes.insert(0, b'1');
2637 return PerlListRangeIncOutcome::Continue;
2638 }
2639 idx -= 1;
2640 } else {
2641 bytes[idx] = bytes[idx].wrapping_add(1);
2642 if bytes[idx].is_ascii_alphabetic() {
2643 return PerlListRangeIncOutcome::Continue;
2644 }
2645 bytes[idx] = bytes[idx].wrapping_sub(b'z' - b'a' + 1);
2646 if idx == 0 {
2647 let c = bytes[0];
2648 bytes.insert(0, if c.is_ascii_digit() { b'1' } else { c });
2649 return PerlListRangeIncOutcome::Continue;
2650 }
2651 idx -= 1;
2652 }
2653 }
2654}
2655
2656fn perl_list_range_max_bound(right: &str) -> usize {
2657 if right.is_ascii() {
2658 right.len()
2659 } else {
2660 right.chars().count()
2661 }
2662}
2663
2664fn perl_list_range_cur_bound(cur: &str, right_is_ascii: bool) -> usize {
2665 if right_is_ascii {
2666 cur.len()
2667 } else {
2668 cur.chars().count()
2669 }
2670}
2671
2672fn perl_list_range_expand_string_magic(from: PerlValue, to: PerlValue) -> Vec<PerlValue> {
2673 let mut cur = from.into_string();
2674 let right = to.into_string();
2675 let right_ascii = right.is_ascii();
2676 let max_bound = perl_list_range_max_bound(&right);
2677 let mut out = Vec::new();
2678 let mut guard = 0usize;
2679 loop {
2680 guard += 1;
2681 if guard > 50_000_000 {
2682 break;
2683 }
2684 let cur_bound = perl_list_range_cur_bound(&cur, right_ascii);
2685 if cur_bound > max_bound {
2686 break;
2687 }
2688 out.push(PerlValue::string(cur.clone()));
2689 if cur == right {
2690 break;
2691 }
2692 match perl_magic_string_increment_for_range(&mut cur) {
2693 PerlListRangeIncOutcome::Continue => {}
2694 PerlListRangeIncOutcome::BecameNumeric => break,
2695 }
2696 }
2697 out
2698}
2699
2700pub(crate) fn perl_list_range_expand(from: PerlValue, to: PerlValue) -> Vec<PerlValue> {
2702 if perl_list_range_pair_is_numeric(&from, &to) {
2703 let i = from.to_int();
2704 let j = to.to_int();
2705 if j >= i {
2706 (i..=j).map(PerlValue::integer).collect()
2707 } else {
2708 Vec::new()
2709 }
2710 } else {
2711 perl_list_range_expand_string_magic(from, to)
2712 }
2713}
2714
2715impl PerlDataFrame {
2716 pub fn row_hashref(&self, row: usize) -> PerlValue {
2718 let mut m = IndexMap::new();
2719 for (i, col) in self.columns.iter().enumerate() {
2720 m.insert(
2721 col.clone(),
2722 self.cols[i].get(row).cloned().unwrap_or(PerlValue::UNDEF),
2723 );
2724 }
2725 PerlValue::hash_ref(Arc::new(RwLock::new(m)))
2726 }
2727}
2728
2729#[cfg(test)]
2730mod tests {
2731 use super::PerlValue;
2732 use crate::perl_regex::PerlCompiledRegex;
2733 use indexmap::IndexMap;
2734 use parking_lot::RwLock;
2735 use std::cmp::Ordering;
2736 use std::sync::Arc;
2737
2738 #[test]
2739 fn undef_is_false() {
2740 assert!(!PerlValue::UNDEF.is_true());
2741 }
2742
2743 #[test]
2744 fn string_zero_is_false() {
2745 assert!(!PerlValue::string("0".into()).is_true());
2746 assert!(PerlValue::string("00".into()).is_true());
2747 }
2748
2749 #[test]
2750 fn empty_string_is_false() {
2751 assert!(!PerlValue::string(String::new()).is_true());
2752 }
2753
2754 #[test]
2755 fn integer_zero_is_false_nonzero_true() {
2756 assert!(!PerlValue::integer(0).is_true());
2757 assert!(PerlValue::integer(-1).is_true());
2758 }
2759
2760 #[test]
2761 fn float_zero_is_false_nonzero_true() {
2762 assert!(!PerlValue::float(0.0).is_true());
2763 assert!(PerlValue::float(0.1).is_true());
2764 }
2765
2766 #[test]
2767 fn num_cmp_orders_float_against_integer() {
2768 assert_eq!(
2769 PerlValue::float(2.5).num_cmp(&PerlValue::integer(3)),
2770 Ordering::Less
2771 );
2772 }
2773
2774 #[test]
2775 fn to_int_parses_leading_number_from_string() {
2776 assert_eq!(PerlValue::string("42xyz".into()).to_int(), 42);
2777 assert_eq!(PerlValue::string(" -3.7foo".into()).to_int(), -3);
2778 }
2779
2780 #[test]
2781 fn num_cmp_orders_as_numeric() {
2782 assert_eq!(
2783 PerlValue::integer(2).num_cmp(&PerlValue::integer(11)),
2784 Ordering::Less
2785 );
2786 assert_eq!(
2787 PerlValue::string("2foo".into()).num_cmp(&PerlValue::string("11".into())),
2788 Ordering::Less
2789 );
2790 }
2791
2792 #[test]
2793 fn str_cmp_orders_as_strings() {
2794 assert_eq!(
2795 PerlValue::string("2".into()).str_cmp(&PerlValue::string("11".into())),
2796 Ordering::Greater
2797 );
2798 }
2799
2800 #[test]
2801 fn str_eq_heap_strings_fast_path() {
2802 let a = PerlValue::string("hello".into());
2803 let b = PerlValue::string("hello".into());
2804 assert!(a.str_eq(&b));
2805 assert!(!a.str_eq(&PerlValue::string("hell".into())));
2806 }
2807
2808 #[test]
2809 fn str_eq_fallback_matches_stringified_equality() {
2810 let n = PerlValue::integer(42);
2811 let s = PerlValue::string("42".into());
2812 assert!(n.str_eq(&s));
2813 assert!(!PerlValue::integer(1).str_eq(&PerlValue::string("2".into())));
2814 }
2815
2816 #[test]
2817 fn str_cmp_heap_strings_fast_path() {
2818 assert_eq!(
2819 PerlValue::string("a".into()).str_cmp(&PerlValue::string("b".into())),
2820 Ordering::Less
2821 );
2822 }
2823
2824 #[test]
2825 fn scalar_context_array_and_hash() {
2826 let a =
2827 PerlValue::array(vec![PerlValue::integer(1), PerlValue::integer(2)]).scalar_context();
2828 assert_eq!(a.to_int(), 2);
2829 let mut h = IndexMap::new();
2830 h.insert("a".into(), PerlValue::integer(1));
2831 let sc = PerlValue::hash(h).scalar_context();
2832 assert!(sc.is_string_like());
2833 }
2834
2835 #[test]
2836 fn to_list_array_hash_and_scalar() {
2837 assert_eq!(
2838 PerlValue::array(vec![PerlValue::integer(7)])
2839 .to_list()
2840 .len(),
2841 1
2842 );
2843 let mut h = IndexMap::new();
2844 h.insert("k".into(), PerlValue::integer(1));
2845 let list = PerlValue::hash(h).to_list();
2846 assert_eq!(list.len(), 2);
2847 let one = PerlValue::integer(99).to_list();
2848 assert_eq!(one.len(), 1);
2849 assert_eq!(one[0].to_int(), 99);
2850 }
2851
2852 #[test]
2853 fn type_name_and_ref_type_for_core_kinds() {
2854 assert_eq!(PerlValue::integer(0).type_name(), "INTEGER");
2855 assert_eq!(PerlValue::UNDEF.ref_type().to_string(), "");
2856 assert_eq!(
2857 PerlValue::array_ref(Arc::new(RwLock::new(vec![])))
2858 .ref_type()
2859 .to_string(),
2860 "ARRAY"
2861 );
2862 }
2863
2864 #[test]
2865 fn display_undef_is_empty_integer_is_decimal() {
2866 assert_eq!(PerlValue::UNDEF.to_string(), "");
2867 assert_eq!(PerlValue::integer(-7).to_string(), "-7");
2868 }
2869
2870 #[test]
2871 fn empty_array_is_false_nonempty_is_true() {
2872 assert!(!PerlValue::array(vec![]).is_true());
2873 assert!(PerlValue::array(vec![PerlValue::integer(0)]).is_true());
2874 }
2875
2876 #[test]
2877 fn to_number_undef_and_non_numeric_refs_are_zero() {
2878 use super::PerlSub;
2879
2880 assert_eq!(PerlValue::UNDEF.to_number(), 0.0);
2881 assert_eq!(
2882 PerlValue::code_ref(Arc::new(PerlSub {
2883 name: "f".into(),
2884 params: vec![],
2885 body: vec![],
2886 closure_env: None,
2887 prototype: None,
2888 fib_like: None,
2889 }))
2890 .to_number(),
2891 0.0
2892 );
2893 }
2894
2895 #[test]
2896 fn append_to_builds_string_without_extra_alloc_for_int_and_string() {
2897 let mut buf = String::new();
2898 PerlValue::integer(-12).append_to(&mut buf);
2899 PerlValue::string("ab".into()).append_to(&mut buf);
2900 assert_eq!(buf, "-12ab");
2901 let mut u = String::new();
2902 PerlValue::UNDEF.append_to(&mut u);
2903 assert!(u.is_empty());
2904 }
2905
2906 #[test]
2907 fn append_to_atomic_delegates_to_inner() {
2908 use parking_lot::Mutex;
2909 let a = PerlValue::atomic(Arc::new(Mutex::new(PerlValue::string("z".into()))));
2910 let mut buf = String::new();
2911 a.append_to(&mut buf);
2912 assert_eq!(buf, "z");
2913 }
2914
2915 #[test]
2916 fn unwrap_atomic_reads_inner_other_variants_clone() {
2917 use parking_lot::Mutex;
2918 let a = PerlValue::atomic(Arc::new(Mutex::new(PerlValue::integer(9))));
2919 assert_eq!(a.unwrap_atomic().to_int(), 9);
2920 assert_eq!(PerlValue::integer(3).unwrap_atomic().to_int(), 3);
2921 }
2922
2923 #[test]
2924 fn is_atomic_only_true_for_atomic_variant() {
2925 use parking_lot::Mutex;
2926 assert!(PerlValue::atomic(Arc::new(Mutex::new(PerlValue::UNDEF))).is_atomic());
2927 assert!(!PerlValue::integer(0).is_atomic());
2928 }
2929
2930 #[test]
2931 fn as_str_only_on_string_variant() {
2932 assert_eq!(
2933 PerlValue::string("x".into()).as_str(),
2934 Some("x".to_string())
2935 );
2936 assert_eq!(PerlValue::integer(1).as_str(), None);
2937 }
2938
2939 #[test]
2940 fn as_str_or_empty_defaults_non_string() {
2941 assert_eq!(PerlValue::string("z".into()).as_str_or_empty(), "z");
2942 assert_eq!(PerlValue::integer(1).as_str_or_empty(), "");
2943 }
2944
2945 #[test]
2946 fn to_int_truncates_float_toward_zero() {
2947 assert_eq!(PerlValue::float(3.9).to_int(), 3);
2948 assert_eq!(PerlValue::float(-2.1).to_int(), -2);
2949 }
2950
2951 #[test]
2952 fn to_number_array_is_length() {
2953 assert_eq!(
2954 PerlValue::array(vec![PerlValue::integer(1), PerlValue::integer(2)]).to_number(),
2955 2.0
2956 );
2957 }
2958
2959 #[test]
2960 fn scalar_context_empty_hash_is_zero() {
2961 let h = IndexMap::new();
2962 assert_eq!(PerlValue::hash(h).scalar_context().to_int(), 0);
2963 }
2964
2965 #[test]
2966 fn scalar_context_nonhash_nonarray_clones() {
2967 let v = PerlValue::integer(8);
2968 assert_eq!(v.scalar_context().to_int(), 8);
2969 }
2970
2971 #[test]
2972 fn display_float_integer_like_omits_decimal() {
2973 assert_eq!(PerlValue::float(4.0).to_string(), "4");
2974 }
2975
2976 #[test]
2977 fn display_array_concatenates_element_displays() {
2978 let a = PerlValue::array(vec![PerlValue::integer(1), PerlValue::string("b".into())]);
2979 assert_eq!(a.to_string(), "1b");
2980 }
2981
2982 #[test]
2983 fn display_code_ref_includes_sub_name() {
2984 use super::PerlSub;
2985 let c = PerlValue::code_ref(Arc::new(PerlSub {
2986 name: "foo".into(),
2987 params: vec![],
2988 body: vec![],
2989 closure_env: None,
2990 prototype: None,
2991 fib_like: None,
2992 }));
2993 assert!(c.to_string().contains("foo"));
2994 }
2995
2996 #[test]
2997 fn display_regex_shows_non_capturing_prefix() {
2998 let r = PerlValue::regex(
2999 PerlCompiledRegex::compile("x+").unwrap(),
3000 "x+".into(),
3001 "".into(),
3002 );
3003 assert_eq!(r.to_string(), "(?:x+)");
3004 }
3005
3006 #[test]
3007 fn display_iohandle_is_name() {
3008 assert_eq!(PerlValue::io_handle("STDOUT".into()).to_string(), "STDOUT");
3009 }
3010
3011 #[test]
3012 fn ref_type_blessed_uses_class_name() {
3013 let b = PerlValue::blessed(Arc::new(super::BlessedRef::new_blessed(
3014 "Pkg".into(),
3015 PerlValue::UNDEF,
3016 )));
3017 assert_eq!(b.ref_type().to_string(), "Pkg");
3018 }
3019
3020 #[test]
3021 fn blessed_drop_enqueues_pending_destroy() {
3022 let v = PerlValue::blessed(Arc::new(super::BlessedRef::new_blessed(
3023 "Z".into(),
3024 PerlValue::integer(7),
3025 )));
3026 drop(v);
3027 let q = crate::pending_destroy::take_queue();
3028 assert_eq!(q.len(), 1);
3029 assert_eq!(q[0].0, "Z");
3030 assert_eq!(q[0].1.to_int(), 7);
3031 }
3032
3033 #[test]
3034 fn type_name_iohandle_is_glob() {
3035 assert_eq!(PerlValue::io_handle("FH".into()).type_name(), "GLOB");
3036 }
3037
3038 #[test]
3039 fn empty_hash_is_false() {
3040 assert!(!PerlValue::hash(IndexMap::new()).is_true());
3041 }
3042
3043 #[test]
3044 fn hash_nonempty_is_true() {
3045 let mut h = IndexMap::new();
3046 h.insert("k".into(), PerlValue::UNDEF);
3047 assert!(PerlValue::hash(h).is_true());
3048 }
3049
3050 #[test]
3051 fn num_cmp_equal_integers() {
3052 assert_eq!(
3053 PerlValue::integer(5).num_cmp(&PerlValue::integer(5)),
3054 Ordering::Equal
3055 );
3056 }
3057
3058 #[test]
3059 fn str_cmp_compares_lexicographic_string_forms() {
3060 assert_eq!(
3062 PerlValue::integer(2).str_cmp(&PerlValue::integer(10)),
3063 Ordering::Greater
3064 );
3065 }
3066
3067 #[test]
3068 fn to_list_undef_empty() {
3069 assert!(PerlValue::UNDEF.to_list().is_empty());
3070 }
3071
3072 #[test]
3073 fn unwrap_atomic_nested_atomic() {
3074 use parking_lot::Mutex;
3075 let inner = PerlValue::atomic(Arc::new(Mutex::new(PerlValue::integer(2))));
3076 let outer = PerlValue::atomic(Arc::new(Mutex::new(inner)));
3077 assert_eq!(outer.unwrap_atomic().to_int(), 2);
3078 }
3079
3080 #[test]
3081 fn errno_dual_parts_extracts_code_and_message() {
3082 let v = PerlValue::errno_dual(-2, "oops".into());
3083 assert_eq!(v.errno_dual_parts(), Some((-2, "oops".into())));
3084 }
3085
3086 #[test]
3087 fn errno_dual_parts_none_for_plain_string() {
3088 assert!(PerlValue::string("hi".into()).errno_dual_parts().is_none());
3089 }
3090
3091 #[test]
3092 fn errno_dual_parts_none_for_integer() {
3093 assert!(PerlValue::integer(1).errno_dual_parts().is_none());
3094 }
3095
3096 #[test]
3097 fn errno_dual_numeric_context_uses_code_string_uses_msg() {
3098 let v = PerlValue::errno_dual(5, "five".into());
3099 assert_eq!(v.to_int(), 5);
3100 assert_eq!(v.to_string(), "five");
3101 }
3102
3103 #[test]
3104 fn list_range_alpha_joins_like_perl() {
3105 use super::perl_list_range_expand;
3106 let v =
3107 perl_list_range_expand(PerlValue::string("a".into()), PerlValue::string("z".into()));
3108 let s: String = v.iter().map(|x| x.to_string()).collect();
3109 assert_eq!(s, "abcdefghijklmnopqrstuvwxyz");
3110 }
3111
3112 #[test]
3113 fn list_range_numeric_string_endpoints() {
3114 use super::perl_list_range_expand;
3115 let v = perl_list_range_expand(
3116 PerlValue::string("9".into()),
3117 PerlValue::string("11".into()),
3118 );
3119 assert_eq!(v.len(), 3);
3120 assert_eq!(
3121 v.iter().map(|x| x.to_int()).collect::<Vec<_>>(),
3122 vec![9, 10, 11]
3123 );
3124 }
3125
3126 #[test]
3127 fn list_range_leading_zero_is_string_mode() {
3128 use super::perl_list_range_expand;
3129 let v = perl_list_range_expand(
3130 PerlValue::string("01".into()),
3131 PerlValue::string("05".into()),
3132 );
3133 assert_eq!(v.len(), 5);
3134 assert_eq!(
3135 v.iter().map(|x| x.to_string()).collect::<Vec<_>>(),
3136 vec!["01", "02", "03", "04", "05"]
3137 );
3138 }
3139
3140 #[test]
3141 fn list_range_empty_to_letter_one_element() {
3142 use super::perl_list_range_expand;
3143 let v = perl_list_range_expand(
3144 PerlValue::string(String::new()),
3145 PerlValue::string("c".into()),
3146 );
3147 assert_eq!(v.len(), 1);
3148 assert_eq!(v[0].to_string(), "");
3149 }
3150
3151 #[test]
3152 fn magic_string_inc_z_wraps_aa() {
3153 use super::{perl_magic_string_increment_for_range, PerlListRangeIncOutcome};
3154 let mut s = "z".to_string();
3155 assert_eq!(
3156 perl_magic_string_increment_for_range(&mut s),
3157 PerlListRangeIncOutcome::Continue
3158 );
3159 assert_eq!(s, "aa");
3160 }
3161
3162 #[test]
3163 fn test_boxed_numeric_stringification() {
3164 let large_int = 10_000_000_000i64;
3166 let v_int = PerlValue::integer(large_int);
3167 assert_eq!(v_int.to_string(), "10000000000");
3168
3169 let v_inf = PerlValue::float(f64::INFINITY);
3171 assert_eq!(v_inf.to_string(), "inf");
3172 }
3173
3174 #[test]
3175 fn magic_string_inc_nine_to_ten() {
3176 use super::{perl_magic_string_increment_for_range, PerlListRangeIncOutcome};
3177 let mut s = "9".to_string();
3178 assert_eq!(
3179 perl_magic_string_increment_for_range(&mut s),
3180 PerlListRangeIncOutcome::Continue
3181 );
3182 assert_eq!(s, "10");
3183 }
3184}