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