summaryrefslogtreecommitdiff
path: root/BSON-lib/bson_object.c
blob: d1fa21d9f0bed536f15581cc9d2bd5fc2b87ca8f (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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
#include "bson_object.h"
#define DEFAULT_MAP_SIZE 32

size_t hash_function(const char* key, size_t maxValue) {
  size_t keyLength = strlen(key);
  size_t hash = 0;
  int i;
  for (i = 0; i < keyLength; i++) {
    hash += (size_t)key[i];
    hash %= maxValue;
  }
  return hash;
}

bool bson_object_initialize(BsonObject *obj, size_t capacity, float loadFactor) {
  return emhashmap_initialize(&obj->data, (int)capacity, loadFactor, &hash_function);
}

bool bson_object_initialize_default(BsonObject *obj) {
  return bson_object_initialize(obj, DEFAULT_MAP_SIZE, 0.5f);
}

void bson_object_deinitialize(BsonObject *obj) {
  MapIterator iterator = emhashmap_iterator(&obj->data);
  MapEntry *current = emhashmap_iterator_next(&iterator);
  while (current != NULL) {
    BsonElement *element = (BsonElement *)current->value;
    if (element->type == TYPE_DOCUMENT) {
      bson_object_deinitialize((BsonObject *)element->value);
    }
    else if (element->type == TYPE_ARRAY) {
      bson_array_deinitialize((BsonArray *)element->value);
    }
    free(element->value);
    free(element);
    current = emhashmap_iterator_next(&iterator);
  }

  emhashmap_deinitialize(&obj->data);
}

size_t bson_object_size(BsonObject *obj) {
  size_t objSize = OBJECT_OVERHEAD_BYTES;
  MapIterator iterator = emhashmap_iterator(&obj->data);
  MapEntry *current = emhashmap_iterator_next(&iterator);
  while (current != NULL) {
    BsonElement *element = (BsonElement *)current->value;
    objSize += object_key_size(current->key) + ELEMENT_OVERHEAD_BYTES;
    if (element->type == TYPE_DOCUMENT) {
      objSize += bson_object_size((BsonObject *)element->value);
    }
    else if (element->type == TYPE_ARRAY) {
      objSize += bson_array_size((BsonArray *)element->value);
    }
    else {
      objSize += element->size;
    }
    current = emhashmap_iterator_next(&iterator);
  }
  return objSize;
}

uint8_t *bson_object_to_bytes(BsonObject *obj) {
  //TODO just move the pointer rather than keep a position variable
  MapIterator iterator = emhashmap_iterator(&obj->data);
  MapEntry *current = emhashmap_iterator_next(&iterator);
  size_t objSize = bson_object_size(obj);
  uint8_t *bytes = malloc(objSize);
  size_t position = 0;
  write_int32_le(bytes, (int32_t)objSize, &position);

  while (current != NULL) {
    BsonElement *element = (BsonElement *)current->value;

    bytes[position++] = element->type;

    uint8_t *keyBytes = string_to_byte_array(current->key);
    memcpy(&bytes[position], keyBytes, strlen(current->key));
    free(keyBytes);
    position += strlen(current->key);

    //Null-terminate
    bytes[position++] = 0x00;

    switch (element->type) {
      case TYPE_DOCUMENT: {
        BsonObject *subObject = (BsonObject *)element->value;
        uint8_t *subObjectBytes = bson_object_to_bytes(subObject);
        if (subObjectBytes == NULL) {
          printf("An error occured while parsing the object with key \"%s\"\n", current->key);
          free(bytes);
          return NULL;
        }
        size_t subObjectSize = bson_object_size(subObject);
        memcpy(&bytes[position], subObjectBytes, subObjectSize);
        free(subObjectBytes);
        position += subObjectSize;
        break;
      }
      case TYPE_ARRAY: {
        BsonArray *array = (BsonArray *)element->value;
        uint8_t *arrayBytes = bson_array_to_bytes(array);
        if (arrayBytes == NULL) {
          printf("An error occured while parsing the object with key \"%s\"\n", current->key);
          free(bytes);
          return NULL;
        }
        size_t arraySize = bson_array_size(array);
        memset(&bytes[position], 0, arraySize);
        memcpy(&bytes[position], arrayBytes, arraySize);
        free(arrayBytes);
        position += arraySize;
        break;
      }
      case TYPE_INT32: {
        write_int32_le(bytes, *(int32_t *)element->value, &position);
        break;
      }
      case TYPE_INT64: {
        write_int64_le(bytes, *(int64_t *)element->value, &position);
        break;
      }
      case TYPE_STRING: {
        char *stringVal = (char *)element->value;
        //String length is written first
        write_int32_le(bytes, (int32_t)(strlen(stringVal) + 1), &position);

        uint8_t *stringBytes = string_to_byte_array(stringVal);
        memcpy(&bytes[position], stringBytes, strlen(stringVal));
        free(stringBytes);
        position += strlen(stringVal);

        //Null-terminate
        bytes[position++] = 0x00;
        break;
      }
      case TYPE_DOUBLE: {
        write_double_le(bytes, *(double *)element->value, &position);
        break;
      }
      case TYPE_BOOLEAN: {
        bytes[position++] = (uint8_t)(*(bson_boolean *)element->value);
        break;
      }
      default: {
        printf("Unrecognized BSON type: %i\n", element->type);
        position += sizeof(element->value);
      }
    }
    current = emhashmap_iterator_next(&iterator);
  }

  bytes[position++] = DOCUMENT_END;
  if (position != objSize) {
    printf("Something went horribly wrong. Unexpected size of map in bytes: %i, expected size: %i\n", (int)position, (int)objSize);
    free(bytes);
    return NULL;
  }
  return bytes;
}

// DEPRECATED: use bson_object_from_bytes_len() instead
BsonObject bson_object_from_bytes(uint8_t *data) {
  uint8_t *p = data;
  int32_t size = read_int32_le(&p);

  BsonObject obj;
  bson_object_from_bytes_len(&obj, data, size);
  return obj;
}

size_t bson_object_from_bytes_len(BsonObject *output, const uint8_t *data, size_t dataSize) {
  const uint8_t *current = data;
  size_t remainBytes = dataSize;
  int32_t size = 0;
  bool parseError = false;
  size_t ret;

  if (output == NULL || data == NULL || dataSize < SIZE_INT32) {
    return 0;
  }
  size = read_int32_le((uint8_t **)&current);
  remainBytes -= SIZE_INT32;
  if (size > dataSize) {
    printf("Unexpected object length %i, data is only %i bytes\n", (int)size, (int)dataSize);
    return 0;
  }

  if (remainBytes < 1) {
    return 0;
  }
  uint8_t type = *current;
  current += 1;
  remainBytes -= 1;

  BsonObject obj;
  bson_object_initialize_default(&obj);

  while (type != DOCUMENT_END) {
    char *key = NULL;
    ret = read_string_len(&key, &current, &remainBytes);
    if (ret == 0) {
      parseError = true;
      break;
    }

    switch ((element_type)type) {
      case TYPE_DOCUMENT: {
        BsonObject subObject;
        ret = bson_object_from_bytes_len(&subObject, current, remainBytes);
        if (ret > 0) {
          bson_object_put_object(&obj, key, &subObject);
          current += ret;
          remainBytes -= ret;
        } else {
          parseError = true;
        }
        break;
      }
      case TYPE_ARRAY: {
        BsonArray array;
        ret = bson_array_from_bytes_len(&array, current, remainBytes);
        if (ret > 0) {
          bson_object_put_array(&obj, key, &array);
          current += ret;
          remainBytes -= ret;
        } else {
          parseError = true;
        }
        break;
      }
      case TYPE_INT32:
        if (remainBytes >= SIZE_INT32) {
          int32_t value = read_int32_le((uint8_t **)&current);
          bson_object_put_int32(&obj, key, value);
          remainBytes -= SIZE_INT32;
        } else {
          parseError = true;
        }
        break;
      case TYPE_INT64:
        if (remainBytes >= SIZE_INT64) {
          int64_t value = read_int64_le((uint8_t **)&current);
          bson_object_put_int64(&obj, key, value);
          remainBytes -= SIZE_INT64;
        } else {
          parseError = true;
        }
        break;
      case TYPE_STRING:
        // Buffer length is read first
        if (remainBytes >= SIZE_INT32) {
          int32_t bufferLength = read_int32_le((uint8_t **)&current);
          remainBytes -= SIZE_INT32;

          if (bufferLength <= remainBytes) {
            char *stringVal = byte_array_to_bson_string((uint8_t*)current, (size_t)bufferLength - 1);
            bson_object_put_string(&obj, key, stringVal);
            free(stringVal);
            current += bufferLength;
            remainBytes -= bufferLength;
          } else {
            parseError = true;
          }
        } else {
          parseError = true;
        }
        break;
      case TYPE_DOUBLE:
        if (remainBytes >= SIZE_DOUBLE) {
          double value = read_double_le((uint8_t **)&current);
          bson_object_put_double(&obj, key, value);
          remainBytes -= SIZE_DOUBLE;
        } else {
          parseError = true;
        }
        break;
      case TYPE_BOOLEAN:
        if (remainBytes >= 1) {
          uint8_t value = *current;
          bson_object_put_bool(&obj, key, value);
          current += 1;
          remainBytes -= 1;
        } else {
          parseError = true;
        }
        break;
      default: {
        printf("Unrecognized BSON type: %i\n", type);
        parseError = true;
      }
    }
    free(key);

    if (parseError) {
      break;
    }

    if (remainBytes >= 1) {
      type = *current;
      current += 1;
      remainBytes -= 1;
    } else {
      parseError = true;
      break;
    }
  }

  if (parseError) {
    bson_object_deinitialize(&obj);
    return 0;
  }

  if (data + size != current) {
    printf("Unexpected parsed object size. Expected %i, got %i\n", (int)size, (int)(current - data));
  }
  *output = obj;
  return dataSize - remainBytes;
}

char *bson_object_to_string(BsonObject *obj, char *out) {
  //TODO just move the pointer rather than keep a position variable
  int position = 0;
  MapIterator iterator = emhashmap_iterator(&obj->data);
  MapEntry *current = emhashmap_iterator_next(&iterator);
  position += sprintf(out, "{ ");
  while (current != NULL) {
    BsonElement *element = (BsonElement *)current->value;
    position += sprintf(&out[position], "\"%s\":", current->key);
    switch (element->type) {
      case TYPE_DOCUMENT: {
        char docString[512];
        position += sprintf(&out[position], "%s", bson_object_to_string(bson_object_get_object(obj, current->key), docString));
        break;
      }
      case TYPE_ARRAY: {
        char docString[512];
        position += sprintf(&out[position], "%s", bson_array_to_string(bson_object_get_array(obj, current->key), docString));
        break;
      }
      case TYPE_INT32: {
        position += sprintf(&out[position], "%i", (int)bson_object_get_int32(obj, current->key));
        break;
      }
      case TYPE_INT64: {
        position += sprintf(&out[position], "%li", (long)bson_object_get_int64(obj, current->key));
        break;
      }
      case TYPE_STRING: {
        position += sprintf(&out[position], "\"%s\"", bson_object_get_string(obj, current->key));
        break;
      }
      case TYPE_DOUBLE: {
        position += sprintf(&out[position], "%f", bson_object_get_double(obj, current->key));
        break;
      }
      case TYPE_BOOLEAN: {
        position += sprintf(&out[position], "%s", (bson_object_get_bool(obj, current->key) == BOOLEAN_TRUE) ? "true" : "false");
        break;
      }
      default: {
        printf("Unrecognized BSON type: %i\n", element->type);
        position += sprintf(&out[position], "UNKNOWN_TYPE");
      }
    }
    current = emhashmap_iterator_next(&iterator);
    if (current != NULL) {
      position += sprintf(&out[position], ", ");    
    }
  }
  sprintf(&out[position], " }");

  return out;
}

bool bson_object_put_element(BsonObject *obj, const char *key, BsonElement *element, size_t allocSize) {
  BsonElement *allocElement = malloc(sizeof(BsonElement));
  allocElement->type = element->type;
  allocElement->size = element->size;
  allocElement->value = malloc(allocSize);
  memcpy(allocElement->value, element->value, allocSize);
  BsonElement *existingElement = emhashmap_remove(&obj->data, key);
  if (existingElement != NULL) {
    if (existingElement->type == TYPE_DOCUMENT) {
      bson_object_deinitialize((BsonObject *)existingElement->value);
    }
    else if (existingElement->type == TYPE_ARRAY) {
      bson_array_deinitialize((BsonArray *)existingElement->value);
    }
    free(existingElement->value);
    free(existingElement);
  }
  return emhashmap_put(&obj->data, key, (void *)allocElement);
}

bool bson_object_put(BsonObject *obj, const char *key, element_type type, void *value, size_t allocSize, size_t elementSize) {
  BsonElement element;
  element.type = type;
  element.value = value;
  element.size = elementSize;
  return bson_object_put_element(obj, key, &element, allocSize);
}

bool bson_object_put_object(BsonObject *obj, const char *key, BsonObject *value) {
  return bson_object_put(obj, key, TYPE_DOCUMENT, value, sizeof(BsonObject), 0);
}

bool bson_object_put_array(BsonObject *obj, const char *key, BsonArray *value) {
  return bson_object_put(obj, key, TYPE_ARRAY, value, sizeof(BsonArray), 0);
}

bool bson_object_put_int32(BsonObject *obj, const char *key, int32_t value) {
  return bson_object_put(obj, key, TYPE_INT32, &value, sizeof(int32_t),
                         SIZE_INT32);
}

bool bson_object_put_int64(BsonObject *obj, const char *key, int64_t value) {
  return bson_object_put(obj, key, TYPE_INT64, &value, sizeof(int64_t),
                         SIZE_INT64);
}

bool bson_object_put_string(BsonObject *obj, const char *key, char *value) {
  return bson_object_put(obj, key, TYPE_STRING, value, (strlen(value) + 1) * sizeof(char),
                         strlen(value) + STRING_OVERHEAD_BYTES);
}

bool bson_object_put_bool(BsonObject *obj, const char *key, bson_boolean value) {
  return bson_object_put(obj, key, TYPE_BOOLEAN, &value, sizeof(bson_boolean),
                         SIZE_BOOLEAN);
}

bool bson_object_put_double(BsonObject *obj, const char *key, double value) {
  return bson_object_put(obj, key, TYPE_DOUBLE, &value, sizeof(double),
                         SIZE_DOUBLE);
}

BsonElement *bson_object_get(BsonObject *obj, const char *key) {
  MapEntry *entry = emhashmap_get(&obj->data, key);
  return (entry == NULL) ? NULL : entry->value;
}

BsonObject *bson_object_get_object(BsonObject *obj, const char *key) {
  BsonElement *element = bson_object_get(obj, key);
  return (element == NULL || element->type != TYPE_DOCUMENT) ? 
          NULL : (BsonObject *)element->value;
}

BsonArray *bson_object_get_array(BsonObject *obj, const char *key) {
  BsonElement *element = bson_object_get(obj, key);
  return (element == NULL || element->type != TYPE_ARRAY) ? 
          NULL : (BsonArray *)element->value;
}

int32_t bson_object_get_int32(BsonObject *obj, const char *key) {
  BsonElement *element = bson_object_get(obj, key);
  return (element == NULL || element->type != TYPE_INT32) ? 
          -1 : *(int32_t *)element->value;
}

int64_t bson_object_get_int64(BsonObject *obj, const char *key) {
  BsonElement *element = bson_object_get(obj, key);
  return (element == NULL || element->type != TYPE_INT64) ? 
          -1 : *(int64_t *)element->value;
}

char *bson_object_get_string(BsonObject *obj, const char *key) {
  BsonElement *element = bson_object_get(obj, key);
  return (element == NULL || element->type != TYPE_STRING) ? 
          NULL : (char *)element->value;
}

bson_boolean bson_object_get_bool(BsonObject *obj, const char *key) {
  BsonElement *element = bson_object_get(obj, key);
  return (element == NULL || element->type != TYPE_BOOLEAN) ? 
          BOOLEAN_INVALID : *(bson_boolean *)element->value;
}

double bson_object_get_double(BsonObject *obj, const char *key) {
  BsonElement *element = bson_object_get(obj, key);
  return (element == NULL || element->type != TYPE_DOUBLE) ? 
          -1 : *(double *)element->value;
}

MapIterator bson_object_iterator(BsonObject *obj) {
  return emhashmap_iterator(&obj->data);
}

BsonObjectEntry bson_object_iterator_next(MapIterator *iterator) {
  MapEntry *entry = emhashmap_iterator_next(iterator);
  BsonObjectEntry bsonEntry;
  if(entry == NULL) {
    bsonEntry.key[0] = 0x00; //Assign empty string
    bsonEntry.element = NULL;
  }
  else {
    strncpy(bsonEntry.key, entry->key, 255);
    bsonEntry.element = (BsonElement *)entry->value;
  }
  return bsonEntry;
}