mumu-string 0.1.0

String functions and tools plugin for the Lava language
Documentation
use mumu::parser::types::Value;
use crate::common::{is_placeholder, make_three_arg_partial};

pub fn string_replace_bridge(_interp: &mut mumu::parser::interpreter::Interpreter, args: Vec<Value>) -> Result<Value, String> {
    match args.len() {
        0 => Ok(make_three_arg_partial(string_replace_finalize, None, None, None)),
        1 => Ok(make_three_arg_partial(string_replace_finalize, Some(args[0].clone()), None, None)),
        2 => Ok(make_three_arg_partial(string_replace_finalize, Some(args[0].clone()), Some(args[1].clone()), None)),
        3 => {
            let s = &args[0];
            let from = &args[1];
            let to = &args[2];
            let s_pl = is_placeholder(s);
            let from_pl = is_placeholder(from);
            let to_pl = is_placeholder(to);
            if !s_pl && !from_pl && !to_pl {
                string_replace_finalize(vec![s.clone(), from.clone(), to.clone()])
            } else {
                Ok(make_three_arg_partial(
                    string_replace_finalize,
                    if s_pl { None } else { Some(s.clone()) },
                    if from_pl { None } else { Some(from.clone()) },
                    if to_pl { None } else { Some(to.clone()) },
                ))
            }
        }
        n => Err(format!("string:replace => expected up to 3 arguments, got {}", n)),
    }
}

fn string_replace_finalize(mut args: Vec<Value>) -> Result<Value, String> {
    if args.len() != 3 {
        return Err(format!(
            "string:replace => finalize => expected 3 real args, got {}", args.len()));
    }
    let s_val = args.remove(0);
    let from_val = args.remove(0);
    let to_val = args.remove(0);
    let s = match s_val {
        Value::SingleString(s) => s,
        Value::StrArray(ss) if ss.len() == 1 => ss[0].clone(),
        other => return Err(format!("string:replace => first arg must be a string, got {:?}", other)),
    };
    let from = match from_val {
        Value::SingleString(s) => s,
        Value::StrArray(ss) if ss.len() == 1 => ss[0].clone(),
        other => return Err(format!("string:replace => second arg must be a string, got {:?}", other)),
    };
    let to = match to_val {
        Value::SingleString(s) => s,
        Value::StrArray(ss) if ss.len() == 1 => ss[0].clone(),
        other => return Err(format!("string:replace => third arg must be a string, got {:?}", other)),
    };
    Ok(Value::SingleString(s.replace(&from, &to)))
}