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