Simplify in a lot of places using odr_strdupn
[yaz-moved-to-github.git] / src / iconv_encode_wchar.c
1 /* This file is part of the YAZ toolkit.
2  * Copyright (C) 1995-2013 Index Data
3  * See the file LICENSE for details.
4  */
5 /**
6  * \file
7  * \brief WCHAR_T iconv encoding / decoding
8  */
9
10 #if HAVE_CONFIG_H
11 #include <config.h>
12 #endif
13
14 #include <assert.h>
15 #include <errno.h>
16 #include <string.h>
17 #if HAVE_WCHAR_H
18 #include <wchar.h>
19 #endif
20
21 #include <yaz/xmalloc.h>
22 #include "iconv-p.h"
23
24 struct encoder_data
25 {
26     unsigned long compose_char;
27 };
28
29 #if HAVE_WCHAR_H
30 static size_t write_wchar_t(yaz_iconv_t cd, yaz_iconv_encoder_t en,
31                             unsigned long x,
32                             char **outbuf, size_t *outbytesleft)
33 {
34     unsigned char *outp = (unsigned char *) *outbuf;
35
36     if (*outbytesleft >= sizeof(wchar_t))
37     {
38         wchar_t wch = x;
39         memcpy(outp, &wch, sizeof(wch));
40         outp += sizeof(wch);
41         (*outbytesleft) -= sizeof(wch);
42     }
43     else
44     {
45         yaz_iconv_set_errno(cd, YAZ_ICONV_E2BIG);
46         return (size_t)(-1);
47     }
48     *outbuf = (char *) outp;
49     return 0;
50 }
51 #endif
52
53 yaz_iconv_encoder_t yaz_wchar_encoder(const char *tocode,
54                                       yaz_iconv_encoder_t e)
55
56 {
57 #if HAVE_WCHAR_H
58     if (!yaz_matchstr(tocode, "wchar_t"))
59     {
60         e->write_handle = write_wchar_t;
61         return e;
62     }
63 #endif
64     return 0;
65 }
66
67 #if HAVE_WCHAR_H
68 static unsigned long read_wchar_t(yaz_iconv_t cd, yaz_iconv_decoder_t d,
69                                   unsigned char *inp,
70                                   size_t inbytesleft, size_t *no_read)
71 {
72     unsigned long x = 0;
73
74     if (inbytesleft < sizeof(wchar_t))
75     {
76         yaz_iconv_set_errno(cd, YAZ_ICONV_EINVAL); /* incomplete input */
77         *no_read = 0;
78     }
79     else
80     {
81         wchar_t wch;
82         memcpy(&wch, inp, sizeof(wch));
83         x = wch;
84         *no_read = sizeof(wch);
85     }
86     return x;
87 }
88 #endif
89
90 yaz_iconv_decoder_t yaz_wchar_decoder(const char *fromcode,
91                                       yaz_iconv_decoder_t d)
92
93 {
94 #if HAVE_WCHAR_H
95     if (!yaz_matchstr(fromcode, "wchar_t"))
96     {
97         d->read_handle = read_wchar_t;
98         return d;
99     }
100 #endif
101     return 0;
102 }
103
104
105 /*
106  * Local variables:
107  * c-basic-offset: 4
108  * c-file-style: "Stroustrup"
109  * indent-tabs-mode: nil
110  * End:
111  * vim: shiftwidth=4 tabstop=8 expandtab
112  */
113