sys

A set of unix utils in hare!
Log | Files | Refs | README

wc.ha (1047B)


      1 use fmt;
      2 use io;
      3 use os;
      4 use strings;
      5 use bufio;
      6 use encoding::utf8;
      7 use getopt;
      8 
      9 use util;
     10 
     11 let delim = " ";
     12 
     13 fn run() size = {
     14 	let sc = bufio::newscanner(os::stdin);
     15 	defer bufio::finish(&sc);
     16 
     17 	let count = 0z;
     18 
     19 	for (true) {
     20 		match (bufio::scan_string(&sc, delim)) {
     21 		case let s: str =>
     22 			let ss = strings::split(s, "\n")!;
     23 			count += len(ss);
     24 			free(ss);
     25 		case io::EOF => return count + 1;
     26 		case let e: io::error => util::die(io::strerror(e));
     27 		};
     28 	};
     29 };
     30 
     31 export fn main() void = {
     32 	let cmd = getopt::parse(os::args,
     33 		"word count",
     34 		('l', "count lines"),
     35 		('w', "count words (default)"),
     36 		('c', "count charaters"),
     37 		);
     38 	defer getopt::finish(&cmd);
     39 
     40 	for (let opt .. cmd.opts) {
     41 		switch (opt.0) {
     42 		case 'l' => delim = "\n";
     43 		case 'w' => delim = " ";
     44 		case 'c' => delim = "";
     45 		case => abort();
     46 		};
     47 	};
     48 
     49 	if (len(delim) == 0) {
     50 		free(match (io::drain(os::stdin)) {
     51 		case let buf: []u8 =>
     52 			fmt::println(len(buf))!;
     53 			yield buf;
     54 		case let e: io::error => util::die(io::strerror(e));
     55 		});
     56 	} else fmt::println(run())!;
     57 };