Created
February 24, 2018 02:12
-
-
Save Exerosis/193482e56dd3bd9b481ddd14fc307305 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| interface Buffer { | |
| fun clear(): Buffer | |
| fun flip(): Buffer | |
| fun index(): Long | |
| //Read a number of bits(or 8) from a value as a Number at the current index. | |
| fun <Type : Number> next(bits: Number = 8): Type | |
| //Write a number of bits(or 8) from a value into the buffer at the current index. | |
| fun next(value: Long, bits: Number = 8): Buffer | |
| } | |
| class Address(val hostname: String, val port: Short) | |
| //Basic send and receive, semi compatible with any protocol. | |
| expect class Socket(local: Address) { | |
| suspend fun receive(packet: Buffer): Address | |
| suspend fun send(packet: Buffer, to: Address) | |
| fun isOpen(): Boolean | |
| } | |
| class TestSocket(private val input: Buffer, | |
| private val output: Buffer, | |
| local: Address) { | |
| private val socket = Socket(local) | |
| private val outputLock = Mutex() | |
| private val inputLock = Mutex() | |
| fun receive(receiver: Buffer.(Address) -> Unit) = launch { | |
| inputLock.withLock { | |
| val address = socket.receive(input.clear()) | |
| receiver(input.flip(), address) | |
| } | |
| } | |
| //Receive a packet from an address. | |
| fun receive(from: Address, receiver: Buffer.() -> Unit) = launch { | |
| //FIXME obviously restructure this class to handle explicit receives. | |
| //As well as full implementation of coroutines. | |
| } | |
| //Send a packet to an address. | |
| fun send(to: Address, sender: Buffer.() -> Unit) = launch { | |
| outputLock.withLock { | |
| val address = sender(output.clear()) | |
| socket.send(output.flip(), to) | |
| } | |
| } | |
| //Receive a packet from an address, then send a result to the same address. | |
| fun respond(from: Address, request: Buffer.() -> Buffer.() -> Unit) { | |
| receive(from) { | |
| send(from, request(this)) | |
| } | |
| } | |
| //Send a packet to an address, then receive a packet from the same address. | |
| fun request(to: Address, request: Buffer.() -> Buffer.() -> Unit) { | |
| send(to) { | |
| receive(to, request(this)) | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment