libc_all.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // Copyright 2024 The Libc Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package libc is a partial reimplementation of C libc in pure Go.
  5. package libc // import "modernc.org/libc"
  6. import (
  7. "sync/atomic"
  8. "unsafe"
  9. "golang.org/x/exp/constraints"
  10. )
  11. func X__sync_add_and_fetch[T constraints.Integer](t *TLS, p uintptr, v T) T {
  12. switch unsafe.Sizeof(v) {
  13. case 4:
  14. return T(atomic.AddInt32((*int32)(unsafe.Pointer(p)), int32(v)))
  15. case 8:
  16. return T(atomic.AddInt64((*int64)(unsafe.Pointer(p)), int64(v)))
  17. default:
  18. panic(todo(""))
  19. }
  20. }
  21. func X__sync_sub_and_fetch[T constraints.Integer](t *TLS, p uintptr, v T) T {
  22. switch unsafe.Sizeof(v) {
  23. case 4:
  24. return T(atomic.AddInt32((*int32)(unsafe.Pointer(p)), -int32(v)))
  25. case 8:
  26. return T(atomic.AddInt64((*int64)(unsafe.Pointer(p)), -int64(v)))
  27. default:
  28. panic(todo(""))
  29. }
  30. }
  31. // GoString returns the value of a C string at s.
  32. func GoString(s uintptr) string {
  33. if s == 0 {
  34. return ""
  35. }
  36. p := s
  37. for *(*byte)(unsafe.Pointer(p)) != 0 {
  38. p++
  39. }
  40. return string(unsafe.Slice((*byte)(unsafe.Pointer(s)), p-s))
  41. }
  42. // GoBytes returns a byte slice from a C char* having length len bytes.
  43. func GoBytes(s uintptr, len int) []byte {
  44. return unsafe.Slice((*byte)(unsafe.Pointer(s)), len)
  45. }