/*
Copyright 2024 Ondrej Lhotak. All rights reserved.
Permission is granted for private study use by students registered in
CS 241E in the Fall 2024 term.
The contents of this file may not be published, in whole or in part,
in print or electronic form.
The contents of this file may be included in work submitted for CS
241E assignments in Fall 2024. The contents of this file may not be
submitted, in whole or in part, for credit in any other course.
*/
package cs241e.mips
/** An object containing utility methods for writing and pattern matching sequences of bits
* using strings.
*/
object Bits {
/** Constructs a bit sequence from a string.
* Example: `Bits("01") == Seq(false, true)`
*/
def apply(bits: String): Seq[Boolean] = bits.filter(bit => bit != ' ').map{
case '0' => false
case '1' => true
case c => sys.error(s"illegal bit: $c")
}
/** Enables pattern matching of bit sequences using strings.
* Example: {{{
* (Seq(false, true) match {
* case Bits("01") => 42
* }) == 42
* }}}
*/
def unapply(bits: Seq[Boolean]): Option[String] = Some(bits.map{if(_) '1' else '0'}.mkString)
}