1 /*
2  * This file is part of libdyn.a, the C Dynamic Object library.  It
3  * contains the source code for the function DynInsert().
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 <string.h>
15 #include "dynP.h"
16 
DynInsert(obj,index,els,num)17 int DynInsert(obj, index, els, num)
18    DynObjectP obj;
19    DynPtr els;
20    int index, num;
21 {
22      int ret;
23 
24      if (index < 0 || index > obj->num_el) {
25 	  if (obj->debug)
26 	       fprintf(stderr, "dyn: insert: index %d is not in [0,%d]\n",
27 		       index, obj->num_el);
28 	  return DYN_BADINDEX;
29      }
30 
31      if (num < 1) {
32 	  if (obj->debug)
33 	       fprintf(stderr, "dyn: insert: cannot insert %d elements\n",
34 		       num);
35 	  return DYN_BADVALUE;
36      }
37 
38      if (obj->debug)
39 	  fprintf(stderr,"dyn: insert: Moving %d bytes from %p + %d to + %d\n",
40 		  (obj->num_el-index)*obj->el_size, obj->array,
41 		  obj->el_size*index, obj->el_size*(index+num));
42 
43      if ((ret = _DynResize(obj, obj->num_el + num)) != DYN_OK)
44 	  return ret;
45 
46      bcopy(obj->array + index, obj->array + (index + num),
47 	   (obj->num_el-index)*obj->el_size);
48 
49      if (obj->debug)
50 	  fprintf(stderr, "dyn: insert: Copying %d bytes from %p to %p + %d\n",
51 		  obj->el_size*num, els, obj->array, obj->el_size*index);
52 
53      bcopy(els, obj->array + obj->el_size*index, obj->el_size*num);
54 
55      obj->num_el += num;
56 
57      if (obj->debug)
58 	  fprintf(stderr, "dyn: insert: done.\n");
59 
60      return DYN_OK;
61 }
62