]> git.tdb.fi Git - libs/core.git/blob - source/codec.cpp
More sophisticated error handling
[libs/core.git] / source / codec.cpp
1 #include "ascii.h"
2 #include "codec.h"
3 #include "iso2022jp.h"
4 #include "iso646fi.h"
5 #include "jisx0201.h"
6 #include "jisx0208.h"
7 #include "latin1.h"
8 #include "utf8.h"
9
10 using namespace std;
11
12 namespace Msp {
13
14 /**
15 Determines whether the given string can be successfully decoded with this
16 codec.  Note that this function returning true does not guarantee that the
17 string was actually encoded with this codec.  In particular, many 8-bit
18 encodings are indistinguishable.
19 */
20 bool StringCodec::detect(const string &str) const
21 {
22         Decoder *dec=create_decoder();
23         bool result=true;
24         try
25         {
26                 for(string::const_iterator i=str.begin(); i!=str.end(); )
27                         dec->decode_char(str, i);
28                 dec->sync();
29         }
30         catch(const CodecError &)
31         {
32                 result=false;
33         }
34
35         delete dec;
36
37         return result;
38 }
39
40 void StringCodec::Encoder::error(const string &msg)
41 {
42         switch(err_mode_)
43         {
44         case IGNORE_ERRORS: break;
45         case REPLACE_ERRORS: append_replacement(); break;
46         default: throw CodecError(msg);
47         }
48 }
49
50 void StringCodec::Decoder::error(const string &msg)
51 {
52         switch(err_mode_)
53         {
54         case IGNORE_ERRORS: break;
55         case REPLACE_ERRORS: append(0xFFFD); break;
56         default: throw CodecError(msg);
57         }
58 }
59
60 /**
61 Creates a codec for the given encoding.  The caller is responsible for deleting
62 the codec when it's no longer needed.
63 */
64 StringCodec *create_codec(const string &n)
65 {
66         string name;
67         for(string::const_iterator i=n.begin(); i!=n.end(); ++i)
68         {
69                 if(isupper(*i))
70                         name+=tolower(*i);
71                 else if(islower(*i) || isdigit(*i))
72                         name+=*i;
73         }
74
75         if(name=="ascii") return new Ascii;
76         if(name=="iso2022jp") return new Iso2022Jp;
77         if(name=="iso646fi") return new Iso646Fi;
78         if(name=="jisx0201") return new JisX0201;
79         if(name=="jisx0208") return new JisX0208;
80         if(name=="latin1") return new Latin1;
81         if(name=="utf8") return new Utf8;
82         throw InvalidParameterValue("Unknown string codec");
83 }
84
85 } // namespace Msp