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