-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvector.c
94 lines (73 loc) · 2.46 KB
/
vector.c
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
#include "vector.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
void grow(vector *v){
v-> alloc_len += v->init_alloc;
v->elems = realloc(v->elems, v->elem_size * v->alloc_len);
}
void vector_new(vector *v, int elem_size, int init_alloc){
assert(elem_size > 0);
assert(init_alloc > 0);
assert(v != NULL);
v->alloc_len = init_alloc;
v->init_alloc = init_alloc;
v->log_len = 0;
v->elem_size = elem_size;
v->elems = malloc(v->elem_size * v->alloc_len);
}
void vector_dispose(vector * v){
assert(v != NULL);
free(v->elems);
}
int vector_length(const vector *v){
assert(v != NULL);
return v->log_len;
}
void *vector_nth(const vector *v, int position){
assert(v != NULL);
assert(position >= 0);
assert(position < v->log_len);
return (char *)v->elems + v->elem_size * position;
}
void vector_insert(vector *v, const void *elem_addr, int position){
assert(v != NULL);
assert(position >= 0);
assert(position <= v->log_len);
if(v->log_len == v->alloc_len)
grow(v);
void * destination = (char *)v->elems + (position + 1) * v->elem_size;
void * source = (char *)v->elems + position * v->elem_size;
int move_size = (v->log_len - position) * v->elem_size;
memmove(destination, source, move_size);
source = memcpy(source, elem_addr, v->elem_size);
v->log_len ++;
}
void vector_append(vector *v, const void *elem_addr){
assert(v != NULL);
assert(elem_addr != NULL);
if(v->log_len == v->alloc_len)
grow(v);
void * destination = (char *)v->elems + v->elem_size * v->log_len;
memcpy(destination, elem_addr, v->elem_size);
v->log_len ++;
}
void vector_replace(vector *v, const void *elem_addr, int position){
assert(v != NULL);
assert(elem_addr != NULL);
assert(position >= 0);
assert(position < v->log_len);
void * destination = (char *)v->elems + position * v->elem_size;
memcpy(destination, elem_addr, v->elem_size);
}
void vector_delete(vector *v, int position){
assert(v != NULL);
assert(position >= 0);
assert(position < v->log_len);
void * destination = (char *)v->elems + position * v->elem_size;
void * source = (char *)v->elems + (position + 1) * v->elem_size;
int move_size = (v->log_len - position + 1) * v->elem_size;
memmove(destination, source, move_size);
v->log_len --;
}