CCL: slight reformat
[yaz-moved-to-github.git] / src / iconv_encode_danmarc.c
1 /* This file is part of the YAZ toolkit.
2  * Copyright (C) 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 == '@' || x == '*')
29     {
30         if (*outbytesleft < 2)
31         {
32             yaz_iconv_set_errno(cd, YAZ_ICONV_E2BIG);
33             return (size_t)(-1);
34         }
35         *outp++ = '@';
36         (*outbytesleft)--;
37         *outp++ = (unsigned char) 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++ = (unsigned char) x;
48         (*outbytesleft)--;
49     }
50     else
51     {
52         if (*outbytesleft < 6)
53         {
54             yaz_iconv_set_errno(cd, YAZ_ICONV_E2BIG);
55             return (size_t)(-1);
56         }
57         switch (x)
58         {
59         case 0xa733:
60             *outp++ = '@';
61             *outp++ = 0xe5;
62             (*outbytesleft) -= 2;
63             break;
64         case 0xa732:
65             *outp++ = '@';
66             *outp++ = 0xc5;
67             (*outbytesleft) -= 2;
68             break;
69         default:
70             /* full unicode, emit @XXXX */
71             sprintf(*outbuf, "@%04lX", x);
72             outp += 5;
73             (*outbytesleft) -= 5;
74             break;
75         }
76     }
77     *outbuf = (char *) outp;
78     return 0;
79 }
80
81 yaz_iconv_encoder_t yaz_danmarc_encoder(const char *tocode,
82                                         yaz_iconv_encoder_t e)
83
84 {
85     if (!yaz_matchstr(tocode, "danmarc"))
86     {
87         e->write_handle = write_danmarc;
88         return e;
89     }
90     return 0;
91 }
92
93
94 /*
95  * Local variables:
96  * c-basic-offset: 4
97  * c-file-style: "Stroustrup"
98  * indent-tabs-mode: nil
99  * End:
100  * vim: shiftwidth=4 tabstop=8 expandtab
101  */
102