]> asedeno.scripts.mit.edu Git - 1ts-debian.git/blob - zephyr/lib/ZMakeZcode.c
these should have been added when the branch was merged. *sigh*
[1ts-debian.git] / zephyr / lib / ZMakeZcode.c
1 /* This file is part of the Project Athena Zephyr Notification System.
2  * It contains source for the ZMakeZcode function.
3  *
4  *      Created by:     Jeffrey Hutzelman
5  *
6  *      $Id$
7  *
8  *      Copyright (c) 1987, 2002 by the Massachusetts Institute of Technology.
9  *      For copying and distribution information, see the file
10  *      "mit-copyright.h". 
11  */
12
13 #include <internal.h>
14 #include <assert.h>
15
16 #ifndef lint
17 static const char rcsid_ZMakeZcode_c[] = "$Id$";
18 #endif
19
20 Code_t ZMakeZcode32(ptr, len, val)
21     char *ptr;
22     int len;
23     unsigned long val;
24 {
25     unsigned char buf[4];
26     buf[0] = (val >> 24) & 0xff;
27     buf[1] = (val >> 16) & 0xff;
28     buf[2] = (val >>  8) & 0xff;
29     buf[3] =  val        & 0xff;
30     return ZMakeZcode(ptr, len, buf, 4);
31 }
32
33 Code_t ZMakeZcode(ptr, len, field, num)
34     register char *ptr;
35     int len;
36     unsigned char *field;
37     int num;
38 {
39     int i;
40
41     /*
42      * This optimistic check lets us discover quickly if the buffer
43      * is not even large enough to hold the field without escapes.
44      * It also insures we'll have space for the leading 'Z' and the
45      * trailing NUL.  Note that this does _not_ remove the need for
46      * checking length as we encode.
47      */
48     if (len < num + 2)
49       return ZERR_FIELDLEN;
50     *ptr++ = 'Z';
51     --len;
52     for (i=0;i<num;i++) {
53         switch (field[i]) {
54             case 0x00:
55                 if (len < 3)
56                     return ZERR_FIELDLEN;
57                 *ptr++ = 0xff;
58                 *ptr++ = 0xf0;
59                 len -= 2;
60                 continue;
61
62             case 0xff:
63                 if (len < 3)
64                     return ZERR_FIELDLEN;
65                 *ptr++ = 0xff;
66                 *ptr++ = 0xf1;
67                 len -= 2;
68                 continue;
69
70             default:
71                 if (len < 2)
72                     return ZERR_FIELDLEN;
73                 *ptr++ = field[i];
74                 len--;
75         }
76     }
77
78     *ptr = '\0';
79     return ZERR_NONE;
80 }