]> asedeno.scripts.mit.edu Git - 1ts-debian.git/blob - libdyn/dyn_put.c
r4276@bucket (orig r266): kcr | 2008-01-21 11:20:29 -0500
[1ts-debian.git] / libdyn / dyn_put.c
1 /*
2  * This file is part of libdyn.a, the C Dynamic Object library.  It
3  * contains the source code for the functions DynGet() and DynAdd().
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 "dynP.h"
14
15 static int DynPut __P((DynObject obj, DynPtr el, int index));
16
17 DynPtr
18 DynGet(DynObject obj,
19        int num)
20 {
21      if (num < 0) {
22           if (obj->debug)
23                fprintf(stderr, "dyn: get: bad index %d\n", num);
24           return NULL;
25      }
26      
27      if (num >= obj->num_el) {
28           if (obj->debug)
29                fprintf(stderr, "dyn: get: highest element is %d.\n",
30                        obj->num_el);
31           return NULL;
32      }
33      
34      if (obj->debug)
35           fprintf(stderr, "dyn: get: Returning address %p + %d.\n",
36                   obj->array, obj->el_size*num);
37      
38      return (DynPtr) obj->array + obj->el_size*num;
39 }
40
41 int
42 DynAdd(DynObject obj,
43        DynPtr el)
44 {
45      int        ret;
46
47      ret = DynPut(obj, el, obj->num_el);
48      if (ret != DYN_OK)
49           return ret;
50
51      ++obj->num_el;
52      return ret;
53 }
54
55 /*
56  * WARNING!  There is a reason this function is not documented in the
57  * man page.  If DynPut used to mutate already existing elements,
58  * everything will go fine.  If it is used to add new elements
59  * directly, however, the state within the object (such as
60  * obj->num_el) will not be updated properly and many other functions
61  * in the library will lose.  Have a nice day.
62  */
63 static int
64 DynPut(DynObject obj,
65        DynPtr el,
66        int index)
67 {
68      int ret;
69      
70      if (obj->debug)
71           fprintf(stderr, "dyn: put: Writing %d bytes from %p to %p + %d\n",
72                   obj->el_size, el, obj->array, index*obj->el_size);
73
74      if ((ret = _DynResize(obj, index)) != DYN_OK)
75           return ret;
76      
77      (void) memmove(obj->array + index*obj->el_size, el, obj->el_size);
78
79      if (obj->debug)
80           fprintf(stderr, "dyn: put: done.\n");
81      
82      return DYN_OK;
83 }