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