summaryrefslogtreecommitdiff
path: root/src/include/xml/decode.c
blob: a405e97799a1e1b3cfee6a2e42bda4a3771607f5 (plain)
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
64
65
66
67
68
69
70
71
72
73
74
#include <stdlib.h>
#include <string.h>

#include "xml.h"

static char *gettag(char *xml, int *pos);
static char *getvalue(char *xml, int *pos);

// TODO: make this smaller
map_t *decode(char *xml, int *pos, int *len)
{
  if (*len)
    ++(*len);
  else
    *len = 1;
  map_t *decoded = calloc(1, sizeof(map_t));

  int err = 0, closed = 1;
  for (int i = *pos; i < strlen(xml); ++i) {
    if (!strncmp(xml + i, "</", 2)) {
      i += 2;
      char *tmp = gettag(xml, &i);
      if (!strcmp(decoded->tag, tmp))
        *pos = i;
      else
        err = 1;
      free(tmp);
      goto end;
    } else if (xml[i] == '<' && closed) {
      ++i;
      decoded->tag = gettag(xml, &i);
      closed = 0;
    } else if (xml[i] == '<' && !closed) {
      map_t *ndec = decode(xml, &i, &(decoded->n));
      decoded->size = sizeof(map_t);
      if (decoded->n > 1)
        decoded->payload = realloc(decoded->payload, decoded->n * sizeof(map_t));
      else
        decoded->payload = calloc(1, sizeof(map_t));
      ((map_t *) decoded->payload)[decoded->n - 1] = *ndec;
      free(ndec);
    } else {
      decoded->payload = getvalue(xml, &i);
      decoded->size = sizeof(char);
      decoded->n = strlen(decoded->payload);
    }
  }
  end:
    if (err) {
      free(decoded);
      decoded = NULL;
    }
    return decoded;
}

static char *gettag(char *xml, int *pos)
{
  int len, i;
  for (i = *pos, len = 0; xml[i] != '>'; ++i, ++len) ;
  char *title = calloc(len + 1, sizeof(char));
  strncpy(title, xml + *pos, len);
  *pos += len;
  return title;
}

static char *getvalue(char *xml, int *pos)
{
  int len, i;
  for (i = *pos, len = 0; xml[i] != '<'; ++i, ++len) ;
  char *value = calloc(len + 1, sizeof(char));
  strncpy(value, xml + *pos, len);
  *pos += len - 1;
  return value;
}