]> git.tdb.fi Git - libs/core.git/blob - source/stringcodec/utf16.h
Add a UTF-16 codec
[libs/core.git] / source / stringcodec / utf16.h
1 #ifndef MSP_STRINGCODEC_UTF16_H_
2 #define MSP_STRINGCODEC_UTF16_H_
3
4 #include "codec.h"
5
6 namespace Msp {
7 namespace StringCodec {
8
9 /**
10 The UTF-16 codec, as specified in the Unicode standard.  Both little and big
11 endian are supported, as well as autodetection with the BOM.  In the absence
12 of a BOM, big endian is assumed.
13 */
14 class Utf16: public StandardCodec<Utf16>
15 {
16 public:
17         enum Endian
18         {
19                 AUTO,
20                 BIG,
21                 LITTLE
22         };
23
24         class Encoder: public Codec::Encoder
25         {
26         private:
27                 Endian endian;
28                 bool emit_bom;
29
30         public:
31                 Encoder(ErrorMode em = DEFAULT, Endian en = BIG);
32
33                 virtual void encode_char(unichar, std::string &);
34         private:
35                 virtual void transliterate(unichar, std::string &);
36         };
37
38         class Decoder: public Codec::Decoder
39         {
40         private:
41                 Endian endian;
42
43         public:
44                 Decoder(ErrorMode em = DEFAULT, Endian en = AUTO);
45
46                 virtual unichar decode_char(const std::string &, std::string::const_iterator &);
47         private:
48                 unichar decode_unit(const std::string &, const std::string::const_iterator &, std::string::const_iterator &);
49         };
50
51 private:
52         Endian endian;
53
54 public:
55         Utf16(ErrorMode em = DEFAULT, Endian en = AUTO):
56                 StandardCodec<Utf16>(em),
57                 endian(en)
58         { }
59
60         virtual const char *get_name() const
61         { return endian==BIG ? "UTF-16-BE" : "UTF-16-LE"; }
62
63         virtual Encoder *create_encoder(ErrorMode em = DEFAULT) const
64         { return new Encoder(get_error_mode(em), endian); }
65
66         virtual Decoder *create_decoder(ErrorMode em = DEFAULT) const
67         { return new Decoder(get_error_mode(em), endian); }
68 };
69
70
71 /**
72 A helper template to define the Utf16Be and Utf16Le types.
73 */
74 template<Utf16::Endian en>
75 class Utf16E: public Utf16
76 {
77 public:
78         class Encoder: public Utf16::Encoder
79         {
80         public:
81                 Encoder(ErrorMode em = DEFAULT): Utf16::Encoder(em, en) { }
82         };
83
84         class Decoder: public Utf16::Decoder
85         {
86         public:
87                 Decoder(ErrorMode em = DEFAULT): Utf16::Decoder(em, en) { }
88         };
89
90         Utf16E(ErrorMode em = DEFAULT): Utf16(em, en) { }
91 };
92
93 typedef Utf16E<Utf16::BIG> Utf16Be;
94 typedef Utf16E<Utf16::LITTLE> Utf16Le;
95
96 } // namespace StringCodec
97 } // namespace Msp
98
99 #endif