]> gitweb.factorcode.org Git - factor.git/blob - extra/tools/wc/wc.factor
94d8d3f1dfd17984ea7042a97d563ddd55101e7d
[factor.git] / extra / tools / wc / wc.factor
1 ! Copyright (C) 2016 John Benediktsson
2 ! See http://factorcode.org/license.txt for BSD license
3
4 USING: alien.data command-line formatting io io.encodings
5 io.encodings.binary io.files kernel math math.bitwise
6 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 PRIVATE>
34
35 : wc ( path -- n )
36     binary [ count-lines ] with-file-reader ;
37
38 : run-wc ( -- )
39     command-line get [
40         wc-stdin "%8d\n" printf
41     ] [
42         [ [ wc ] keep dupd "%8d %s\n" printf ] map
43         dup length 1 > [ sum "%8d total\n" printf ] [ drop ] if
44     ] if-empty ;
45
46 MAIN: run-wc