• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* encode.c -- encoding and decoding of CoAP data types
2  *
3  * Copyright (C) 2010,2011 Olaf Bergmann <bergmann@tzi.org>
4  *
5  * This file is part of the CoAP library libcoap. Please see
6  * README for terms of use.
7  */
8 
9 #include "coap_internal.h"
10 
11 /* Carsten suggested this when fls() is not available: */
12 #ifndef HAVE_FLS
coap_fls(unsigned int i)13 int coap_fls(unsigned int i) {
14   return coap_flsll(i);
15 }
16 #endif
17 
18 #ifndef HAVE_FLSLL
coap_flsll(long long i)19 int coap_flsll(long long i)
20 {
21   int n;
22   for (n = 0; i; n++)
23     i >>= 1;
24   return n;
25 }
26 #endif
27 
28 unsigned int
coap_decode_var_bytes(const uint8_t * buf,unsigned int len)29 coap_decode_var_bytes(const uint8_t *buf,unsigned int len) {
30   unsigned int i, n = 0;
31   for (i = 0; i < len; ++i)
32     n = (n << 8) + buf[i];
33 
34   return n;
35 }
36 
37 unsigned int
coap_encode_var_safe(uint8_t * buf,size_t length,unsigned int val)38 coap_encode_var_safe(uint8_t *buf, size_t length, unsigned int val) {
39   unsigned int n, i;
40 
41   for (n = 0, i = val; i && n < sizeof(val); ++n)
42     i >>= 8;
43 
44   if (n > length) {
45     assert (n <= length);
46     return 0;
47   }
48   i = n;
49   while (i--) {
50     buf[i] = val & 0xff;
51     val >>= 8;
52   }
53 
54   return n;
55 }
56 
57 uint64_t
coap_decode_var_bytes8(const uint8_t * buf,unsigned int len)58 coap_decode_var_bytes8(const uint8_t *buf,unsigned int len) {
59   unsigned int i;
60   uint64_t n = 0;
61   for (i = 0; i < len; ++i)
62     n = (n << 8) + buf[i];
63 
64   return n;
65 }
66 
67 unsigned int
coap_encode_var_safe8(uint8_t * buf,size_t length,uint64_t val)68 coap_encode_var_safe8(uint8_t *buf, size_t length, uint64_t val) {
69   unsigned int n, i;
70   uint64_t tval = val;
71 
72   for (n = 0; tval && n < sizeof(val); ++n)
73     tval >>= 8;
74 
75   if (n > length) {
76     assert (n <= length);
77     return 0;
78   }
79   i = n;
80   while (i--) {
81     buf[i] = val & 0xff;
82     val >>= 8;
83   }
84 
85   return n;
86 }
87