From 10f4743f82ade72f1b6379331faa7fb1aaafed03 Mon Sep 17 00:00:00 2001 From: Savanni D'Gerinel Date: Thu, 22 Jun 2023 22:59:45 -0400 Subject: [PATCH] Reserialize a game tree --- go-sgf/Makefile | 6 +++++ go-sgf/src/lib.rs | 62 ++++++++++++++++++++++++++++++++++++++++++----- 2 files changed, 62 insertions(+), 6 deletions(-) create mode 100644 go-sgf/Makefile diff --git a/go-sgf/Makefile b/go-sgf/Makefile new file mode 100644 index 0000000..bfcdb8e --- /dev/null +++ b/go-sgf/Makefile @@ -0,0 +1,6 @@ + +test: + cargo watch -x 'nextest run' + +test-oneshot: + cargo nextest run diff --git a/go-sgf/src/lib.rs b/go-sgf/src/lib.rs index 47f146f..2d5dd6f 100644 --- a/go-sgf/src/lib.rs +++ b/go-sgf/src/lib.rs @@ -161,12 +161,6 @@ struct Node { } */ -#[derive(Debug, PartialEq)] -pub struct Property { - ident: String, - values: Vec, -} - enum PropType { Move, Setup, @@ -193,11 +187,55 @@ struct Tree { sub_sequences: Vec, } +impl ToString for Tree { + fn to_string(&self) -> String { + let sequence = self + .sequence + .iter() + .map(|node| node.to_string()) + .collect::(); + let subsequences = self + .sub_sequences + .iter() + .map(|seq| seq.to_string()) + .collect::(); + format!("({}{})", sequence, subsequences) + } +} + #[derive(Debug, PartialEq)] struct Node { properties: Vec, } +impl ToString for Node { + fn to_string(&self) -> String { + let props = self + .properties + .iter() + .map(|prop| prop.to_string()) + .collect::(); + format!(";{}", props) + } +} + +#[derive(Debug, PartialEq)] +struct Property { + ident: String, + values: Vec, +} + +impl ToString for Property { + fn to_string(&self) -> String { + let values = self + .values + .iter() + .map(|val| format!("[{}]", val)) + .collect::(); + format!("{}{}", self.ident, values) + } +} + // note: must preserve unknown properties // note: must fix or preserve illegally formatted game-info properties // note: must correct or delete illegally foramtted properties, but display a warning @@ -475,6 +513,18 @@ Usually B plays the 3,3 invasion - see variation];W[qo];B[qp] assert_eq!(ex_tree.sub_sequences[0].sub_sequences.len(), 2); } + #[test] + fn it_can_regenerate_the_tree() { + let (_, tree1) = parse_tree(EXAMPLE_1).unwrap(); + println!("{}", tree1.to_string()); + assert_eq!( + tree1.to_string(), + "(;FF[4]C[root](;C[a];C[b](;C[c])(;C[d];C[e]))(;C[f](;C[g];C[h];C[i])(;C[j])))" + ); + let (_, tree2) = parse_tree(&tree1.to_string()).unwrap(); + assert_eq!(tree1, tree2); + } + /* fn with_examples(f: impl FnOnce(GameTree, GameTree)) { let (example_1, _) = parse_sgf(EXAMPLE_1).unwrap();