1 #include <asn_application.h>
2 #include <asn_internal.h>
3 #include <uper_encoder.h>
5 static int _uper_encode_flush_outp(asn_per_outp_t *po);
8 uper_encode(const asn_TYPE_descriptor_t *td,
9 const asn_per_constraints_t *constraints, const void *sptr,
10 asn_app_consume_bytes_f *cb, void *app_key) {
12 asn_enc_rval_t er = {0,0,0};
15 * Invoke type-specific encoder.
17 if(!td || !td->op->uper_encoder)
18 ASN__ENCODE_FAILED; /* PER is not compiled in */
20 po.buffer = po.tmpspace;
22 po.nbits = 8 * sizeof(po.tmpspace);
23 po.output = cb ? cb : ignore_output;
27 er = td->op->uper_encoder(td, constraints, sptr, &po);
28 if(er.encoded != -1) {
31 bits_to_flush = ((po.buffer - po.tmpspace) << 3) + po.nboff;
33 /* Set number of bits encoded to a firm value */
34 er.encoded = (po.flushed_bytes << 3) + bits_to_flush;
36 if(_uper_encode_flush_outp(&po)) ASN__ENCODE_FAILED;
43 * Argument type and callback necessary for uper_encode_to_buffer().
45 typedef struct enc_to_buf_arg {
49 static int encode_to_buffer_cb(const void *buffer, size_t size, void *key) {
50 enc_to_buf_arg *arg = (enc_to_buf_arg *)key;
53 return -1; /* Data exceeds the available buffer size */
55 memcpy(arg->buffer, buffer, size);
56 arg->buffer = ((char *)arg->buffer) + size;
63 uper_encode_to_buffer(const asn_TYPE_descriptor_t *td,
64 const asn_per_constraints_t *constraints,
65 const void *sptr, void *buffer, size_t buffer_size) {
69 key.left = buffer_size;
71 if(td) ASN_DEBUG("Encoding \"%s\" using UNALIGNED PER", td->name);
73 return uper_encode(td, constraints, sptr, encode_to_buffer_cb, &key);
77 uper_encode_to_new_buffer(const asn_TYPE_descriptor_t *td,
78 const asn_per_constraints_t *constraints,
79 const void *sptr, void **buffer_r) {
80 asn_enc_rval_t er = {0,0,0};
83 memset(&key, 0, sizeof(key));
85 er = uper_encode(td, constraints, sptr, encode_dyn_cb, &key);
92 key.buffer = MALLOC(1);
94 *(char *)key.buffer = '\0';
95 *buffer_r = key.buffer;
101 *buffer_r = key.buffer;
102 ASN_DEBUG("Complete encoded in %ld bits", (long)er.encoded);
103 return ((er.encoded + 7) >> 3);
108 * Internally useful functions.
111 /* Flush partially filled buffer */
113 _uper_encode_flush_outp(asn_per_outp_t *po) {
116 if(po->nboff == 0 && po->buffer == po->tmpspace)
119 buf = po->buffer + (po->nboff >> 3);
120 /* Make sure we account for the last, partially filled */
121 if(po->nboff & 0x07) {
122 buf[0] &= 0xff << (8 - (po->nboff & 0x07));
126 return po->output(po->tmpspace, buf - po->tmpspace, po->op_key);