Lev Walkin | 523de9e | 2006-08-18 01:34:18 +0000 | [diff] [blame] | 1 | #include <asn_application.h> |
| 2 | #include <asn_internal.h> |
| 3 | #include <per_encoder.h> |
| 4 | |
| 5 | /* Flush partially filled buffer */ |
| 6 | static int _uper_encode_flush_outp(asn_per_outp_t *po); |
| 7 | |
| 8 | asn_enc_rval_t |
| 9 | uper_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; |
| 24 | |
| 25 | er = td->uper_encoder(td, 0, sptr, &po); |
| 26 | if(er.encoded != -1 && _uper_encode_flush_outp(&po)) |
| 27 | _ASN_ENCODE_FAILED; |
| 28 | |
| 29 | return er; |
| 30 | } |
| 31 | |
| 32 | /* |
| 33 | * Argument type and callback necessary for uper_encode_to_buffer(). |
| 34 | */ |
| 35 | typedef struct enc_to_buf_arg { |
| 36 | void *buffer; |
| 37 | size_t left; |
| 38 | } enc_to_buf_arg; |
| 39 | static int encode_to_buffer_cb(const void *buffer, size_t size, void *key) { |
| 40 | enc_to_buf_arg *arg = (enc_to_buf_arg *)key; |
| 41 | |
| 42 | if(arg->left < size) |
| 43 | return -1; /* Data exceeds the available buffer size */ |
| 44 | |
| 45 | memcpy(arg->buffer, buffer, size); |
| 46 | arg->buffer = ((char *)arg->buffer) + size; |
| 47 | arg->left -= size; |
| 48 | |
| 49 | return 0; |
| 50 | } |
| 51 | |
| 52 | asn_enc_rval_t |
| 53 | uper_encode_to_buffer(asn_TYPE_descriptor_t *td, void *sptr, void *buffer, size_t buffer_size) { |
| 54 | enc_to_buf_arg key; |
| 55 | asn_enc_rval_t er; |
| 56 | |
| 57 | /* |
| 58 | * Invoke type-specific encoder. |
| 59 | */ |
| 60 | if(!td || !td->uper_encoder) |
| 61 | _ASN_ENCODE_FAILED; /* PER is not compiled in */ |
| 62 | |
| 63 | key.buffer = buffer; |
| 64 | key.left = buffer_size; |
| 65 | |
| 66 | ASN_DEBUG("Encoding \"%s\" using UNALIGNED PER", td->name); |
| 67 | |
| 68 | er = uper_encode(td, sptr, encode_to_buffer_cb, &key); |
| 69 | if(er.encoded != -1) |
| 70 | er.encoded = buffer_size - key.left; |
| 71 | return er; |
| 72 | } |
| 73 | |
| 74 | static int |
| 75 | _uper_encode_flush_outp(asn_per_outp_t *po) { |
| 76 | uint8_t *buf; |
| 77 | |
| 78 | if(po->nboff == 0 && po->buffer == po->tmpspace) |
| 79 | return 0; |
| 80 | |
| 81 | buf = po->buffer + (po->nboff >> 3); |
| 82 | /* Make sure we account for the last, partially filled */ |
| 83 | if(po->nboff & 0x07) { |
| 84 | buf[0] &= 0xff << (8 - (po->nboff & 0x07)); |
| 85 | buf++; |
| 86 | } |
| 87 | |
| 88 | return po->outper(po->tmpspace, buf - po->tmpspace, po->op_key); |
| 89 | } |