iocaine 2.2.0

The deadliest poison known to AI
Documentation
// SPDX-FileCopyrightText: 2025 Gergely Nagy
// SPDX-FileContributor: Gergely Nagy
//
// SPDX-License-Identifier: MIT

use roto::{Runtime, Val, roto_method, roto_static_method};
use std::cell::RefCell;
use std::ops::{Deref, DerefMut};
use std::rc::Rc;
use std::sync::Arc;

use crate::means_of_production::Error;

#[derive(Debug, Clone, Default)]
pub struct MutableStringList(pub Rc<RefCell<Vec<String>>>);
pub type StringList = Arc<Vec<String>>;

impl Deref for MutableStringList {
    type Target = Rc<RefCell<Vec<String>>>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl DerefMut for MutableStringList {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

pub fn register_string_list(runtime: &mut Runtime) -> Result<(), Error> {
    runtime.register_clone_type_with_name::<MutableStringList>(
        "MutableStringList",
        "Mutable list of strings",
    )?;
    runtime
        .register_clone_type_with_name::<StringList>("StringList", "Read-only list of strings")?;

    #[roto_static_method(runtime, MutableStringList)]
    fn new() -> Val<MutableStringList> {
        MutableStringList(Rc::new(RefCell::new(Vec::new()))).into()
    }

    #[roto_method(runtime, MutableStringList)]
    fn push(l: Val<MutableStringList>, s: Arc<str>) -> Val<MutableStringList> {
        (*l).borrow_mut().push(s.to_string());
        l
    }

    #[roto_method(runtime, MutableStringList)]
    fn get(l: Val<MutableStringList>) -> Val<StringList> {
        Arc::new((*l).borrow().clone()).into()
    }

    #[roto_method(runtime, MutableStringList)]
    fn join(l: Val<MutableStringList>, separator: Arc<str>) -> Arc<str> {
        (*l).borrow().join(separator.as_ref()).into()
    }

    #[roto_method(runtime, Arc<str>)]
    fn split_by(s: Arc<str>, delimiter: Arc<str>) -> Val<MutableStringList> {
        let split: Vec<String> = s
            .as_ref()
            .split(delimiter.as_ref())
            .map(std::borrow::ToOwned::to_owned)
            .collect();
        MutableStringList(Rc::new(RefCell::new(split))).into()
    }

    Ok(())
}