1 /*
2 * This file is part of libdyn.a, the C Dynamic Object library. It
3 * contains the source code for the internal function _DynRealloc().
4 *
5 * There are no restrictions on this code; however, if you make any
6 * changes, I request that you document them so that I do not get
7 * credit or blame for your modifications.
8 *
9 * Written by Barr3y Jaspan, Student Information Processing Board (SIPB)
10 * and MIT-Project Athena, 1989.
11 */
12
13 #include <stdio.h>
14 #include <stdlib.h>
15
16 #include "dynP.h"
17
18 /*
19 * Resize the array so that element req exists.
20 */
_DynResize(obj,req)21 int _DynResize(obj, req)
22 DynObjectP obj;
23 int req;
24 {
25 int cnt, size;
26
27 if (obj->size > req)
28 return DYN_OK;
29 else if (obj->inc > 0)
30 return _DynRealloc(obj, (req - obj->size) / obj->inc + 1);
31 else {
32 if (obj->size == 0)
33 size = -obj->inc;
34 else
35 size = obj->size;
36
37 while (size <= req)
38 size <<= 1;
39
40 return _DynRealloc(obj, size);
41 }
42 }
43
44 /*
45 * Resize the array by num_incs units. If obj->inc is positive, this
46 * means make it obj->inc*num_incs elements larger. If obj->inc is
47 * negative, this means make the array num_incs elements long.
48 *
49 * Ideally, this function should not be called from outside the
50 * library. However, nothing will break if it is.
51 */
_DynRealloc(obj,num_incs)52 int _DynRealloc(obj, num_incs)
53 DynObjectP obj;
54 int num_incs;
55 {
56 DynPtr temp;
57 int new_size_in_bytes;
58
59 if (obj->inc > 0)
60 new_size_in_bytes = obj->el_size*(obj->size + obj->inc*num_incs);
61 else
62 new_size_in_bytes = obj->el_size*num_incs;
63
64 if (obj->debug)
65 fprintf(stderr,
66 "dyn: alloc: Increasing object by %d bytes (%d incs).\n",
67 new_size_in_bytes - obj->el_size*obj->size,
68 num_incs);
69
70 temp = (DynPtr) realloc(obj->array, new_size_in_bytes);
71 if (temp == NULL) {
72 if (obj->debug)
73 fprintf(stderr, "dyn: alloc: Out of memory.\n");
74 return DYN_NOMEM;
75 }
76 else {
77 obj->array = temp;
78 if (obj->inc > 0)
79 obj->size += obj->inc*num_incs;
80 else
81 obj->size = num_incs;
82 }
83
84 if (obj->debug)
85 fprintf(stderr, "dyn: alloc: done.\n");
86
87 return DYN_OK;
88 }
89