huangcm
2024-12-18 9d29be7f7249789d6ffd0440067187a9f040c2cd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <stdlib.h>
#include <string.h>
#include <assert.h>
 
#include "cn-cbor/cn-cbor.h"
 
cn_cbor* cn_cbor_mapget_int(const cn_cbor* cb, int key) {
  cn_cbor* cp;
  assert(cb);
  for (cp = cb->first_child; cp && cp->next; cp = cp->next->next) {
    switch(cp->type) {
    case CN_CBOR_UINT:
      if (cp->v.uint == (unsigned long)key) {
        return cp->next;
      }
      break;
    case CN_CBOR_INT:
      if (cp->v.sint == (long)key) {
        return cp->next;
      }
      break;
    default:
      ; // skip non-integer keys
    }
  }
  return NULL;
}
 
cn_cbor* cn_cbor_mapget_string(const cn_cbor* cb, const char* key) {
  cn_cbor *cp;
  int keylen;
  assert(cb);
  assert(key);
  keylen = strlen(key);
  for (cp = cb->first_child; cp && cp->next; cp = cp->next->next) {
    switch(cp->type) {
    case CN_CBOR_TEXT: // fall-through
    case CN_CBOR_BYTES:
      if (keylen != cp->length) {
        continue;
      }
      if (memcmp(key, cp->v.str, keylen) == 0) {
        return cp->next;
      }
    default:
      ; // skip non-string keys
    }
  }
  return NULL;
}
 
cn_cbor* cn_cbor_index(const cn_cbor* cb, unsigned int idx) {
  cn_cbor *cp;
  unsigned int i = 0;
  assert(cb);
  for (cp = cb->first_child; cp; cp = cp->next) {
    if (i == idx) {
      return cp;
    }
    i++;
  }
  return NULL;
}