1
0
mirror of https://github.com/fumiama/simple-protobuf.git synced 2026-06-05 00:10:24 +08:00

add more api

This commit is contained in:
源文雨
2022-05-06 11:15:13 +08:00
parent f94738a2f1
commit d0c7f47123
2 changed files with 44 additions and 3 deletions

View File

@@ -5,9 +5,8 @@
#include "simple_protobuf.h"
static uint32_t read_num(FILE* fp) {
uint8_t c;
uint32_t n = 0;
uint8_t i = 0;
uint32_t c, n = 0;
long i = 0;
do {
c = fgetc(fp);
if(feof(fp)) return n;
@@ -16,6 +15,18 @@ static uint32_t read_num(FILE* fp) {
return n;
}
static uint32_t peek_num(FILE* fp) {
uint32_t c, n = 0;
long i = 0;
do {
c = fgetc(fp);
if(feof(fp)) return n;
else n |= (c & 0x7f) << (7 * i++);
} while((c & 0x80));
fseek(fp, -i, SEEK_CUR);
return n;
}
static int write_num(FILE* fp, uint32_t n) {
char* c = (char*)(&n);
int i = 0;
@@ -51,6 +62,30 @@ SIMPLE_PB* get_pb(FILE* fp) {
return spb;
}
uint32_t get_pb_len(FILE* fp) {
uint32_t init_pos = ftell(fp);
uint32_t struct_len = peek_num(fp);
if(struct_len <= 1 || struct_len >= 1u<<20) return 0; // 1B<struct_len<1MB
return struct_len + 2*sizeof(uint32_t);
}
SIMPLE_PB* read_pb_into(FILE* fp, SIMPLE_PB* spb) {
if(!spb) return NULL;
uint32_t init_pos = ftell(fp);
uint32_t struct_len = read_num(fp);
if(struct_len <= 1 || struct_len >= 1u<<20) return NULL; // 1B<struct_len<1MB
spb->struct_len = struct_len;
memset(spb->target, 0, struct_len);
uint32_t offset, data_len;
for(char* p = spb->target; p < spb->target+struct_len; p += offset) {
offset = read_num(fp);
data_len = read_num(fp);
if(data_len > 0 && data_len <= offset) fread(p, data_len, 1, fp);
}
spb->real_len = ftell(fp) - init_pos;
return spb;
}
int set_pb(FILE* fp, uint32_t* items_len, uint32_t struct_len, void* target) {
uint32_t offset = 0;
uint32_t i = 0;

View File

@@ -11,7 +11,13 @@ struct SIMPLE_PB {
typedef struct SIMPLE_PB SIMPLE_PB;
SIMPLE_PB* get_pb(FILE* fp);
uint32_t get_pb_len(FILE* fp);
SIMPLE_PB* read_pb_into(FILE* fp, SIMPLE_PB* spb);
int set_pb(FILE* fp, uint32_t* items_len, uint32_t struct_len, void* target);
//uint32_t struct_size, uint32_t items_cnt, void* item_addr1, void* item_addr2...
uint32_t* align_struct(uint32_t struct_size, uint32_t items_cnt, ...);