From d39e011ca195b545d7a592675872867b36019761 Mon Sep 17 00:00:00 2001 From: Tudor Roman Date: Fri, 2 Aug 2019 12:07:21 +0300 Subject: [PATCH] Added len function --- src/builtin/len.rs | 34 ++++++++++++++++++++++++++++++++++ src/builtin/mod.rs | 9 ++++++--- 2 files changed, 40 insertions(+), 3 deletions(-) create mode 100644 src/builtin/len.rs diff --git a/src/builtin/len.rs b/src/builtin/len.rs new file mode 100644 index 0000000..9e60228 --- /dev/null +++ b/src/builtin/len.rs @@ -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 . + */ +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 +} diff --git a/src/builtin/mod.rs b/src/builtin/mod.rs index db6800c..8b07c13 100644 --- a/src/builtin/mod.rs +++ b/src/builtin/mod.rs @@ -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 { - BULTINS + BUILTINS .binary_search_by(|b| b.name.cmp(name)) .ok() - .map(|i| BULTINS[i]) + .map(|i| BUILTINS[i]) } -- 2.45.2