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