Port builtin count to rust (#9963)

* Port builtin count to rust

* Explicitly use wstring
This commit is contained in:
Fabian Boehm
2023-08-18 23:18:52 +02:00
committed by GitHub
parent a29aa44183
commit 566123edc6
5 changed files with 40 additions and 37 deletions

View File

@@ -0,0 +1,33 @@
use super::prelude::*;
// How many bytes we read() at once.
// Since this is just for counting, it can be massive.
const COUNT_CHUNK_SIZE: usize = 512 * 256;
/// Implementation of the builtin count command, used to count the number of arguments sent to it.
pub fn count(
_parser: &mut parser_t,
streams: &mut io_streams_t,
argv: &mut [&wstr],
) -> Option<c_int> {
// Always add the size of argv (minus 0, which is "count").
// That means if you call `something | count a b c`, you'll get the count of something _plus 3_.
let mut numargs = argv.len() - 1;
// (silly variable for Arguments to do nothing with)
let mut zero = 0;
// Count the newlines coming in via stdin like `wc -l`.
// This means excluding lines that don't end in a newline!
numargs += Arguments::new(&[] as _, &mut zero, streams, COUNT_CHUNK_SIZE)
// second is "want_newline" - whether the line ended in a newline
.filter(|x| x.1)
.count();
streams.out.appendln(numargs.to_wstring());
if numargs == 0 {
return STATUS_CMD_ERROR;
}
STATUS_CMD_OK
}

View File

@@ -8,6 +8,7 @@
pub mod cd;
pub mod command;
pub mod contains;
pub mod count;
pub mod echo;
pub mod emit;
pub mod exit;

View File

@@ -240,6 +240,7 @@ pub fn run_builtin(
RustBuiltin::Cd => super::cd::cd(parser, streams, args),
RustBuiltin::Contains => super::contains::contains(parser, streams, args),
RustBuiltin::Command => super::command::command(parser, streams, args),
RustBuiltin::Count => super::count::count(parser, streams, args),
RustBuiltin::Echo => super::echo::echo(parser, streams, args),
RustBuiltin::Emit => super::emit::emit(parser, streams, args),
RustBuiltin::Exit => super::exit::exit(parser, streams, args),