Update copyright.
[shibboleth/cpp-xmltooling.git] / xmltooling / unicode.cpp
1 /*
2  *  Copyright 2001-2007 Internet2
3  * 
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /**
18  * unicode.cpp
19  * 
20  * Helper classes and types for manipulating Unicode 
21  */
22
23 #include "internal.h"
24 #include "unicode.h"
25
26 #include <xercesc/util/XMLUTF8Transcoder.hpp>
27 #include <xercesc/util/XMLUniDefs.hpp>
28
29 static const XMLCh UTF8[]={ chLatin_U, chLatin_T, chLatin_F, chDigit_8, chNull };
30
31 char* xmltooling::toUTF8(const XMLCh* src)
32 {
33     unsigned int eaten;
34     unsigned int srclen=XMLString::stringLen(src);
35     XMLUTF8Transcoder t(UTF8, srclen*4 + 1);
36     char* buf=new char[srclen*4 + 1];
37     memset(buf,0,srclen*4 + 1);
38     t.transcodeTo(
39         src,srclen,
40         reinterpret_cast<XMLByte*>(buf),srclen*4,
41         eaten,XMLTranscoder::UnRep_RepChar);
42     return buf;
43 }
44
45 XMLCh* xmltooling::fromUTF8(const char* src)
46 {
47     unsigned int eaten;
48     unsigned int srclen=strlen(src);
49     XMLUTF8Transcoder t(UTF8, srclen + 1);
50     XMLCh* buf=new XMLCh[srclen + 1];
51     unsigned char* sizes=new unsigned char[srclen];
52     memset(buf,0,(srclen+1)*sizeof(XMLCh));
53     t.transcodeFrom(
54         reinterpret_cast<const XMLByte*>(src),srclen,
55         buf,srclen,
56         eaten,sizes);
57     delete[] sizes;
58     return buf;
59 }
60
61 std::ostream& xmltooling::operator<<(std::ostream& ostr, const XMLCh* s)
62 {
63     if (s) {
64         char* p=xmltooling::toUTF8(s);
65         ostr << p;
66         delete[] p;
67     }
68     return ostr;
69 }