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

// Package libc is a partial reimplementation of C libc in pure Go.
//
// # READ THIS BEFORE UPGRADING
//
// This package is to ccgo what the runtime package is to Go. It is not a
// library you happen to link against, it is the other half of the compiler.
// Code that ccgo produced and the libc it was produced for are one artifact
// split across two modules, and they are only ever tested as a pair.
//
// That is why the version numbers here do not mean what semver says they mean.
// A release that bumps only the patch or the minor number can still change the
// contract between generated code and this package, which by semver's own rules
// it must not. Read every libc version as though it were a major one.
//
// None of this is new. It has been documented for as long as this package has
// carried ccgo's runtime, and it holds for every release. What is new is how it
// fails.
//
// Upgrading libc alone used to change behaviour quietly. It can now stop the
// build. The setjmp/longjmp support changed shape: LongjmpRetval went from an
// integer to a struct naming the jump buffer a longjmp targeted, because a
// region recovering that panic has no other way to tell whether the longjmp was
// meant for it or for a setjmp further out, and recovering one meant for another
// region resumes the program at the wrong place. Code generated by an older ccgo
// does not compile against it, failing on the conversion between LongjmpRetval
// and int32. That is the intended outcome rather than an oversight: a refusal to
// build, in place of a program that would have built and then jumped to the
// wrong setjmp.
//
// This is a correctness fix and there is no backward compatible way to make it.
// Deciding which region a longjmp belongs to needs information the old panic
// value did not carry, so any fix has to change what that value is. Keeping the
// old shape working alongside the new one would leave every consumer silently on
// the broken path, which is the bug.
//
// The remedy is what it has always been, and it is not to pin an old libc and
// hope: recompile your C to Go with a ccgo new enough to depend on the libc you
// want, then use that pair together. If you consume translated code produced by
// someone else, modernc.org/sqlite for instance, take the libc version from that
// package's go.mod and do not bump it on your own just because a newer libc is
// tagged.
package libc // import "modernc.org/libc"

import (
	"math"
	"sync/atomic"
	"unsafe"
)

type integer interface {
	~int | ~int32 | ~int64 | ~uint | ~uint32 | ~uint64 | ~uintptr
}

func X__sync_add_and_fetch[T integer](t *TLS, p uintptr, v T) T {
	switch unsafe.Sizeof(v) {
	case 4:
		return T(atomic.AddInt32((*int32)(unsafe.Pointer(p)), int32(v)))
	case 8:
		return T(atomic.AddInt64((*int64)(unsafe.Pointer(p)), int64(v)))
	default:
		panic(todo(""))
	}
}

func X__sync_sub_and_fetch[T integer](t *TLS, p uintptr, v T) T {
	switch unsafe.Sizeof(v) {
	case 4:
		return T(atomic.AddInt32((*int32)(unsafe.Pointer(p)), -int32(v)))
	case 8:
		return T(atomic.AddInt64((*int64)(unsafe.Pointer(p)), -int64(v)))
	default:
		panic(todo(""))
	}
}

// GoString returns the value of a C string at s.
func GoString(s uintptr) string {
	if s == 0 {
		return ""
	}

	if n := strlen(s); n != 0 {
		return string(unsafe.Slice((*byte)(unsafe.Pointer(s)), n))
	}

	return ""
}

// GoBytes returns a byte slice from a C char* having length len bytes.
func GoBytes(s uintptr, len int) []byte {
	return unsafe.Slice((*byte)(unsafe.Pointer(s)), len)
}

func X__isfinitef(tls *TLS, f float32) int32 {
	d := float64(f)
	if !math.IsInf(d, 0) && !math.IsNaN(d) {
		return 1
	}

	return 0
}

func X__isfinite(tls *TLS, d float64) int32 {
	if !math.IsInf(d, 0) && !math.IsNaN(d) {
		return 1
	}

	return 0
}

func X__isfinitel(tls *TLS, d float64) int32 {
	if !math.IsInf(d, 0) && !math.IsNaN(d) {
		return 1
	}

	return 0
}

func strlen(s uintptr) (r Tsize_t) {
	if s == 0 {
		return 0
	}

	if strlenUseIndexByte {
		return strlenIndexByte(s)
	}

	return strlenWords(s)
}

// size_t strlen(const char *s)
func Xstrlen(t *TLS, s uintptr) (r Tsize_t) {
	if __ccgo_strace {
		trc("t=%v s=%v, (%v:)", t, s, origin(2))
		defer func() { trc("-> %v", r) }()
	}
	return strlen(s)

}

func _strlen(t *TLS, s uintptr) (r Tsize_t) {
	return strlen(s)
}

func X__builtin_ilogb(tls *TLS, x float64) int32 {
	return int32(math.Ilogb(x))
}

func X__builtin_ilogbl(tls *TLS, x float64) int32 {
	return int32(math.Ilogb(x))
}

func X__builtin_ilogbf(tls *TLS, x float32) int32 {
	// Casting to float64 is safe and mathematically correct here.
	// Subnormal float32 values become normal float64 values,
	// which allows math.Ilogb to correctly return their negative exponent.
	return int32(math.Ilogb(float64(x)))
}
