]> git.tdb.fi Git - libs/core.git/blob - source/stringcodec/jisx0208.cpp
Move files around to prepare for assimilation into core
[libs/core.git] / source / stringcodec / jisx0208.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 "jisx0208.h"
9
10 #include "jisx0208.table"
11
12 using namespace std;
13
14 namespace Msp {
15 namespace Codecs {
16
17 void JisX0208::Encoder::encode_char(UnicodeChar ucs, string &buf)
18 {
19         unsigned short jis = ucs_to_jisx0208(ucs);
20         if(jis)
21         {
22                 char jbuf[2] = {jis>>8, jis};
23                 buf.append(jbuf, 2);
24         }
25         else
26                 error(ucs, buf, "Can't express character in JIS X 0208");
27 }
28
29 void JisX0208::Encoder::transliterate(UnicodeChar, string &buf)
30 {
31         buf.append("!)", 2);
32 }
33
34
35 UnicodeChar JisX0208::Decoder::decode_char(const string &str, string::const_iterator &i)
36 {
37         if(i==str.end())
38                 return error("No input");
39
40         string::const_iterator j = i;
41         Kuten jis;
42         jis.ku = *j++-0x20;
43
44         UnicodeChar result;
45         if(j==str.end())
46                 result = error("Incomplete JIS X 0208 character");
47         else
48         {
49                 jis.ten = *j++-0x20;
50                 result = jisx0208_to_ucs(jis);
51                 if(result==0)
52                         result = error("Undefined JIS X 0208 character");
53         }
54
55         i = j;
56         return result;
57 }
58
59
60 UnicodeChar jisx0208_to_ucs(Kuten jis)
61 {
62         if(jis.ku==0 || jis.ku>0x5E || jis.ten==0 || jis.ten>0x5E)
63                 return 0;
64
65         return jisx0208_to_ucs_table[jis.ku*94 + jis.ten - 95];
66 }
67
68 Kuten ucs_to_jisx0208(UnicodeChar c)
69 {
70         if(c<0 || c>0xFFFF)
71                 return Kuten();
72
73         unsigned i = 0;
74         for(unsigned bit=0x1000; bit; bit>>=1)
75         {
76                 if(i+bit>=ucs_to_jisx0208_table_size)
77                         continue;
78                 if(ucs_to_jisx0208_table[i+bit].ucs<=static_cast<unsigned short>(c))
79                         i += bit;
80         }
81
82         Kuten result;
83         if(ucs_to_jisx0208_table[i].ucs==static_cast<unsigned short>(c))
84         {
85                 result.ku = (ucs_to_jisx0208_table[i].jis>>8)+1;
86                 result.ten = ucs_to_jisx0208_table[i].jis+1;
87         }
88
89         return result;
90 }
91
92 } // namespace Codecs
93 } // namespace Msp