Improve error reporting for ICU chains YAZ-707
[yaz-moved-to-github.git] / src / iconv_encode_danmarc.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 Danmarc2 character set encoding
8  */
9
10 #if HAVE_CONFIG_H
11 #include <config.h>
12 #endif
13
14 #include <assert.h>
15 #include <stdio.h>
16 #include <errno.h>
17 #include <string.h>
18
19 #include <yaz/xmalloc.h>
20 #include "iconv-p.h"
21
22 static size_t write_danmarc(yaz_iconv_t cd, yaz_iconv_encoder_t en,
23                             unsigned long x,
24                             char **outbuf, size_t *outbytesleft)
25 {
26     unsigned char *outp = (unsigned char *) *outbuf;
27
28     if (x == '@')
29     {
30         if (*outbytesleft < 2)
31         {
32             yaz_iconv_set_errno(cd, YAZ_ICONV_E2BIG);
33             return (size_t)(-1);
34         }
35         *outp++ = x;
36         (*outbytesleft)--;
37         *outp++ = x;
38         (*outbytesleft)--;
39     }
40     else if (x <= 255)
41     {  /* latin-1 range */
42         if (*outbytesleft < 1)
43         {
44             yaz_iconv_set_errno(cd, YAZ_ICONV_E2BIG);
45             return (size_t)(-1);
46         }
47         *outp++ = x;
48         (*outbytesleft)--;
49     }
50     else
51     {  /* full unicode, emit @XXXX */
52         if (*outbytesleft < 6)
53         {
54             yaz_iconv_set_errno(cd, YAZ_ICONV_E2BIG);
55             return (size_t)(-1);
56         }
57         sprintf(*outbuf, "@%04lX", x);
58         outp += 5;
59         (*outbytesleft) -= 5;
60     }
61     *outbuf = (char *) outp;
62     return 0;
63 }
64
65 yaz_iconv_encoder_t yaz_danmarc_encoder(const char *tocode,
66                                         yaz_iconv_encoder_t e)
67
68 {
69     if (!yaz_matchstr(tocode, "danmarc"))
70     {
71         e->write_handle = write_danmarc;
72         return e;
73     }
74     return 0;
75 }
76
77
78 /*
79  * Local variables:
80  * c-basic-offset: 4
81  * c-file-style: "Stroustrup"
82  * indent-tabs-mode: nil
83  * End:
84  * vim: shiftwidth=4 tabstop=8 expandtab
85  */
86