binary_storage.c 2.42 KB
Newer Older
1
2
3
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
4
/* #include <byteswap.h> */
5
6
7
#include <sys/time.h>
#include "binary_storage.h"

8
9
uint64_t encodeDbl(double a){
    uint64_t b;
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
    unsigned char *src = (unsigned char *)&a,
                  *dst = (unsigned char *)&b;
        dst[0] = src[7];
        dst[1] = src[6];
        dst[2] = src[5];
        dst[3] = src[4];
        dst[4] = src[3];
        dst[5] = src[2];
        dst[6] = src[1];
        dst[7] = src[0];
    return b;
}

BinaryStorage bs_open(char* filename){
   BinaryStorage storage;
   storage.file = fopen(filename,"wb");
   storage.buf_size = 500;
   storage.con_idx = 0;
28
   storage.contents = (uint64_t*) malloc(sizeof(uint64_t)*storage.buf_size);
29
30
31
32
33
34
35
36
37
38
39
40
41

   char header[]="SNS-BIET2020"; 
   fwrite(header,sizeof(header)-1,1,storage.file);
   storage.contents[storage.con_idx]=ftell(storage.file);
   storage.con_idx++;

   return storage;
}

int write_record(BinaryStorage *bs, char* name, TSTMP timestamp, double value, TAGS *tags){
  unsigned char name_len = strlen(name);

  int i=0;
42
  uint32_t tag_length=0;
43
44
45
46
  for(i=0;i<tags->num;i++){
    tag_length+=strlen(tags->data[i])+2;
  }

47
  uint32_t total_length = bswap_32(1+1+name_len+1+8+1+8+1+tag_length);
48
49
50
51
52
53
54
55
56
  fwrite(&total_length,4,1,bs->file);

/* name */
  fputc(1,bs->file);
  fwrite(&name_len,1,1,bs->file);
  fwrite(name, 1,name_len,bs->file);

/* timestamp */
  fputc(2,bs->file);
57
58
  uint32_t sec = bswap_32(timestamp.seconds);
  uint32_t nano = bswap_32(timestamp.nanos); 
59
60
61
62
63
  fwrite(&sec,4,1,bs->file);
  fwrite(&nano,4,1,bs->file);

/* double scalar */
  fputc(17,bs->file);
64
  uint64_t rawdata = encodeDbl(value);
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
  fwrite(&rawdata,8,1,bs->file);

/* tags */
  for(i=0;i<tags->num;i++){
    unsigned char tag_len = strlen(tags->data[i]);
    fputc(4,bs->file);
    fputc(tag_len,bs->file);
    fwrite(tags->data[i],1,tag_len,bs->file);
  }

/* end of record */
  fputc(254,bs->file);

  bs->contents[bs->con_idx]=ftell(bs->file);  
  bs->con_idx++;
}

void bs_close(BinaryStorage *bs){
83
   uint32_t total_length = bswap_32(1+1);
84
85
86
87
88
89
90
   fwrite(&total_length,4,1,bs->file);
   fputc(255,bs->file);
   fputc(254,bs->file);
   bs->contents[bs->con_idx]=ftell(bs->file);
   bs->con_idx++;
   int i;
   for(i=0;i<bs->con_idx;i++){
91
      uint64_t swapped = bswap_64(bs->contents[i]);
92
93
      fwrite(&swapped,8,1,bs->file);
   }
94
   uint32_t num_of_rec = bswap_32(bs->con_idx);
95
96
97
98
99
   fwrite(&num_of_rec,4,1,bs->file);

   fclose(bs->file);
   free(bs->contents);
}