Skip to content

Commit

Permalink
Merge pull request #22 from natsukagami/formatting
Browse files Browse the repository at this point in the history
Enable formatting with `scalafmt`
  • Loading branch information
natsukagami authored Dec 8, 2023
2 parents fbcdccf + e7833da commit 1137ee0
Show file tree
Hide file tree
Showing 28 changed files with 580 additions and 547 deletions.
26 changes: 26 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,32 @@ on:
- main
pull_request:
jobs:
formatting-check:
strategy:
fail-fast: false
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
submodules: recursive
fetch-depth: 0
- uses: coursier/cache-action@v6
- uses: actions/setup-java@v3
with:
distribution: temurin
java-version: 21
- name: Get submodule status hash
id: get-submodules
run: echo "submodules=$(git submodule status | sha256sum | awk '{print $1}')" >> $GITHUB_OUTPUT
- uses: actions/cache@v3
with:
path: |
./dependencies/**/target
key: ${{ runner.os }}-${{ steps.get-submodules.outputs.submodules }}-scala-native-only
- name: Build dependencies
run: ./dependencies/publish-deps.sh --scala-native-only
- name: Test Formatting
run: sbt scalafmtCheckAll
test-jvm:
strategy:
fail-fast: false
Expand Down
3 changes: 3 additions & 0 deletions .scalafmt.conf
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
version = 3.7.3
runner.dialect = scala3
maxColumn = 120
4 changes: 2 additions & 2 deletions dependencies/publish-deps.sh
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@ set -e

cd "$(dirname "${BASH_SOURCE[0]}")" # change to this directory

cd scala-native && sbt 'publish-local-dev 3' && cd ..
cd scala-native && sbt 'publish-local-dev 2.12' && cd ..

if test "$1" != "--scala-native-only"; then
cd scala-native && sbt '++3.1.2 publishLocal' && cd ..
cd scala-native && sbt '++3.3.1 publishLocal; ++3.1.2 publishLocal' && cd ..
cd munit && sbt "++3.1.2 munitNative/publishLocal" && cd ..
fi

49 changes: 31 additions & 18 deletions jvm/src/main/scala/PosixLikeIO/PIO.scala
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import scala.Tuple.Union
import scala.concurrent.ExecutionContext
import scala.util.{Failure, Success, Try}


class File(val path: String) {
private var channel: Option[AsynchronousFileChannel] = None

Expand All @@ -22,8 +21,7 @@ class File(val path: String) {
def open(options: StandardOpenOption*): File =
assert(channel.isEmpty)
val options1 = if (options.isEmpty) Seq(StandardOpenOption.READ) else options
channel = Some(
AsynchronousFileChannel.open(Path.of(path), options1*))
channel = Some(AsynchronousFileChannel.open(Path.of(path), options1*))
this

def close(): Unit =
Expand All @@ -35,10 +33,15 @@ class File(val path: String) {
assert(channel.isDefined)

val p = Promise[Int]()
channel.get.read(buffer, 0, buffer, new CompletionHandler[Integer, ByteBuffer] {
override def completed(result: Integer, attachment: ByteBuffer): Unit = p.complete(Success(result))
override def failed(e: Throwable, attachment: ByteBuffer): Unit = p.complete(Failure(e))
})
channel.get.read(
buffer,
0,
buffer,
new CompletionHandler[Integer, ByteBuffer] {
override def completed(result: Integer, attachment: ByteBuffer): Unit = p.complete(Success(result))
override def failed(e: Throwable, attachment: ByteBuffer): Unit = p.complete(Failure(e))
}
)
p.future

def readString(size: Int, charset: Charset = StandardCharsets.UTF_8): Future[String] =
Expand All @@ -47,24 +50,33 @@ class File(val path: String) {

val buffer = ByteBuffer.allocate(size)
val p = Promise[String]()
channel.get.read(buffer, 0, buffer, new CompletionHandler[Integer, ByteBuffer] {
override def completed(result: Integer, attachment: ByteBuffer): Unit =
p.complete(Success(charset.decode(attachment.slice(0, result)).toString()))
override def failed(e: Throwable, attachment: ByteBuffer): Unit = p.complete(Failure(e))
})
channel.get.read(
buffer,
0,
buffer,
new CompletionHandler[Integer, ByteBuffer] {
override def completed(result: Integer, attachment: ByteBuffer): Unit =
p.complete(Success(charset.decode(attachment.slice(0, result)).toString()))
override def failed(e: Throwable, attachment: ByteBuffer): Unit = p.complete(Failure(e))
}
)
p.future

def write(buffer: ByteBuffer): Future[Int] =
assert(channel.isDefined)

val p = Promise[Int]()
channel.get.write(buffer, 0, buffer, new CompletionHandler[Integer, ByteBuffer] {
override def completed(result: Integer, attachment: ByteBuffer): Unit = p.complete(Success(result))
override def failed(e: Throwable, attachment: ByteBuffer): Unit = p.complete(Failure(e))
})
channel.get.write(
buffer,
0,
buffer,
new CompletionHandler[Integer, ByteBuffer] {
override def completed(result: Integer, attachment: ByteBuffer): Unit = p.complete(Success(result))
override def failed(e: Throwable, attachment: ByteBuffer): Unit = p.complete(Failure(e))
}
)
p.future


def writeString(s: String, charset: Charset = StandardCharsets.UTF_8): Future[Int] =
write(ByteBuffer.wrap(s.getBytes(charset)))

Expand Down Expand Up @@ -100,7 +112,8 @@ class SocketUDP() {

Async.blocking:
Future:
val packet: DatagramPacket = new DatagramPacket(data.array(), data.limit(), InetAddress.getByName(address), port)
val packet: DatagramPacket =
new DatagramPacket(data.array(), data.limit(), InetAddress.getByName(address), port)
socket.get.send(packet)

def receive(): Future[DatagramPacket] =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import java.nio.charset.StandardCharsets
import java.nio.file.StandardOpenOption
import scala.concurrent.ExecutionContext


@main def readAndWriteFile(): Unit =
given ExecutionContext = ExecutionContext.global
Async.blocking:
Expand Down
20 changes: 9 additions & 11 deletions jvm/src/main/scala/PosixLikeIO/examples/readWholeFile.scala
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,16 @@ import java.nio.charset.StandardCharsets
import java.nio.file.StandardOpenOption
import scala.concurrent.ExecutionContext


@main def readWholeFile(): Unit =
given ExecutionContext = ExecutionContext.global
Async.blocking:
PIOHelper.withFile("/home/julian/Desktop/x.txt", StandardOpenOption.READ): f =>
val b = ByteBuffer.allocate(1024)
val retCode = f.read(b).result.get
assert(retCode >= 0)
val s = StandardCharsets.UTF_8.decode(b.slice(0, retCode)).toString()
println("Read size with read(): " + retCode.toString())
println("Data: " + s)

PIOHelper.withFile("/home/julian/Desktop/x.txt", StandardOpenOption.READ): f =>
val b = ByteBuffer.allocate(1024)
val retCode = f.read(b).result.get
assert(retCode >= 0)
val s = StandardCharsets.UTF_8.decode(b.slice(0, retCode)).toString()
println("Read size with read(): " + retCode.toString())
println("Data: " + s)

println("Read with readString():")
println(Async.await(f.readString(1000)).get)
println("Read with readString():")
println(Async.await(f.readString(1000)).get)
15 changes: 7 additions & 8 deletions jvm/src/main/scala/async/JvmAsyncOperations.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,11 @@ package gears.async

object JvmAsyncOperations extends AsyncOperations:

private def jvmInterruptible[T](fn: => T)(using Async): T =
val th = Thread.currentThread()
cancellationScope(() => th.interrupt()):
try fn
catch
case _: InterruptedException => throw new CancellationException()
private def jvmInterruptible[T](fn: => T)(using Async): T =
val th = Thread.currentThread()
cancellationScope(() => th.interrupt()):
try fn
catch case _: InterruptedException => throw new CancellationException()

override def sleep(millis: Long)(using Async): Unit =
jvmInterruptible(Thread.sleep(millis))
override def sleep(millis: Long)(using Async): Unit =
jvmInterruptible(Thread.sleep(millis))
25 changes: 10 additions & 15 deletions jvm/src/main/scala/async/VThreadSupport.scala
Original file line number Diff line number Diff line change
Expand Up @@ -32,23 +32,21 @@ object VThreadSupport extends AsyncSupport:
try
result = Some(data)
cond.signalAll()
finally
lock.unlock()
finally lock.unlock()

private[VThreadSupport] def waitResult(): R =
lock.lock()
try
while result.isEmpty do
cond.await()
while result.isEmpty do cond.await()
result.get
finally
lock.unlock()
finally lock.unlock()

override opaque type Label[R] = VThreadLabel[R]

// outside boundary: waiting on label
// inside boundary: waiting on suspension
private final class VThreadSuspension[-T, +R](using private[VThreadSupport] val l: Label[R] @uncheckedVariance) extends gears.async.Suspension[T, R]:
private final class VThreadSuspension[-T, +R](using private[VThreadSupport] val l: Label[R] @uncheckedVariance)
extends gears.async.Suspension[T, R]:
private var nextInput: Option[T] = None
private val lock = ReentrantLock()
private val cond = lock.newCondition()
Expand All @@ -58,18 +56,15 @@ object VThreadSupport extends AsyncSupport:
try
nextInput = Some(data)
cond.signalAll()
finally
lock.unlock()
finally lock.unlock()

// variance is safe because the only caller created the object
private[VThreadSupport] def waitInput(): T @uncheckedVariance =
lock.lock()
try
while nextInput.isEmpty do
cond.await()
while nextInput.isEmpty do cond.await()
nextInput.get
finally
lock.unlock()
finally lock.unlock()

// normal resume only tells other thread to run again -> resumeAsync may redirect here
override def resume(arg: T): R =
Expand All @@ -88,8 +83,8 @@ object VThreadSupport extends AsyncSupport:
label.waitResult()

override private[async] def resumeAsync[T, R](suspension: Suspension[T, R])(arg: T)(using Scheduler): Unit =
suspension.l.clearResult()
suspension.setInput(arg)
suspension.l.clearResult()
suspension.setInput(arg)

override def scheduleBoundary(body: (Label[Unit]) ?=> Unit)(using Scheduler): Unit =
Thread.startVirtualThread: () =>
Expand Down
Loading

0 comments on commit 1137ee0

Please sign in to comment.