diff --git a/pdu.c b/pdu.c index ce324731..ea8ab87a 100644 --- a/pdu.c +++ b/pdu.c @@ -120,6 +120,7 @@ coap_add_token(coap_pdu_t *pdu, size_t len, const unsigned char *data) { return 1; } +/** @FIXME de-duplicate code with coap_add_option_later */ size_t coap_add_option(coap_pdu_t *pdu, unsigned short type, unsigned int len, const unsigned char *data) { size_t optsize; @@ -151,6 +152,38 @@ coap_add_option(coap_pdu_t *pdu, unsigned short type, unsigned int len, const un return optsize; } +/** @FIXME de-duplicate code with coap_add_option */ +unsigned char* +coap_add_option_later(coap_pdu_t *pdu, unsigned short type, unsigned int len) { + size_t optsize; + coap_opt_t *opt; + + assert(pdu); + pdu->data = NULL; + + if (type < pdu->max_delta) { + warn("coap_add_option: options are not in correct order\n"); + return NULL; + } + + opt = (unsigned char *)pdu->hdr + pdu->length; + + /* encode option and check length */ + optsize = coap_opt_encode(opt, pdu->max_size - pdu->length, + type - pdu->max_delta, NULL, len); + + if (!optsize) { + warn("coap_add_option: cannot add option\n"); + /* error */ + return NULL; + } else { + pdu->max_delta = type; + pdu->length += optsize; + } + + return ((unsigned char*)opt) + optsize - len; +} + int coap_add_data(coap_pdu_t *pdu, unsigned int len, const unsigned char *data) { assert(pdu); diff --git a/pdu.h b/pdu.h index 6f27487d..2cf04f88 100644 --- a/pdu.h +++ b/pdu.h @@ -287,6 +287,16 @@ int coap_add_token(coap_pdu_t *pdu, size_t len, const unsigned char *data); size_t coap_add_option(coap_pdu_t *pdu, unsigned short type, unsigned int len, const unsigned char *data); +/** + * Adds option of given type to pdu that is passed as first + * parameter, but does not write a value. It works like coap_add_option with + * respect to calling sequence (i.e. after token and before data). + * This function returns a memory address to which the option data has to be + * written before the PDU can be sent, or @c NULL on error. + */ +unsigned char *coap_add_option_later(coap_pdu_t *pdu, unsigned short type, + unsigned int len); + /** * Adds given data to the pdu that is passed as first parameter. Note * that the PDU's data is destroyed by coap_add_option(). coap_add_data()