1 ! (c)2010 Joe Groff bsd license
2 USING: accessors byte-arrays byte-arrays.hex combinators
3 continuations fry io io.encodings io.encodings.8-bit.latin1
4 io.encodings.ascii io.encodings.binary io.encodings.iana
5 io.encodings.string io.encodings.utf16 io.encodings.utf32
6 io.encodings.utf8 io.files io.streams.string kernel literals
7 math namespaces sequences strings ;
8 IN: io.encodings.detect
10 SYMBOL: default-8bit-encoding
11 default-8bit-encoding [ latin1 ] initialize
15 : prolog-tag ( bytes -- string )
16 CHAR: > over index [ 1 + head-slice ] when* >string ;
18 : prolog-encoding ( string -- iana-encoding )
20 _ "encoding=" over start
21 10 + swap [ [ 1 - ] dip nth ] [ index-from ] [ swapd subseq ] 2tri
22 ] [ drop "UTF-8" ] recover ;
24 : detect-xml-prolog ( bytes -- encoding )
25 prolog-tag prolog-encoding name>encoding [ ascii ] unless* ;
27 : valid-utf8? ( bytes -- ? )
28 utf8 decode 1 head-slice* replacement-char swap member? not ;
32 : detect-byte-array ( bytes -- encoding )
34 { [ dup HEX{ 0000FEFF } head? ] [ drop utf32be ] }
35 { [ dup HEX{ FFFE0000 } head? ] [ drop utf32le ] }
36 { [ dup HEX{ FEFF } head? ] [ drop utf16be ] }
37 { [ dup HEX{ FFFE } head? ] [ drop utf16le ] }
38 { [ dup HEX{ EF BB BF } head? ] [ drop utf8 ] }
39 { [ dup $[ "<?xml" >byte-array ] head? ] [ detect-xml-prolog ] }
40 { [ 0 over member? ] [ drop binary ] }
41 { [ dup empty? ] [ drop utf8 ] }
42 { [ dup valid-utf8? ] [ drop utf8 ] }
43 [ drop default-8bit-encoding get ]
46 : detect-stream ( stream -- sample encoding )
47 256 swap stream-read dup detect-byte-array ;
49 : detect-file ( file -- encoding )
50 binary [ input-stream get detect-stream nip ] with-file-reader ;