blob: 614dd23331d482a05b973f790449359e7f503768 [file] [log] [blame]
Lev Walkin523de9e2006-08-18 01:34:18 +00001#include <asn_application.h>
2#include <asn_internal.h>
3#include <per_encoder.h>
4
5/* Flush partially filled buffer */
6static int _uper_encode_flush_outp(asn_per_outp_t *po);
7
8asn_enc_rval_t
9uper_encode(asn_TYPE_descriptor_t *td, void *sptr, asn_app_consume_bytes_f *cb, void *app_key) {
10 asn_per_outp_t po;
11 asn_enc_rval_t er;
12
13 /*
14 * Invoke type-specific encoder.
15 */
16 if(!td || !td->uper_encoder)
17 _ASN_ENCODE_FAILED; /* PER is not compiled in */
18
19 po.buffer = po.tmpspace;
20 po.nboff = 0;
21 po.nbits = 8 * sizeof(po.tmpspace);
22 po.outper = cb;
23 po.op_key = app_key;
Lev Walkinbc691772006-09-17 11:02:53 +000024 po.flushed_bytes = 0;
Lev Walkin523de9e2006-08-18 01:34:18 +000025
26 er = td->uper_encoder(td, 0, sptr, &po);
Lev Walkinbc691772006-09-17 11:02:53 +000027 if(er.encoded != -1) {
28 size_t bits_to_flush;
29
30 bits_to_flush = ((po.buffer - po.tmpspace) << 3) + po.nboff;
31
32 /* Set number of bits encoded to a firm value */
33 er.encoded = (po.flushed_bytes << 3) + bits_to_flush;
34
35 if(_uper_encode_flush_outp(&po))
36 _ASN_ENCODE_FAILED;
37 }
Lev Walkin523de9e2006-08-18 01:34:18 +000038
39 return er;
40}
41
42/*
43 * Argument type and callback necessary for uper_encode_to_buffer().
44 */
45typedef struct enc_to_buf_arg {
46 void *buffer;
47 size_t left;
48} enc_to_buf_arg;
49static int encode_to_buffer_cb(const void *buffer, size_t size, void *key) {
50 enc_to_buf_arg *arg = (enc_to_buf_arg *)key;
51
52 if(arg->left < size)
53 return -1; /* Data exceeds the available buffer size */
54
55 memcpy(arg->buffer, buffer, size);
56 arg->buffer = ((char *)arg->buffer) + size;
57 arg->left -= size;
58
59 return 0;
60}
61
62asn_enc_rval_t
63uper_encode_to_buffer(asn_TYPE_descriptor_t *td, void *sptr, void *buffer, size_t buffer_size) {
64 enc_to_buf_arg key;
Lev Walkin523de9e2006-08-18 01:34:18 +000065
66 /*
67 * Invoke type-specific encoder.
68 */
69 if(!td || !td->uper_encoder)
70 _ASN_ENCODE_FAILED; /* PER is not compiled in */
71
72 key.buffer = buffer;
73 key.left = buffer_size;
74
75 ASN_DEBUG("Encoding \"%s\" using UNALIGNED PER", td->name);
76
Lev Walkinbc691772006-09-17 11:02:53 +000077 return uper_encode(td, sptr, encode_to_buffer_cb, &key);
Lev Walkin523de9e2006-08-18 01:34:18 +000078}
79
80static int
81_uper_encode_flush_outp(asn_per_outp_t *po) {
82 uint8_t *buf;
83
84 if(po->nboff == 0 && po->buffer == po->tmpspace)
85 return 0;
86
87 buf = po->buffer + (po->nboff >> 3);
88 /* Make sure we account for the last, partially filled */
89 if(po->nboff & 0x07) {
90 buf[0] &= 0xff << (8 - (po->nboff & 0x07));
91 buf++;
92 }
93
94 return po->outper(po->tmpspace, buf - po->tmpspace, po->op_key);
95}