blob: 44ddf471d7982ddcbb2ced2494c05155cbb44963 [file] [log] [blame]
Vsevolod Tolstopyatov4ddfc912018-07-12 18:36:02 +03001/*
2 * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
3 */
4
Roman Elizarov0950dfa2018-07-13 10:33:25 +03005package kotlinx.coroutines.internal
Vsevolod Tolstopyatov4ddfc912018-07-12 18:36:02 +03006
7import kotlin.test.Test
8import kotlin.test.assertEquals
9import kotlin.test.assertFalse
10import kotlin.test.assertTrue
11
12class LinkedListTest {
Steve Elliottca095be2022-07-25 14:26:10 +000013 data class IntNode(val i: Int) : LockFreeLinkedListNode()
Vsevolod Tolstopyatov4ddfc912018-07-12 18:36:02 +030014
15 @Test
16 fun testSimpleAddLastRemove() {
Steve Elliottca095be2022-07-25 14:26:10 +000017 val list = LockFreeLinkedListHead()
Vsevolod Tolstopyatov4ddfc912018-07-12 18:36:02 +030018 assertContents(list)
19 val n1 = IntNode(1).apply { list.addLast(this) }
20 assertContents(list, 1)
21 val n2 = IntNode(2).apply { list.addLast(this) }
22 assertContents(list, 1, 2)
23 val n3 = IntNode(3).apply { list.addLast(this) }
24 assertContents(list, 1, 2, 3)
25 val n4 = IntNode(4).apply { list.addLast(this) }
26 assertContents(list, 1, 2, 3, 4)
27 assertTrue(n1.remove())
28 assertContents(list, 2, 3, 4)
29 assertTrue(n3.remove())
30 assertContents(list, 2, 4)
31 assertTrue(n4.remove())
32 assertContents(list, 2)
33 assertTrue(n2.remove())
34 assertFalse(n2.remove())
35 assertContents(list)
36 }
37
Steve Elliottca095be2022-07-25 14:26:10 +000038 private fun assertContents(list: LockFreeLinkedListHead, vararg expected: Int) {
Vsevolod Tolstopyatov4ddfc912018-07-12 18:36:02 +030039 val n = expected.size
40 val actual = IntArray(n)
41 var index = 0
42 list.forEach<IntNode> { actual[index++] = it.i }
43 assertEquals(n, index)
44 for (i in 0 until n) assertEquals(expected[i], actual[i], "item i")
45 assertEquals(expected.isEmpty(), list.isEmpty)
46 }
47}