Skip to content

Commit

Permalink
Fix Instance
Browse files Browse the repository at this point in the history
  • Loading branch information
05nelsonm committed Feb 12, 2024
1 parent ce5aa7b commit 3b895e9
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,22 @@
**/
package io.matthewnelson.kmp.process.internal

internal class Instance<T: Any?> internal constructor(
private val create: () -> T,
) {
internal class Instance<T: Any?> internal constructor(create: () -> T) {

private var create: (() -> T)? = create
private val instance = SynchronizedSet<T>()

internal fun getOrCreate(): T = instance.withLock {
firstOrNull() ?: create()
.also { add(it) }
if (isEmpty()) {
create?.let { function ->
function().also { element ->
create = null
add(element)
}
} ?: throw IllegalStateException()
} else {
first()
}
}

internal fun getOrNull(): T? = instance.withLock { firstOrNull() }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -301,7 +301,7 @@ abstract class ProcessBaseTest {
println(stdout.toString())
println(stderr.toString())

p2.waitForAsync(::delay)
withContext(Dispatchers.Default) { delay(250.milliseconds) }

assertEquals(0, p2.stdoutFeedsSize())
assertEquals(0, p2.stderrFeedsSize())
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/*
* Copyright (c) 2024 Matthew Nelson
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
package io.matthewnelson.kmp.process.internal

import kotlin.test.Test
import kotlin.test.assertNotNull
import kotlin.test.assertNull

class InstanceUnitTest {

@Test
fun givenNullableType_whenGetOrCreate_thenReturnsAsExpected() {
val i = Instance<Any?> { Any() }

assertNull(i.getOrNull())
assertNotNull(i.getOrCreate())
assertNotNull(i.getOrNull())
}
}

0 comments on commit 3b895e9

Please sign in to comment.