]> www.average.org Git - pam_pcsc_cr.git/blob - serial.c
bump version, show version
[pam_pcsc_cr.git] / serial.c
1 /*
2 Copyright (c) 2013 Eugene Crosser
3
4 This software is provided 'as-is', without any express or implied
5 warranty. In no event will the authors be held liable for any damages
6 arising from the use of this software.
7
8 Permission is granted to anyone to use this software for any purpose,
9 including commercial applications, and to alter it and redistribute it
10 freely, subject to the following restrictions:
11
12     1. The origin of this software must not be misrepresented; you must
13     not claim that you wrote the original software. If you use this
14     software in a product, an acknowledgment in the product documentation
15     would be appreciated but is not required.
16
17     2. Altered source versions must be plainly marked as such, and must
18     not be misrepresented as being the original software.
19
20     3. This notice may not be removed or altered from any source
21     distribution.
22 */
23
24 #ifdef HAVE_CONFIG_H
25 # include "config.h"
26 #endif
27 #include <string.h>
28 #include "serial.h"
29
30 void serial_init(serializer_t *srl, void *buffer, int size)
31 {
32         srl->buffer = srl->cursor = buffer;
33         srl->bufsize = size;
34 }
35
36 void serial_switch(serializer_t *srl, void *buffer, int size)
37 {
38         int used = srl->cursor - srl->buffer;
39
40         memcpy(buffer, srl->buffer, used);
41         srl->buffer = buffer;
42         srl->bufsize = size;
43         srl->cursor = buffer + used;
44 }
45
46 /* returns 'size' on success, or remainging space if it was insufficient */
47 int serial_put(serializer_t *srl, const void *item, int size)
48 {
49         int left = srl->bufsize - (srl->cursor - srl->buffer);
50
51         if (left < size + sizeof(short)) return left - sizeof(short);
52         *((short *)srl->cursor) = size;
53         srl->cursor += sizeof(short);
54         if (size) memcpy(srl->cursor, item, size);
55         srl->cursor += size;
56         return size;
57 }
58
59 /* return 0 on success, -1 on wrong encoding (item longer than space left) */
60 int serial_get(serializer_t *srl, void **item, int *size)
61 {
62         int left = srl->bufsize - (srl->cursor - srl->buffer);
63         short isize = *((short *)srl->cursor);
64
65         if (isize + sizeof(short) > left) return -1;
66         srl->cursor += sizeof(short);
67         *item = srl->cursor;
68         *size = isize;
69         srl->cursor += isize;
70         return 0;
71 }
72
73 int serial_size(serializer_t *srl)
74 {
75         return srl->cursor - srl->buffer;
76 }