Roman Elizarov | a7db8ec | 2017-12-21 22:45:12 +0300 | [diff] [blame] | 1 | /* |
| 2 | * Copyright 2016-2017 JetBrains s.r.o. |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
Roman Elizarov | 45c1a73 | 2017-12-21 11:53:31 +0300 | [diff] [blame] | 17 | package kotlinx.coroutines.experimental.internal |
| 18 | |
| 19 | import kotlin.test.Test |
| 20 | import kotlin.test.assertEquals |
| 21 | import kotlin.test.assertFalse |
| 22 | import kotlin.test.assertTrue |
| 23 | |
| 24 | class LinkedListTest { |
| 25 | data class IntNode(val i: Int) : LinkedListNode() |
| 26 | |
| 27 | @Test |
| 28 | fun testSimpleAddLastRemove() { |
| 29 | val list = LinkedListHead() |
| 30 | assertContents(list) |
| 31 | val n1 = IntNode(1).apply { list.addLast(this) } |
| 32 | assertContents(list, 1) |
| 33 | val n2 = IntNode(2).apply { list.addLast(this) } |
| 34 | assertContents(list, 1, 2) |
| 35 | val n3 = IntNode(3).apply { list.addLast(this) } |
| 36 | assertContents(list, 1, 2, 3) |
| 37 | val n4 = IntNode(4).apply { list.addLast(this) } |
| 38 | assertContents(list, 1, 2, 3, 4) |
| 39 | assertTrue(n1.remove()) |
| 40 | assertContents(list, 2, 3, 4) |
| 41 | assertTrue(n3.remove()) |
| 42 | assertContents(list, 2, 4) |
| 43 | assertTrue(n4.remove()) |
| 44 | assertContents(list, 2) |
| 45 | assertTrue(n2.remove()) |
| 46 | assertFalse(n2.remove()) |
| 47 | assertContents(list) |
| 48 | } |
| 49 | |
| 50 | private fun assertContents(list: LinkedListHead, vararg expected: Int) { |
| 51 | val n = expected.size |
| 52 | val actual = IntArray(n) |
| 53 | var index = 0 |
| 54 | list.forEach<IntNode> { actual[index++] = it.i } |
| 55 | assertEquals(n, index) |
| 56 | for (i in 0 until n) assertEquals(expected[i], actual[i], "item i") |
| 57 | assertEquals(expected.isEmpty(), list.isEmpty) |
| 58 | } |
| 59 | } |