Skip to content

Commit

Permalink
fix memory alignment check (#1742)
Browse files Browse the repository at this point in the history
* fix memory alignment check

* added test for memory alignment
  • Loading branch information
Louis9902 authored Jun 4, 2020
1 parent c2fb182 commit d97c19d
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -533,9 +533,9 @@ internal inline fun requireRange(offset: Long, length: Long, size: Long, name: S
}
}

private inline fun Memory.isAlignedShort(offset: Long) = (pointer.toLong() + offset) and 1L == 0L
private inline fun Memory.isAlignedInt(offset: Long) = (pointer.toLong() + offset) and 11L == 0L
private inline fun Memory.isAlignedLong(offset: Long) = (pointer.toLong() + offset) and 111L == 0L
internal inline fun Memory.isAlignedShort(offset: Long) = (pointer.toLong() + offset) and 0b1 == 0L
internal inline fun Memory.isAlignedInt(offset: Long) = (pointer.toLong() + offset) and 0b11 == 0L
internal inline fun Memory.isAlignedLong(offset: Long) = (pointer.toLong() + offset) and 0b111 == 0L


private fun copy(
Expand Down
70 changes: 70 additions & 0 deletions ktor-io/posix/test/io/ktor/utils/io/tests/MemoryTest.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/*
* Copyright 2014-2020 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/

package io.ktor.utils.io.tests

import io.ktor.utils.io.bits.*
import kotlinx.cinterop.*
import kotlin.test.*

class MemoryTest {

private lateinit var mem: Memory

@BeforeTest
fun setup() {
mem = DefaultAllocator.alloc(1024)
}

@AfterTest
fun cleanup() {
DefaultAllocator.free(mem)
}

@Test
fun testShortAlign() {
assertTrue(mem.isAlignedShort(0))
assertFalse(mem.isAlignedShort(1))

assertTrue(mem.isAlignedShort(510))
assertFalse(mem.isAlignedShort(511))
assertTrue(mem.isAlignedShort(512))
}

@Test
fun testIntAlign() {
assertTrue(mem.isAlignedInt(0))
assertFalse(mem.isAlignedInt(1))
assertFalse(mem.isAlignedInt(2))
assertFalse(mem.isAlignedInt(3))

assertTrue(mem.isAlignedInt(508))
assertFalse(mem.isAlignedInt(509))
assertFalse(mem.isAlignedInt(510))
assertFalse(mem.isAlignedInt(511))
assertTrue(mem.isAlignedInt(512))
}

@Test
fun testLongAlign() {
assertTrue(mem.isAlignedLong(0))
assertFalse(mem.isAlignedLong(1))
assertFalse(mem.isAlignedLong(2))
assertFalse(mem.isAlignedLong(3))
assertFalse(mem.isAlignedLong(4))
assertFalse(mem.isAlignedLong(6))
assertFalse(mem.isAlignedLong(6))
assertFalse(mem.isAlignedLong(7))

assertTrue(mem.isAlignedLong(504))
assertFalse(mem.isAlignedLong(505))
assertFalse(mem.isAlignedLong(506))
assertFalse(mem.isAlignedLong(507))
assertFalse(mem.isAlignedLong(508))
assertFalse(mem.isAlignedLong(509))
assertFalse(mem.isAlignedLong(510))
assertFalse(mem.isAlignedLong(511))
assertTrue(mem.isAlignedLong(512))
}
}

0 comments on commit d97c19d

Please sign in to comment.