summaryrefslogtreecommitdiff
path: root/libgo/runtime/go-append.c
blob: 91493b1b78d7ecb4082e1f0f99b0ec723eaa43c9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/* go-append.c -- the go builtin append function.

   Copyright 2010 The Go Authors. All rights reserved.
   Use of this source code is governed by a BSD-style
   license that can be found in the LICENSE file.  */

#include "go-type.h"
#include "go-panic.h"
#include "array.h"
#include "runtime.h"
#include "malloc.h"

/* We should be OK if we don't split the stack here, since the only
   libc functions we call are memcpy and memmove.  If we don't do
   this, we will always split the stack, because of memcpy and
   memmove.  */
extern struct __go_open_array
__go_append (struct __go_open_array, void *, size_t, size_t)
  __attribute__ ((no_split_stack));

struct __go_open_array
__go_append (struct __go_open_array a, void *bvalues, size_t bcount,
	     size_t element_size)
{
  size_t ucount;
  int count;

  if (bvalues == NULL || bcount == 0)
    return a;

  ucount = (size_t) a.__count + bcount;
  count = (int) ucount;
  if ((size_t) count != ucount || count <= a.__count)
    __go_panic_msg ("append: slice overflow");

  if (count > a.__capacity)
    {
      int m;
      void *n;

      m = a.__capacity;
      if (m == 0)
	m = (int) bcount;
      else
	{
	  do
	    {
	      if (a.__count < 1024)
		m += m;
	      else
		m += m / 4;
	    }
	  while (m < count);
	}

      n = __go_alloc (m * element_size);
      __builtin_memcpy (n, a.__values, a.__count * element_size);

      a.__values = n;
      a.__capacity = m;
    }

  __builtin_memmove ((char *) a.__values + a.__count * element_size,
		     bvalues, bcount * element_size);
  a.__count = count;
  return a;
}