go-append.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /* go-append.c -- the go builtin append function.
  2. Copyright 2010 The Go Authors. All rights reserved.
  3. Use of this source code is governed by a BSD-style
  4. license that can be found in the LICENSE file. */
  5. #include "runtime.h"
  6. #include "go-panic.h"
  7. #include "go-type.h"
  8. #include "array.h"
  9. #include "arch.h"
  10. #include "malloc.h"
  11. /* We should be OK if we don't split the stack here, since the only
  12. libc functions we call are memcpy and memmove. If we don't do
  13. this, we will always split the stack, because of memcpy and
  14. memmove. */
  15. extern struct __go_open_array
  16. __go_append (struct __go_open_array, void *, uintptr_t, uintptr_t)
  17. __attribute__ ((no_split_stack));
  18. struct __go_open_array
  19. __go_append (struct __go_open_array a, void *bvalues, uintptr_t bcount,
  20. uintptr_t element_size)
  21. {
  22. uintptr_t ucount;
  23. intgo count;
  24. if (bvalues == NULL || bcount == 0)
  25. return a;
  26. ucount = (uintptr_t) a.__count + bcount;
  27. count = (intgo) ucount;
  28. if ((uintptr_t) count != ucount || count <= a.__count)
  29. runtime_panicstring ("append: slice overflow");
  30. if (count > a.__capacity)
  31. {
  32. intgo m;
  33. uintptr capmem;
  34. void *n;
  35. m = a.__capacity;
  36. if (m + m < count)
  37. m = count;
  38. else
  39. {
  40. do
  41. {
  42. if (a.__count < 1024)
  43. m += m;
  44. else
  45. m += m / 4;
  46. }
  47. while (m < count);
  48. }
  49. if (element_size > 0 && (uintptr) m > MaxMem / element_size)
  50. runtime_panicstring ("growslice: cap out of range");
  51. capmem = runtime_roundupsize (m * element_size);
  52. n = __go_alloc (capmem);
  53. __builtin_memcpy (n, a.__values, a.__count * element_size);
  54. a.__values = n;
  55. a.__capacity = m;
  56. }
  57. __builtin_memmove ((char *) a.__values + a.__count * element_size,
  58. bvalues, bcount * element_size);
  59. a.__count = count;
  60. return a;
  61. }