Use unsigned types in interop (#1913)

This commit is contained in:
SvyatoslavScherbina
2018-08-24 18:30:56 +03:00
committed by GitHub
parent 29cddb46bf
commit 8f1b94f38b
46 changed files with 665 additions and 192 deletions
@@ -45,7 +45,7 @@ fun CPointer<ByteVar>.toKString(length: Int): String {
}
fun header_callback(buffer: CPointer<ByteVar>?, size: size_t, nitems: size_t, userdata: COpaquePointer?): size_t {
if (buffer == null) return 0
if (buffer == null) return 0u
if (userdata != null) {
val header = buffer.toKString((size * nitems).toInt()).trim()
val curl = userdata.asStableRef<CUrl>().get()
@@ -56,7 +56,7 @@ fun header_callback(buffer: CPointer<ByteVar>?, size: size_t, nitems: size_t, us
fun write_callback(buffer: CPointer<ByteVar>?, size: size_t, nitems: size_t, userdata: COpaquePointer?): size_t {
if (buffer == null) return 0
if (buffer == null) return 0u
if (userdata != null) {
val data = buffer.toKString((size * nitems).toInt()).trim()
val curl = userdata.asStableRef<CUrl>().get()
@@ -32,11 +32,11 @@ class GitCommit(val repository: GitRepository, val commit: CPointer<git_commit>)
}
val parents: List<GitCommit> get() = memScoped {
val count = git_commit_parentcount(commit)
val count = git_commit_parentcount(commit).toInt()
val result = ArrayList<GitCommit>(count)
for (index in 0..count - 1) {
val commitPtr = allocPointerTo<git_commit>()
git_commit_parent(commitPtr.ptr, commit, index).errorCheck()
git_commit_parent(commitPtr.ptr, commit, index.toUInt()).errorCheck()
result.add(GitCommit(repository, commitPtr.value!!))
}
result
@@ -21,10 +21,10 @@ import libgit2.*
class GitDiff(val repository: GitRepository, val handle: CPointer<git_diff>) {
fun deltas(): List<GifDiffDelta> {
val size = git_diff_num_deltas(handle)
val results = ArrayList<GifDiffDelta>(size.toInt())
val size = git_diff_num_deltas(handle).toInt()
val results = ArrayList<GifDiffDelta>(size)
for (index in 0..size - 1) {
val delta = git_diff_get_delta(handle, index)
val delta = git_diff_get_delta(handle, index.convert())
results.add(GifDiffDelta(this, delta!!))
}
return results
@@ -23,10 +23,10 @@ class GitTree(val repository: GitRepository, val handle: CPointer<git_tree>) {
fun close() = git_tree_free(handle)
fun entries(): List<GitTreeEntry> = memScoped {
val size = git_tree_entrycount(handle)
val entries = ArrayList<GitTreeEntry>(size.toInt())
val size = git_tree_entrycount(handle).toInt()
val entries = ArrayList<GitTreeEntry>(size)
for (index in 0..size - 1) {
val treeEntry = git_tree_entry_byindex(handle, index)!!
val treeEntry = git_tree_entry_byindex(handle, index.convert())!!
val entryType = git_tree_entry_type(treeEntry)
val entry = when (entryType) {
GIT_OBJ_TREE -> memScoped {
+1 -1
View File
@@ -19,7 +19,7 @@ import gtk3.*
// Note that all callback parameters must be primitive types or nullable C pointers.
fun <F : CFunction<*>> g_signal_connect(obj: CPointer<*>, actionName: String,
action: CPointer<F>, data: gpointer? = null, connect_flags: Int = 0) {
action: CPointer<F>, data: gpointer? = null, connect_flags: GConnectFlags = 0u) {
g_signal_connect_data(obj.reinterpret(), actionName, action.reinterpret(),
data = data, destroy_data = null, connect_flags = connect_flags)
@@ -32,16 +32,16 @@ fun main(args: Array<String>) {
val serverAddr = alloc<sockaddr_in>()
val listenFd = socket(AF_INET, SOCK_STREAM, 0)
.ensureUnixCallResult { it >= 0 }
.ensureUnixCallResult { !it.isMinusOne() }
with(serverAddr) {
memset(this.ptr, 0, sockaddr_in.size)
sin_family = AF_INET.narrow()
sin_addr.s_addr = posix_htons(0).toInt()
sin_port = posix_htons(port)
memset(this.ptr, 0, sockaddr_in.size.convert())
sin_family = AF_INET.convert()
sin_addr.s_addr = posix_htons(0).convert()
sin_port = posix_htons(port).convert()
}
bind(listenFd, serverAddr.ptr.reinterpret(), sockaddr_in.size.toInt())
bind(listenFd, serverAddr.ptr.reinterpret(), sockaddr_in.size.toUInt())
.ensureUnixCallResult { it == 0 }
fcntl(listenFd, F_SETFL, O_NONBLOCK)
@@ -53,8 +53,8 @@ fun main(args: Array<String>) {
var connectionId = 0
acceptClientsAndRun(listenFd) {
memScoped {
val bufferLength = 100L
val buffer = allocArray<ByteVar>(bufferLength)
val bufferLength = 100uL
val buffer = allocArray<ByteVar>(bufferLength.toLong())
val connectionIdString = "#${++connectionId}: ".cstr
val connectionIdBytes = connectionIdString.ptr
@@ -62,10 +62,10 @@ fun main(args: Array<String>) {
while (true) {
val length = read(buffer, bufferLength)
if (length == 0L)
if (length == 0uL)
break
write(connectionIdBytes, connectionIdString.size.toLong())
write(connectionIdBytes, connectionIdString.size.toULong())
write(buffer, length)
}
} catch (e: IOException) {
@@ -80,19 +80,19 @@ sealed class WaitingFor {
class Accept : WaitingFor()
class Read(val data: CArrayPointer<ByteVar>,
val length: Long,
val continuation: Continuation<Long>) : WaitingFor()
val length: ULong,
val continuation: Continuation<ULong>) : WaitingFor()
class Write(val data: CArrayPointer<ByteVar>,
val length: Long,
val length: ULong,
val continuation: Continuation<Unit>) : WaitingFor()
}
class Client(val clientFd: Int, val waitingList: MutableMap<Int, WaitingFor>) {
suspend fun read(data: CArrayPointer<ByteVar>, dataLength: Long): Long {
suspend fun read(data: CArrayPointer<ByteVar>, dataLength: ULong): ULong {
val length = read(clientFd, data, dataLength)
if (length >= 0)
return length
return length.toULong()
if (posix_errno() != EWOULDBLOCK)
throw IOException(getUnixError())
// Save continuation and suspend.
@@ -101,7 +101,7 @@ class Client(val clientFd: Int, val waitingList: MutableMap<Int, WaitingFor>) {
}
}
suspend fun write(data: CArrayPointer<ByteVar>, length: Long) {
suspend fun write(data: CArrayPointer<ByteVar>, length: ULong) {
val written = write(clientFd, data, length)
if (written >= 0)
return
@@ -153,7 +153,7 @@ fun acceptClientsAndRun(serverFd: Int, block: suspend Client.() -> Unit) {
// Accept new client.
val clientFd = accept(serverFd, null, null)
if (clientFd < 0) {
if (clientFd.isMinusOne()) {
if (posix_errno() != EWOULDBLOCK)
throw Error(getUnixError())
break@loop
@@ -173,7 +173,7 @@ fun acceptClientsAndRun(serverFd: Int, block: suspend Client.() -> Unit) {
val length = read(socketFd, waitingFor.data, waitingFor.length)
if (length < 0) // Read error.
waitingFor.continuation.resumeWithException(IOException(getUnixError()))
waitingFor.continuation.resume(length)
waitingFor.continuation.resume(length.toULong())
}
is WaitingFor.Write -> {
if (errorOccured)
@@ -210,3 +210,14 @@ inline fun Long.ensureUnixCallResult(predicate: (Long) -> Boolean): Long {
}
return this
}
inline fun ULong.ensureUnixCallResult(predicate: (ULong) -> Boolean): ULong {
if (!predicate(this)) {
throw Error(getUnixError())
}
return this
}
private fun Int.isMinusOne() = (this == -1)
private fun Long.isMinusOne() = (this == -1L)
private fun ULong.isMinusOne() = (this == ULong.MAX_VALUE)
+2 -2
View File
@@ -24,7 +24,7 @@ private fun runApp() {
app.run()
}
data class Data(val stamp: Long)
data class Data(val stamp: ULong)
private class Controller : NSObject() {
private val asyncQueue = dispatch_queue_create("com.jetbrains.CustomQueue", null)
@@ -33,7 +33,7 @@ private class Controller : NSObject() {
fun onClick() {
// Execute some async action on button click.
dispatch_async_f(asyncQueue, detachObjectGraph {
Data(clock_gettime_nsec_np(CLOCK_REALTIME))
Data(clock_gettime_nsec_np(CLOCK_REALTIME.convert()))
}, staticCFunction {
it ->
initRuntimeIfNeeded()
+20 -20
View File
@@ -29,7 +29,7 @@ private val windowHeight = 480
fun display() {
// Clear Screen and Depth Buffer
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT)
glClear((GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT).convert())
glLoadIdentity()
// Define a viewing transformation
@@ -56,13 +56,13 @@ fun display() {
fun initialize() {
// select projection matrix
glMatrixMode(GL_PROJECTION)
glMatrixMode(GL_PROJECTION.convert())
// set the viewport
glViewport(0, 0, windowWidth, windowHeight)
// set matrix mode
glMatrixMode(GL_PROJECTION)
glMatrixMode(GL_PROJECTION.convert())
// reset projection matrix
glLoadIdentity()
@@ -72,29 +72,29 @@ fun initialize() {
gluPerspective(45.0, aspect, 1.0, 500.0)
// specify which matrix is the current matrix
glMatrixMode(GL_MODELVIEW)
glShadeModel(GL_SMOOTH)
glMatrixMode(GL_MODELVIEW.convert())
glShadeModel(GL_SMOOTH.convert())
// specify the clear value for the depth buffer
glClearDepth(1.0)
glEnable(GL_DEPTH_TEST)
glDepthFunc(GL_LEQUAL)
glEnable(GL_DEPTH_TEST.convert())
glDepthFunc(GL_LEQUAL.convert())
// specify implementation-specific hints
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST)
glHint(GL_PERSPECTIVE_CORRECTION_HINT.convert(), GL_NICEST.convert())
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, cValuesOf(0.1f, 0.1f, 0.1f, 1.0f))
glLightfv(GL_LIGHT0, GL_DIFFUSE, cValuesOf(0.6f, 0.6f, 0.6f, 1.0f))
glLightfv(GL_LIGHT0, GL_SPECULAR, cValuesOf(0.7f, 0.7f, 0.3f, 1.0f))
glLightModelfv(GL_LIGHT_MODEL_AMBIENT.convert(), cValuesOf(0.1f, 0.1f, 0.1f, 1.0f))
glLightfv(GL_LIGHT0.convert(), GL_DIFFUSE.convert(), cValuesOf(0.6f, 0.6f, 0.6f, 1.0f))
glLightfv(GL_LIGHT0.convert(), GL_SPECULAR.convert(), cValuesOf(0.7f, 0.7f, 0.3f, 1.0f))
glEnable(GL_LIGHT0)
glEnable(GL_COLOR_MATERIAL)
glShadeModel(GL_SMOOTH)
glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE)
glDepthFunc(GL_LEQUAL)
glEnable(GL_DEPTH_TEST)
glEnable(GL_LIGHTING)
glEnable(GL_LIGHT0)
glEnable(GL_LIGHT0.convert())
glEnable(GL_COLOR_MATERIAL.convert())
glShadeModel(GL_SMOOTH.convert())
glLightModeli(GL_LIGHT_MODEL_TWO_SIDE.convert(), GL_FALSE)
glDepthFunc(GL_LEQUAL.convert())
glEnable(GL_DEPTH_TEST.convert())
glEnable(GL_LIGHTING.convert())
glEnable(GL_LIGHT0.convert())
glClearColor(0.0f, 0.0f, 0.0f, 1.0f)
}
@@ -106,7 +106,7 @@ fun main(args: Array<String>) {
}
// Display Mode
glutInitDisplayMode(GLUT_RGB or GLUT_DOUBLE or GLUT_DEPTH)
glutInitDisplayMode((GLUT_RGB or GLUT_DOUBLE or GLUT_DEPTH).convert())
// Set window size
glutInitWindowSize(windowWidth, windowHeight)
+20 -9
View File
@@ -35,35 +35,35 @@ fun main(args: Array<String>) {
val serverAddr = alloc<sockaddr_in>()
val listenFd = socket(AF_INET, SOCK_STREAM, 0)
.ensureUnixCallResult("socket") { it >= 0 }
.ensureUnixCallResult("socket") { !it.isMinusOne() }
with(serverAddr) {
memset(this.ptr, 0, sockaddr_in.size)
sin_family = AF_INET.narrow()
sin_port = posix_htons(port)
memset(this.ptr, 0, sockaddr_in.size.convert())
sin_family = AF_INET.convert()
sin_port = posix_htons(port).convert()
}
bind(listenFd, serverAddr.ptr.reinterpret(), sockaddr_in.size.toInt())
bind(listenFd, serverAddr.ptr.reinterpret(), sockaddr_in.size.convert())
.ensureUnixCallResult("bind") { it == 0 }
listen(listenFd, 10)
.ensureUnixCallResult("listen") { it == 0 }
val commFd = accept(listenFd, null, null)
.ensureUnixCallResult("accept") { it >= 0 }
.ensureUnixCallResult("accept") { !it.isMinusOne() }
buffer.usePinned { pinned ->
while (true) {
val length = recv(commFd, pinned.addressOf(0), buffer.size.signExtend(), 0).toInt()
val length = recv(commFd, pinned.addressOf(0), buffer.size.convert(), 0).toInt()
.ensureUnixCallResult("read") { it >= 0 }
if (length == 0) {
break
}
send(commFd, prefixBuffer.refTo(0), prefixBuffer.size.signExtend(), 0)
send(commFd, prefixBuffer.refTo(0), prefixBuffer.size.convert(), 0)
.ensureUnixCallResult("write") { it >= 0 }
send(commFd, pinned.addressOf(0), length.signExtend(), 0)
send(commFd, pinned.addressOf(0), length.convert(), 0)
.ensureUnixCallResult("write") { it >= 0 }
}
}
@@ -83,3 +83,14 @@ inline fun Long.ensureUnixCallResult(op: String, predicate: (Long) -> Boolean):
}
return this
}
inline fun ULong.ensureUnixCallResult(op: String, predicate: (ULong) -> Boolean): ULong {
if (!predicate(this)) {
throw Error("$op: ${strerror(posix_errno())!!.toKString()}")
}
return this
}
private fun Int.isMinusOne() = (this == -1)
private fun Long.isMinusOne() = (this == -1L)
private fun ULong.isMinusOne() = (this == ULong.MAX_VALUE)
@@ -1,4 +1,5 @@
import kotlinx.cinterop.*
import platform.posix.size_t
import tensorflow.*
typealias Status = CPointer<TF_Status>
@@ -31,13 +32,13 @@ fun scalarTensor(value: Int): Tensor {
return TF_NewTensor(TF_INT32,
dims = null, num_dims = 0,
data = data, len = IntVar.size,
data = data, len = IntVar.size.convert(),
deallocator = staticCFunction { dataToFree, _, _ -> nativeHeap.free(dataToFree!!.reinterpret<IntVar>()) },
deallocator_arg = null)!!
}
val Tensor.scalarIntValue: Int get() {
if (TF_INT32 != TF_TensorType(this) || IntVar.size != TF_TensorByteSize(this)) {
if (TF_INT32 != TF_TensorType(this) || IntVar.size.convert<size_t>() != TF_TensorByteSize(this)) {
throw Error("Tensor is not of type int.")
}
if (0 != TF_NumDims(this)) {
@@ -42,13 +42,13 @@ class AudioFrame(val buffer: CPointer<AVBufferRef>, var position: Int, val size:
private fun Int.checkAVError() {
if (this != 0) {
val buffer = ByteArray(1024)
av_strerror(this, buffer.refTo(0), buffer.size.signExtend())
av_strerror(this, buffer.refTo(0), buffer.size.convert())
throw Error("AVError: ${buffer.stringFromUtf8()}")
}
}
private val AVFormatContext.codecs: List<AVCodecContext?>
get() = List(nb_streams) { streams?.get(it)?.pointed?.codec?.pointed }
get() = List(nb_streams.toInt()) { streams?.get(it)?.pointed?.codec?.pointed }
private fun AVFormatContext.streamAt(index: Int): AVStream? =
if (index < 0) null else streams?.get(index)?.pointed
@@ -124,7 +124,7 @@ private class VideoDecoder(
dispose = ::sws_freeContext
)
private val scaledFrameSize = avpicture_get_size(avPixelFormat, windowSize.w, windowSize.h)
private val buffer: ByteArray = ByteArray(scaledFrameSize)
private val buffer: UByteArray = UByteArray(scaledFrameSize) { 0u }
private val videoQueue = Queue<VideoFrame>(100)
@@ -158,7 +158,7 @@ private class VideoDecoder(
val buffer = av_buffer_alloc(scaledFrameSize)!!
val ts = av_frame_get_best_effort_timestamp(videoFrame.ptr) *
av_q2d(videoCodecContext.time_base.readValue())
memcpy(buffer.pointed.data, scaledVideoFrame.data[0], scaledFrameSize.signExtend())
memcpy(buffer.pointed.data, scaledVideoFrame.data[0], scaledFrameSize.convert())
videoQueue.push(VideoFrame(buffer, scaledVideoFrame.linesize[0], ts))
}
}
@@ -204,11 +204,11 @@ private class AudioDecoder(
channels = output.channels
sample_rate = output.sampleRate
format = output.sampleFormat
channel_layout = output.channelLayout.signExtend()
channel_layout = output.channelLayout.convert()
}
with (audioCodecContext) {
setResampleOpt("in_channel_layout", channel_layout.narrow())
setResampleOpt("in_channel_layout", channel_layout.convert())
setResampleOpt("out_channel_layout", output.channelLayout)
setResampleOpt("in_sample_rate", sample_rate)
setResampleOpt("out_sample_rate", output.sampleRate)
@@ -255,7 +255,7 @@ private class AudioDecoder(
val buffer = av_buffer_alloc(audioFrameSize)!!
val ts = av_frame_get_best_effort_timestamp(audioFrame.ptr) *
av_q2d(audioCodecContext.time_base.readValue())
memcpy(buffer.pointed.data, data[0], audioFrameSize.signExtend())
memcpy(buffer.pointed.data, data[0], audioFrameSize.convert())
audioQueue.push(AudioFrame(buffer, 0, audioFrameSize, ts))
}
}
@@ -27,7 +27,7 @@ enum class SampleFormat {
data class AudioOutput(val sampleRate: Int, val channels: Int, val sampleFormat: SampleFormat)
private fun SampleFormat.toSDLFormat(): SDL_AudioFormat? = when (this) {
SampleFormat.S16 -> AUDIO_S16SYS.narrow()
SampleFormat.S16 -> AUDIO_S16SYS.convert()
SampleFormat.INVALID -> null
}
@@ -45,9 +45,9 @@ class SDLAudio(val player: VideoPlayer) : DisposableContainer() {
val spec = alloc<SDL_AudioSpec>().apply {
freq = audio.sampleRate
format = audioFormat
channels = audio.channels.narrow()
silence = 0
samples = 4096
channels = audio.channels.convert()
silence = 0u
samples = 4096u
userdata = threadData
callback = staticCFunction(::audioCallback)
}
@@ -89,12 +89,12 @@ private fun audioCallback(userdata: COpaquePointer?, buffer: CPointer<Uint8Var>?
val frame = decoder.nextAudioFrame(length - outPosition)
if (frame != null) {
val toCopy = minOf(length - outPosition, frame.size - frame.position)
memcpy(buffer + outPosition, frame.buffer.pointed.data + frame.position, toCopy.signExtend())
memcpy(buffer + outPosition, frame.buffer.pointed.data + frame.position, toCopy.convert())
frame.unref()
outPosition += toCopy
} else {
// println("Decoder returned nothing!")
memset(buffer + outPosition, 0, (length - outPosition).signExtend())
memset(buffer + outPosition, 0, (length - outPosition).convert())
break
}
}
@@ -81,7 +81,7 @@ class SDLRendererWindow(windowPos: Dimensions, videoSize: Dimensions) : Disposab
SDL_CreateTexture(renderer, SDL_GetWindowPixelFormat(window), 0, videoSize.w, videoSize.h),
::SDL_DestroyTexture)
private val rect = sdlDisposable("calloc(SDL_Rect)",
SDL_calloc(1, SDL_Rect.size), ::SDL_free)
SDL_calloc(1u, SDL_Rect.size.convert()), ::SDL_free)
.reinterpret<SDL_Rect>()
init {
@@ -71,7 +71,7 @@ class VideoPlayer(val requestedSize: Dimensions?) : DisposableContainer() {
}
private fun getTime(): Double {
clock_gettime(platform.posix.CLOCK_MONOTONIC, now)
clock_gettime(platform.posix.CLOCK_MONOTONIC.convert(), now)
return now.pointed.tv_sec + now.pointed.tv_nsec / 1e9
}
@@ -127,7 +127,7 @@ class VideoPlayer(val requestedSize: Dimensions?) : DisposableContainer() {
lastFrameTime += frameDuration // try to maintain perfect frame rate
// Wait for next frame, if needed
if (passedTime < frameDuration) {
usleep((1000_000 * (frameDuration - passedTime)).toInt())
usleep((1000_000 * (frameDuration - passedTime)).toInt().toUInt())
} else if (passedTime > frameDuration * 1.5){
lastFrameTime = now // we fell behind more than half frame, reset time
}
@@ -140,7 +140,7 @@ class VideoPlayer(val requestedSize: Dimensions?) : DisposableContainer() {
while (state == State.PAUSED) {
audio.pause()
input.check()
usleep(1 * 1000)
usleep(1u * 1000u)
}
audio.resume()
}
@@ -152,14 +152,14 @@ class VideoPlayer(val requestedSize: Dimensions?) : DisposableContainer() {
if (!decoder.audioVideoSynced()) {
println("Resynchronizing video with audio")
while (!decoder.audioVideoSynced() && state == State.PLAYING) {
usleep(500)
usleep(500u)
input.check()
}
}
}
} else {
// For pure sound, playback is driven by demand.
usleep(10 * 1000)
usleep(10u * 1000u)
}
}
}
+2 -1
View File
@@ -1,6 +1,7 @@
import kotlinx.cinterop.*
import platform.windows.*
fun main(args: Array<String>) {
MessageBoxW(null, "Konan говорит:\nЗДРАВСТВУЙ МИР!\n",
"Заголовок окна", MB_YESNOCANCEL or MB_ICONQUESTION)
"Заголовок окна", (MB_YESNOCANCEL or MB_ICONQUESTION).convert())
}