xref: /PHP-7.4/sapi/fpm/fpm/fpm_arrays.h (revision 1ad08256)
1 	/* (c) 2007,2008 Andrei Nigmatulin */
2 
3 #ifndef FPM_ARRAYS_H
4 #define FPM_ARRAYS_H 1
5 
6 #include <stdlib.h>
7 #include <string.h>
8 
9 struct fpm_array_s {
10 	void *data;
11 	size_t sz;
12 	size_t used;
13 	size_t allocated;
14 };
15 
fpm_array_init(struct fpm_array_s * a,unsigned int sz,unsigned int initial_num)16 static inline struct fpm_array_s *fpm_array_init(struct fpm_array_s *a, unsigned int sz, unsigned int initial_num) /* {{{ */
17 {
18 	void *allocated = 0;
19 
20 	if (!a) {
21 		a = malloc(sizeof(struct fpm_array_s));
22 
23 		if (!a) {
24 			return 0;
25 		}
26 
27 		allocated = a;
28 	}
29 
30 	a->sz = sz;
31 
32 	a->data = calloc(sz, initial_num);
33 
34 	if (!a->data) {
35 		free(allocated);
36 		return 0;
37 	}
38 
39 	a->allocated = initial_num;
40 	a->used = 0;
41 
42 	return a;
43 }
44 /* }}} */
45 
fpm_array_item(struct fpm_array_s * a,unsigned int n)46 static inline void *fpm_array_item(struct fpm_array_s *a, unsigned int n) /* {{{ */
47 {
48 	char *ret;
49 
50 	ret = (char *) a->data + a->sz * n;
51 
52 	return ret;
53 }
54 /* }}} */
55 
fpm_array_item_last(struct fpm_array_s * a)56 static inline void *fpm_array_item_last(struct fpm_array_s *a) /* {{{ */
57 {
58 	return fpm_array_item(a, a->used - 1);
59 }
60 /* }}} */
61 
fpm_array_item_remove(struct fpm_array_s * a,unsigned int n)62 static inline int fpm_array_item_remove(struct fpm_array_s *a, unsigned int n) /* {{{ */
63 {
64 	int ret = -1;
65 
66 	if (n < a->used - 1) {
67 		void *last = fpm_array_item(a, a->used - 1);
68 		void *to_remove = fpm_array_item(a, n);
69 
70 		memcpy(to_remove, last, a->sz);
71 
72 		ret = n;
73 	}
74 
75 	--a->used;
76 
77 	return ret;
78 }
79 /* }}} */
80 
fpm_array_push(struct fpm_array_s * a)81 static inline void *fpm_array_push(struct fpm_array_s *a) /* {{{ */
82 {
83 	void *ret;
84 
85 	if (a->used == a->allocated) {
86 		size_t new_allocated = a->allocated ? a->allocated * 2 : 20;
87 		void *new_ptr = realloc(a->data, a->sz * new_allocated);
88 
89 		if (!new_ptr) {
90 			return 0;
91 		}
92 
93 		a->data = new_ptr;
94 		a->allocated = new_allocated;
95 	}
96 
97 	ret = fpm_array_item(a, a->used);
98 
99 	++a->used;
100 
101 	return ret;
102 }
103 /* }}} */
104 
fpm_array_free(struct fpm_array_s * a)105 static inline void fpm_array_free(struct fpm_array_s *a) /* {{{ */
106 {
107 	free(a->data);
108 	a->data = 0;
109 	a->sz = 0;
110 	a->used = a->allocated = 0;
111 }
112 /* }}} */
113 
114 #endif
115