1 #include <asn_application.h>
2 #include <asn_internal.h>
3 #include <per_encoder.h>
5 static int _uper_encode_flush_outp(asn_per_outp_t *po);
8 ignore_output(const void *data, size_t size, void *app_key) {
16 uper_encode(const asn_TYPE_descriptor_t *td,
17 const asn_per_constraints_t *constraints, const void *sptr,
18 asn_app_consume_bytes_f *cb, void *app_key) {
23 * Invoke type-specific encoder.
25 if(!td || !td->op->uper_encoder)
26 ASN__ENCODE_FAILED; /* PER is not compiled in */
28 po.buffer = po.tmpspace;
30 po.nbits = 8 * sizeof(po.tmpspace);
31 po.output = cb ? cb : ignore_output;
35 er = td->op->uper_encoder(td, constraints, sptr, &po);
36 if(er.encoded != -1) {
39 bits_to_flush = ((po.buffer - po.tmpspace) << 3) + po.nboff;
41 /* Set number of bits encoded to a firm value */
42 er.encoded = (po.flushed_bytes << 3) + bits_to_flush;
44 if(_uper_encode_flush_outp(&po)) ASN__ENCODE_FAILED;
51 * Argument type and callback necessary for uper_encode_to_buffer().
53 typedef struct enc_to_buf_arg {
57 static int encode_to_buffer_cb(const void *buffer, size_t size, void *key) {
58 enc_to_buf_arg *arg = (enc_to_buf_arg *)key;
61 return -1; /* Data exceeds the available buffer size */
63 memcpy(arg->buffer, buffer, size);
64 arg->buffer = ((char *)arg->buffer) + size;
71 uper_encode_to_buffer(const asn_TYPE_descriptor_t *td,
72 const asn_per_constraints_t *constraints,
73 const void *sptr, void *buffer, size_t buffer_size) {
77 key.left = buffer_size;
79 if(td) ASN_DEBUG("Encoding \"%s\" using UNALIGNED PER", td->name);
81 return uper_encode(td, constraints, sptr, encode_to_buffer_cb, &key);
84 typedef struct enc_dyn_arg {
90 encode_dyn_cb(const void *buffer, size_t size, void *key) {
91 enc_dyn_arg *arg = key;
92 if(arg->length + size >= arg->allocated) {
93 size_t new_size = arg->allocated ? arg->allocated : 8;
98 } while(arg->length + size >= new_size);
100 p = REALLOC(arg->buffer, new_size);
102 FREEMEM(arg->buffer);
103 memset(arg, 0, sizeof(*arg));
107 arg->allocated = new_size;
109 memcpy(((char *)arg->buffer) + arg->length, buffer, size);
114 uper_encode_to_new_buffer(const asn_TYPE_descriptor_t *td,
115 const asn_per_constraints_t *constraints,
116 const void *sptr, void **buffer_r) {
120 memset(&key, 0, sizeof(key));
122 er = uper_encode(td, constraints, sptr, encode_dyn_cb, &key);
129 key.buffer = MALLOC(1);
131 *(char *)key.buffer = '\0';
132 *buffer_r = key.buffer;
138 *buffer_r = key.buffer;
139 ASN_DEBUG("Complete encoded in %ld bits", (long)er.encoded);
140 return ((er.encoded + 7) >> 3);
145 * Internally useful functions.
148 /* Flush partially filled buffer */
150 _uper_encode_flush_outp(asn_per_outp_t *po) {
153 if(po->nboff == 0 && po->buffer == po->tmpspace)
156 buf = po->buffer + (po->nboff >> 3);
157 /* Make sure we account for the last, partially filled */
158 if(po->nboff & 0x07) {
159 buf[0] &= 0xff << (8 - (po->nboff & 0x07));
163 return po->output(po->tmpspace, buf - po->tmpspace, po->op_key);