]> gitweb.factorcode.org Git - factor.git/blob - extra/tools/wc/wc.factor
Switch to https urls
[factor.git] / extra / tools / wc / wc.factor
1 ! Copyright (C) 2016 John Benediktsson
2 ! See https://factorcode.org/license.txt for BSD license
3
4 USING: alien.data command-line io io.encodings
5 io.encodings.binary io.files kernel math math.bitwise
6 math.parser math.vectors math.vectors.simd namespaces sequences
7 specialized-arrays ;
8
9 SPECIALIZED-ARRAY: uchar-16
10
11 IN: tools.wc
12
13 <PRIVATE
14
15 : aligned-slices ( seq -- head tail )
16     dup length 0xf unmask cut-slice ; inline
17
18 : count-characters ( -- n )
19     0 [ length + ] each-block-slice ; inline
20
21 : count-lines ( -- n )
22     0 [
23         aligned-slices [
24             uchar-16 cast-array swap
25             [ CHAR: \n uchar-16-with v= vcount + >fixnum ] reduce
26         ] [ [ CHAR: \n = ] count + >fixnum ] bi*
27     ] each-block-slice ; inline
28
29 : wc-stdin ( -- n )
30     input-stream get binary re-decode
31     [ count-lines ] with-input-stream* ;
32
33 : print-wc ( n name/f -- )
34     [ number>string 8 CHAR: \s pad-head write ]
35     [ bl [ write ] when* ] bi* nl ;
36
37 PRIVATE>
38
39 : wc ( path -- n )
40     binary [ count-lines ] with-file-reader ;
41
42 : run-wc ( -- )
43     command-line get [
44         wc-stdin f print-wc
45     ] [
46         [
47             dup file-exists? [
48                 [ wc ] keep dupd print-wc
49             ] [
50                 write ": not found" print flush f
51             ] if
52         ] map sift dup length 1 > [ sum "total" print-wc ] [ drop ] if
53     ] if-empty ;
54
55 MAIN: run-wc