]>
git.proxmox.com Git - mirror_ovs.git/blob - lib/object-collection.c
2 * Copyright (c) 2016 Nicira, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at:
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
19 #include "object-collection.h"
23 object_collection_init(struct object_collection
*coll
)
25 coll
->objs
= coll
->stub
;
27 coll
->capacity
= ARRAY_SIZE(coll
->stub
);
31 object_collection_add(struct object_collection
*coll
, void *obj
)
33 if (coll
->n
>= coll
->capacity
) {
34 size_t old_size
, new_size
;
36 old_size
= coll
->capacity
* sizeof *coll
->objs
;
38 new_size
= coll
->capacity
* sizeof *coll
->objs
;
40 if (coll
->objs
== coll
->stub
) {
41 coll
->objs
= xmalloc(new_size
);
42 memcpy(coll
->objs
, coll
->stub
, old_size
);
44 coll
->objs
= xrealloc(coll
->objs
, new_size
);
48 coll
->objs
[coll
->n
++] = obj
;
52 object_collection_remove(struct object_collection
*coll
, void *obj
)
56 for (i
= 0; i
< coll
->n
; i
++) {
57 if (coll
->objs
[i
] == obj
) {
66 /* Swap the last item in if needed. */
68 coll
->objs
[i
] = coll
->objs
[coll
->n
];
71 /* Shrink? Watermark at '/ 4' to get hysteresis and leave spare
73 if (coll
->objs
!= coll
->stub
&& coll
->n
<= coll
->capacity
/ 4) {
74 size_t actual_size
, new_size
;
76 actual_size
= coll
->n
* sizeof *coll
->objs
;
78 new_size
= coll
->capacity
* sizeof *coll
->objs
;
80 if (new_size
<= sizeof(coll
->stub
)) {
81 memcpy(coll
->stub
, coll
->objs
, actual_size
);
83 coll
->objs
= coll
->stub
;
85 coll
->objs
= xrealloc(coll
->objs
, new_size
);
91 object_collection_move(struct object_collection
*to
,
92 struct object_collection
*from
)
94 ovs_assert(to
->n
== 0);
97 if (from
->objs
== from
->stub
) {
100 object_collection_init(from
);
103 /* Returns a NULL-terminated array of object pointers,
104 * destroys 'rules'. */
106 object_collection_detach(struct object_collection
*coll
)
110 object_collection_add(coll
, NULL
);
112 if (coll
->objs
== coll
->stub
) {
113 coll
->objs
= xmemdup(coll
->objs
, coll
->n
* sizeof *coll
->objs
);
117 object_collection_init(coll
);
123 object_collection_destroy(struct object_collection
*coll
)
125 if (coll
->objs
!= coll
->stub
) {
129 /* Make repeated destruction harmless. */
130 object_collection_init(coll
);