Skip to content

Commit

Permalink
Added readOption and readOrElse to YamlSequence
Browse files Browse the repository at this point in the history
  • Loading branch information
losizm committed Apr 21, 2024
1 parent af6fb37 commit 88e2371
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
28 changes: 28 additions & 0 deletions src/main/scala/shampoo/yaml/YamlNode.scala
Expand Up @@ -509,6 +509,34 @@ sealed trait YamlSequence extends YamlCollection:
case YamlNull => throw NullPointerException()
case node => node.as[T]

/**
* Optionally reads constructed data.
*
* @param index sequence index
* @param constructor data constructor
*
* @return `Some` constructed data, or `None` if node is null
*
* @throws java.lang.IndexOutOfBoundsException if index is out of bounds
*/
def readOption[T](index: Int)(using constructor: YamlConstructor[T]): Option[T] =
apply(index) match
case YamlNull => None
case node => Some(node.as[T])

/**
* Reads constructed data or returns default value.
*
* @param index sequence index
* @param constructor data constructor
*
* @return constructed data, or default value if node is null
*
* @throws java.lang.IndexOutOfBoundsException if index is out of bounds
*/
def readOrElse[T](index: Int, default: => T)(using constructor: YamlConstructor[T]): T =
readOption(index).getOrElse(default)

/**
* Assumes either YAML mapping or YAML sequence.
*
Expand Down
27 changes: 27 additions & 0 deletions src/test/scala/shampoo/yaml/YamlSpec.scala
Expand Up @@ -124,6 +124,33 @@ class YamlSpec extends org.scalatest.flatspec.AnyFlatSpec:
verify(copy)
}

it should "read optional sequence values" in {
val yaml = Yaml.seq(
YamlString("abc"),
YamlNumber(123),
YamlBoolean(true),
YamlNull
)

assert { yaml.read[String](0) == "abc" }
assert { yaml.readOption[String](0) == Some("abc") }
assert { yaml.readOrElse(0, "def") == "abc" }

assert { yaml.read[Int](1) == 123 }
assert { yaml.readOption[Int](1) == Some(123) }
assert { yaml.readOrElse(1, 456) == 123 }

assert { yaml.read[Boolean](2) == true }
assert { yaml.readOption[Boolean](2) == Some(true) }
assert { yaml.readOrElse(2, false) }

assert { yaml(3) == YamlNull }

assertThrows[NullPointerException] { yaml.read[String](3) }
assert { yaml.readOption[String](3) == None }
assert { yaml.readOrElse(3, "def") == "def" }
}

private def verify(yaml: YamlMapping): Unit =
assert(yaml.nonEmpty)
assert(yaml.size == 7)
Expand Down

0 comments on commit 88e2371

Please sign in to comment.