-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtree.c
More file actions
74 lines (60 loc) · 2.09 KB
/
tree.c
File metadata and controls
74 lines (60 loc) · 2.09 KB
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 "mvcs.h"
/* Write tree object */
int write_tree(tree_entry_t *entries, int count, unsigned char *hash) {
/* Serialize tree entries */
size_t total_size = 0;
for (int i = 0; i < count; i++) {
/* Format: "mode name\0hash" */
total_size += snprintf(NULL, 0, "%o %s", entries[i].mode, entries[i].name) + 1 + HASH_SIZE;
}
unsigned char *data = malloc(total_size);
if (!data) return -1;
size_t offset = 0;
for (int i = 0; i < count; i++) {
int len = sprintf((char *)(data + offset), "%o %s", entries[i].mode, entries[i].name);
offset += len + 1; /* Include null terminator */
memcpy(data + offset, entries[i].hash, HASH_SIZE);
offset += HASH_SIZE;
}
int ret = write_object(OBJ_TREE, data, total_size, hash);
free(data);
return ret;
}
/* Read tree object */
int read_tree(const unsigned char *hash, tree_entry_t **entries, int *count) {
int type;
void *data;
size_t len;
if (read_object(hash, &type, &data, &len) != 0 || type != OBJ_TREE) {
return -1;
}
/* Parse tree entries */
tree_entry_t *ent = malloc(sizeof(tree_entry_t) * MAX_TREE_ENTRIES);
if (!ent) {
free(data);
return -1;
}
*count = 0;
size_t offset = 0;
unsigned char *bytes = (unsigned char *)data;
while (offset < len && *count < MAX_TREE_ENTRIES) {
/* Parse mode and name */
int mode;
char name[256];
int parsed = sscanf((char *)(bytes + offset), "%o %255s", &mode, name);
if (parsed != 2) break;
ent[*count].mode = mode;
strncpy(ent[*count].name, name, sizeof(ent[*count].name) - 1);
ent[*count].name[sizeof(ent[*count].name) - 1] = '\0';
/* Skip to hash */
offset += strlen((char *)(bytes + offset)) + 1;
/* Copy hash */
if (offset + HASH_SIZE > len) break;
memcpy(ent[*count].hash, bytes + offset, HASH_SIZE);
offset += HASH_SIZE;
(*count)++;
}
free(data);
*entries = ent;
return 0;
}