Skip to content

Commit

Permalink
Rust: generate FromStrRadix::from_str_radix for non-base-10 .to_i con…
Browse files Browse the repository at this point in the history
…versions

FromStrRadix is a custom trait from not yet exist Rust runtime library
  • Loading branch information
Mingun committed Apr 16, 2024
1 parent 239c54e commit ffca8d7
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -1084,7 +1084,7 @@ class TranslatorSpec extends AnyFunSpec {
PHPCompiler -> new PHPTranslator(tp, RuntimeConfig()),
PythonCompiler -> new PythonTranslator(tp, new ImportList(), RuntimeConfig()),
RubyCompiler -> new RubyTranslator(tp),
RustCompiler -> new RustTranslator(tp, RuntimeConfig()),
RustCompiler -> new RustTranslator(tp, new ImportList()),
)

langs.foreach { case (langObj, tr) =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ class RustCompiler(typeProvider: ClassTypeProvider, config: RuntimeConfig)

override def innerEnums = false

override val translator: RustTranslator = new RustTranslator(typeProvider, config)
override val translator: RustTranslator = new RustTranslator(typeProvider, importList)

override def universalFooter: Unit = {
out.dec
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ import io.kaitai.struct.exprlang.Ast
import io.kaitai.struct.exprlang.Ast.expr
import io.kaitai.struct.format.{EnumSpec, Identifier}
import io.kaitai.struct.languages.RustCompiler
import io.kaitai.struct.{RuntimeConfig, Utils}
import io.kaitai.struct.{ImportList, Utils}

class RustTranslator(provider: TypeProvider, config: RuntimeConfig) extends BaseTranslator(provider) {
class RustTranslator(provider: TypeProvider, importList: ImportList) extends BaseTranslator(provider) {
override def doByteArrayLiteral(arr: Seq[Byte]): String =
"vec!([" + arr.map((x) =>
"%0#2x".format(x & 0xff)
Expand Down Expand Up @@ -61,13 +61,17 @@ class RustTranslator(provider: TypeProvider, config: RuntimeConfig) extends Base
override def strConcat(left: expr, right: expr, extPrec: Int) =
"format!(\"{}{}\", " + translate(left) + ", " + translate(right) + ")"

override def strToInt(s: expr, base: expr): String =
translate(base) match {
// TODO: do not generate .unwrap(), generate ? instead
override def strToInt(s: expr, base: expr): String = {
val baseStr = translate(base)
baseStr match {
case "10" =>
s"${translate(s)}.parse().unwrap()"
case _ =>
"panic!(\"Converting from string to int in base {} is unimplemented\", " + translate(base) + ")"
importList.add("kaitai_struct::FromStrRadix")
s"FromStrRadix::from_str_radix(${translate(s)}, $baseStr).unwrap()"
}
}

override def enumToInt(v: expr, et: EnumType): String =
translate(v)
Expand Down

0 comments on commit ffca8d7

Please sign in to comment.