]> git.tdb.fi Git - libs/core.git/blob - source/codec.cpp
efc981492f18a08d766eb0c39932548adecfd8c5
[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         }
29         catch(const CodecError &)
30         {
31                 result=false;
32         }
33
34         delete dec;
35
36         return result;
37 }
38
39 /**
40 Creates a codec for the given encoding.  The caller is responsible for deleting
41 the codec when it's no longer needed.
42 */
43 StringCodec *create_codec(const string &n)
44 {
45         string name;
46         for(string::const_iterator i=n.begin(); i!=n.end(); ++i)
47         {
48                 if(isupper(*i))
49                         name+=tolower(*i);
50                 else if(islower(*i) || isdigit(*i))
51                         name+=*i;
52         }
53
54         if(name=="ascii") return new Ascii;
55         if(name=="iso2022jp") return new Iso2022Jp;
56         if(name=="iso646fi") return new Iso646Fi;
57         if(name=="jisx0201") return new JisX0201;
58         if(name=="jisx0208") return new JisX0208;
59         if(name=="latin1") return new Latin1;
60         if(name=="utf8") return new Utf8;
61         throw InvalidParameterValue("Unknown string codec");
62 }
63
64 } // namespace Msp