// Code generated by modernc.org/undup from the per-target sqlite_*.go files; DO NOT EDIT.

//go:build (freebsd && arm64) || (linux && arm64) || (linux && ppc64le) || (linux && riscv64) || (openbsd && arm64)

package sqlite3

import (
	"unsafe"

	"modernc.org/libc"
)

// C documentation
//
//	/*
//	** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
//	*/
func _sqlite3Prepare16(tls *libc.TLS, db uintptr, zSql uintptr, nBytes int32, prepFlags Tu32, ppStmt uintptr, pzTail uintptr) (r int32) {
	bp := tls.Alloc(16)
	defer tls.Free(16)
	var chars_parsed, rc, sz, sz1 int32
	var z, z1, zSql8 uintptr
	var _ /* zTail8 at bp+0 */ uintptr
	_, _, _, _, _, _, _ = chars_parsed, rc, sz, sz1, z, z1, zSql8
	**(**uintptr)(__ccgo_up(bp)) = uintptr(0)
	rc = SQLITE_OK
	**(**uintptr)(__ccgo_up(ppStmt)) = uintptr(0)
	if !(_sqlite3SafetyCheckOk(tls, db) != 0) || zSql == uintptr(0) {
		return _sqlite3MisuseError(tls, int32(148902))
	}
	/* Make sure nBytes is non-negative and correct.  It should be the
	 ** number of bytes until the end of the input buffer or until the first
	 ** U+0000 character.  If the input nBytes is odd, convert it into
	 ** an even number.  If the input nBytes is negative, then the input
	 ** must be terminated by at least one U+0000 character */
	if nBytes >= 0 {
		z = zSql
		sz = 0
		for {
			if !(sz < nBytes && (libc.Int32FromUint8(**(**uint8)(__ccgo_up(z + uintptr(sz)))) != 0 || libc.Int32FromUint8(**(**uint8)(__ccgo_up(z + uintptr(sz+int32(1))))) != 0)) {
				break
			}
			goto _1
		_1:
			;
			sz = sz + int32(2)
		}
		nBytes = sz
	} else {
		z1 = zSql
		sz1 = 0
		for {
			if !(libc.Int32FromUint8(**(**uint8)(__ccgo_up(z1 + uintptr(sz1)))) != 0 || libc.Int32FromUint8(**(**uint8)(__ccgo_up(z1 + uintptr(sz1+int32(1))))) != 0) {
				break
			}
			goto _2
		_2:
			;
			sz1 = sz1 + int32(2)
		}
		nBytes = sz1
	}
	Xsqlite3_mutex_enter(tls, (*Tsqlite3)(unsafe.Pointer(db)).Fmutex)
	zSql8 = _sqlite3Utf16to8(tls, db, zSql, nBytes, uint8(SQLITE_UTF16LE))
	if zSql8 != 0 {
		rc = _sqlite3LockAndPrepare(tls, db, zSql8, -int32(1), prepFlags, uintptr(0), ppStmt, bp)
	}
	if **(**uintptr)(__ccgo_up(bp)) != 0 && pzTail != 0 {
		/* If sqlite3_prepare returns a tail pointer, we calculate the
		 ** equivalent pointer into the UTF-16 string by counting the unicode
		 ** characters between zSql8 and zTail8, and then returning a pointer
		 ** the same number of characters into the UTF-16 string.
		 */
		chars_parsed = _sqlite3Utf8CharLen(tls, zSql8, int32(int64(**(**uintptr)(__ccgo_up(bp)))-int64(zSql8)))
		**(**uintptr)(__ccgo_up(pzTail)) = zSql + uintptr(_sqlite3Utf16ByteLen(tls, zSql, nBytes, chars_parsed))
	}
	_sqlite3DbFree(tls, db, zSql8)
	rc = _sqlite3ApiExit(tls, db, rc)
	Xsqlite3_mutex_leave(tls, (*Tsqlite3)(unsafe.Pointer(db)).Fmutex)
	return rc
}
