/
MemOutputDirectory.scala
60 lines (49 loc) · 1.75 KB
/
MemOutputDirectory.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/*
* Scala.js (https://www.scala-js.org/)
*
* Copyright EPFL.
*
* Licensed under Apache License 2.0
* (https://www.apache.org/licenses/LICENSE-2.0).
*
* See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*/
package org.scalajs.linker
import scala.collection.mutable
import scala.concurrent._
import java.io.{ByteArrayOutputStream, IOException}
import java.nio.ByteBuffer
import org.scalajs.linker.interface.OutputDirectory
import org.scalajs.linker.interface.unstable.OutputDirectoryImpl
/** OutputDirectory that simply writes to memory. */
sealed trait MemOutputDirectory extends OutputDirectory {
/** Content of the file with `name` or `None` if the file was not written. */
def content(name: String): Option[Array[Byte]]
}
object MemOutputDirectory {
def apply(): MemOutputDirectory = new Impl()
private final class Impl
extends OutputDirectoryImpl with MemOutputDirectory {
private val _content: mutable.Map[String, Array[Byte]] = mutable.Map.empty
def content(name: String): Option[Array[Byte]] = synchronized {
_content.get(name)
}
def writeFull(name: String, buf: ByteBuffer)(
implicit ec: ExecutionContext): Future[Unit] = synchronized {
val c = new Array[Byte](buf.remaining())
buf.get(c)
_content(name) = c
Future.successful(())
}
def listFiles()(implicit ec: ExecutionContext): Future[List[String]] = synchronized {
Future.successful(_content.keys.toList)
}
def delete(name: String)(implicit ec: ExecutionContext): Future[Unit] = synchronized {
if (_content.remove(name).isDefined)
Future.successful(())
else
Future.failed(new IOException(s"file $name does not exist"))
}
}
}