]> gitweb.factorcode.org Git - factor.git/blob - basis/io/encodings/utf32/utf32.factor
ba0938e1c0136d45c6d58fc0a391b35d893c4577
[factor.git] / basis / io / encodings / utf32 / utf32.factor
1 ! Copyright (C) 2009 Daniel Ehrenberg.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: math kernel io.encodings combinators io io.encodings.utf16
4 sequences io.binary io.encodings.iana ;
5 IN: io.encodings.utf32
6
7 SINGLETON: utf32be
8
9 utf32be "UTF-32BE" register-encoding
10
11 SINGLETON: utf32le
12
13 utf32le "UTF-32LE" register-encoding
14
15 SINGLETON: utf32
16
17 utf32 "UTF-32" register-encoding
18
19 <PRIVATE
20
21 ! Decoding
22
23 : char> ( stream quot -- ch )
24     swap [ 4 ] dip stream-read dup length {
25         { 0 [ 2drop f ] }
26         { 4 [ swap call ] }
27         [ 3drop replacement-char ]
28     } case ; inline
29
30 M: utf32be decode-char drop [ be> ] char> ;
31
32 M: utf32le decode-char drop [ le> ] char> ;
33
34 ! Encoding
35
36 : >char ( char stream quot -- )
37     4 swap curry dip stream-write ; inline
38
39 M: utf32be encode-char drop [ >be ] >char ;
40
41 M: utf32le encode-char drop [ >le ] >char ;
42
43 ! UTF-32
44
45 CONSTANT: bom-le B{ 0xff 0xfe 0 0 }
46
47 CONSTANT: bom-be B{ 0 0 0xfe 0xff }
48
49 : bom>le/be ( bom -- le/be )
50     dup bom-le sequence= [
51         drop utf32le
52     ] [
53         bom-be sequence= [ utf32be ] [ missing-bom ] if
54     ] if ;
55
56 M: utf32 <decoder>
57     drop 4 over stream-read bom>le/be <decoder> ;
58
59 M: utf32 <encoder>
60     drop bom-le over stream-write utf32le <encoder> ;
61
62 PRIVATE>