~tudor/rwsh

d39e011ca195b545d7a592675872867b36019761 — Tudor Roman 4 years ago 964d735
Added len function
2 files changed, 40 insertions(+), 3 deletions(-)

A src/builtin/len.rs
M src/builtin/mod.rs
A src/builtin/len.rs => src/builtin/len.rs +34 -0
@@ 0,0 1,34 @@
/* Copyright (C) 2019 Tudor-Ioan Roman
 *
 * This file is part of the Really Weird Shell, also known as RWSH.
 *
 * RWSH is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * RWSH is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with RWSH. If not, see <http://www.gnu.org/licenses/>.
 */
use crate::shell::{Context, Key, Var, VarValue};

pub fn len(ctx: &mut Context, args: Vec<&str>) -> i32 {
    if args.len() != 2 {
        eprintln!("Usage: len variable");
        return 2;
    }
    match ctx
        .state
        .get_var(Key::Var(args[1]))
        .unwrap_or(Var::empty(args[1].to_owned()))
        .value
    {
        VarValue::Array(arr) => println!("{}", arr.len()),
    }
    0
}

M src/builtin/mod.rs => src/builtin/mod.rs +6 -3
@@ 21,12 21,14 @@ mod calc;
mod cd;
mod eval;
mod exit;
mod len;
mod r#let;
mod r#true;
use self::calc::calc;
use cd::cd;
use eval::eval;
use exit::exit;
use len::len;
use r#let::r#let;
use r#true::{r#false, r#true};



@@ 51,7 53,7 @@ macro_rules! b {
        }
    };
}
static BULTINS: [Builtin; 7] = [
static BUILTINS: &'static [Builtin] = &[
    // keep sorted pls
    b!(calc),
    b!(cd),


@@ 61,6 63,7 @@ static BULTINS: [Builtin; 7] = [
        name: "false",
        func: r#false,
    },
    b!(len),
    Builtin {
        name: "let",
        func: r#let,


@@ 73,8 76,8 @@ static BULTINS: [Builtin; 7] = [

/// Find a built-in function by name.
pub fn get_builtin(name: &str) -> Option<Builtin> {
    BULTINS
    BUILTINS
        .binary_search_by(|b| b.name.cmp(name))
        .ok()
        .map(|i| BULTINS[i])
        .map(|i| BUILTINS[i])
}