]> git.tdb.fi Git - libs/core.git/blob - source/jisx0208.cpp
Initial upload
[libs/core.git] / source / jisx0208.cpp
1 #include "jisx0208.h"
2
3 #include "jisx0208.table"
4
5 using namespace std;
6
7 namespace Msp {
8
9 void JisX0208::Encoder::encode_char(wchar_t ucs)
10 {
11         unsigned short jis=ucs_to_jisx0208(ucs);
12         if(!jis) throw CodecError("Can't express character in JIS X 0208");
13
14         char buf[2]={jis>>8, jis};
15         append(buf, 2);
16 }
17
18
19 void JisX0208::Decoder::decode_char(const string &str, string::const_iterator &i)
20 {
21         if(i==str.end())
22                 return;
23
24         if(!high)
25                 high=*i++;
26
27         if(i==str.end())
28                 return;
29
30         wchar_t ucs=jisx0208_to_ucs(high<<8 | *i++);
31         high=0;
32
33         if(!ucs)
34                 throw CodecError("Invalid JIS X 0208 string (undefined character)");
35
36         append(ucs);
37 }
38
39 void JisX0208::Decoder::sync()
40 {
41         if(high)
42                 throw CodecError("Sync in middle of JIS X 0208 character");
43 }
44
45
46 wchar_t jisx0208_to_ucs(unsigned short jis)
47 {
48         if((jis&0xFF)<0x21 || (jis&0xFF)>0x7E || (jis&0xFF00)<0x2100 || (jis&0xFF00)>0x7E00)
49                 return 0;
50
51         return jisx0208_to_ucs_table[((jis>>8)&0xFF)*94 + (jis&0xFF)-0x21*95];
52 }
53
54 unsigned short ucs_to_jisx0208(wchar_t c)
55 {
56         if(c&0xFFFF0000) return 0;
57
58         unsigned i=0;
59         for(unsigned bit=0x1000; bit; bit>>=1)
60         {
61                 if(i+bit>=ucs_to_jisx0208_table_size)
62                         continue;
63                 if(ucs_to_jisx0208_table[i+bit].ucs<=(unsigned short)c)
64                         i+=bit;
65         }
66
67         if(ucs_to_jisx0208_table[i].ucs==(unsigned short)c)
68                 return ucs_to_jisx0208_table[i].jis;
69         return 0;
70 }
71
72 } // namespace Msp