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
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
use std::collections::HashMap;
use std::collections::hash_map::Iter;
use std::ops::{Index, IndexMut, Deref, DerefMut};
use std::fmt;
use regex::Regex;
use parser::*;

pub type SgfPoint      = String;
pub type SgfColor      = char;
pub type SgfNumber     = i32;
pub type SgfReal       = f32;
pub type SgfDouble     = char;
pub type SgfText       = String;
pub type SgfSimpleText = String;

#[derive(Debug)]
pub enum SgfError {
    NoProperties,
    EmptyProperty,
    ParseError,
}

/// SGF collection
#[derive(Debug)]
pub struct SgfCollection(Vec<SgfNode>);

impl SgfCollection {
    /// Parses a SGF string and returns a SgfCollection.
    ///
    /// # Example
    ///
    /// ```
    /// use sgf::*;
    ///
    /// let c = SgfCollection::from_sgf("(;CA[UTF-8]FF[4])");
    /// ```
    ///
    pub fn from_sgf(sgf_str: &str) -> ParseResult<SgfCollection> {
        collection(sgf_str)
    }

    pub fn new(games: Vec<SgfNode>) -> SgfCollection {
        SgfCollection(games)
    }
}

impl Deref for SgfCollection {
    type Target = [SgfNode];

    fn deref(&self) -> &[SgfNode] {
        &self.0
    }
}

impl DerefMut for SgfCollection {
    fn deref_mut(&mut self) -> &mut [SgfNode] {
        &mut self.0
    }
}

impl Index<usize> for SgfCollection {
    type Output = SgfNode;

    #[inline]
    fn index<'a>(&'a self, index: usize) -> &'a Self::Output {
        &(**self)[index]
    }
}

impl IndexMut<usize> for SgfCollection {
    #[inline]
    fn index_mut<'a>(&mut self, index: usize) -> &mut Self::Output {
        &mut (**self)[index]
    }
}

impl fmt::Display for SgfCollection {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.0.iter().fold(Ok(()), |acc, item|
            acc.and(write!(f, "({})", item))
        )
    }
}

#[cfg(test)]
mod test_sgf_collection {
    use sgf_node::*;
    #[test]
    fn test_from_sgf1() {
        let result = SgfCollection::from_sgf("(;CA[UTF-8]FF[4])");
        assert!(result.is_ok());
    }

    #[test]
    fn test_from_sgf2() {
        let node = &SgfCollection::from_sgf("(;FF[4]C[root](;C[a];C[b](;C[c])
            (;C[d];C[e]))
            (;C[f](;C[g];C[h];C[i])
            (;C[j])))").unwrap()[0];
        assert!(node.children.len() == 2 && node.children[0].children[0].children.len() == 2);
    }

    #[test]
    fn test_from_sgf_long_propid() {
        let result = SgfCollection::from_sgf("(;CA[UTF-8]LONGNAME[])");
        assert!(result.is_ok());
    }

    #[test]
    fn test_fmt() {
        let sgf = "(;FF[4];C[a];C[b](;C[c])(;C[d];C[e])(;C[f](;C[g];C[h];C[i])(;C[j])))";
        let collection = SgfCollection::from_sgf(sgf).unwrap();
        let string = format!("{}", collection);
        assert_eq!(&string, sgf);
    }

    #[test]
    fn test_index() {
        let sgf = "(;FF[4]GC[game1])(;FF[4]GC[game2])";
        let collection = SgfCollection::from_sgf(sgf).unwrap();
        assert_eq!(collection[1].get_simple_text("GC").unwrap(), "game2".to_string());
    }
}

/// SGF node with children. It means that a node also represents game tree.
/// Access the field 'children' directly to traverse in its tree.
/// To access SGF properties of the node, use various accessors below.
pub struct SgfNode {
    properties: HashMap<String, Vec<String>>,
    pub children: Vec<SgfNode>,
}

impl fmt::Debug for SgfNode {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut result = write!(f, "{{\n");
        for (key, value) in self.properties.iter() {
            let vstr = if value.len() == 1 {
                value[0].clone()
            } else {
                value.iter().map(|e| format!("[{}]", e)).fold("".to_string(), |acc, i| acc + &i)
            };
            result = result.and(write!(f, "    {}: {}\n", key, vstr));
        }
        result.and(write!(f, "}}"))
    }
}

impl fmt::Display for SgfNode {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut result = write!(f, ";");
        for (key, value) in self.properties.iter() {
            result = result.and(write!(f, "{}", key));
            for v in value {
                result = result.and(write!(f, "[{}]", v));
            }
        }
        if self.children.len() == 1 {
            result = result.and(write!(f, "{}", self.children[0]));
        } else {
            for child in self.children.iter() {
                result = result.and(write!(f, "({})", child));
            }
        }
        result
    }
}

#[test]
#[should_panic]
fn test_debug_fmt() {
    let mut hash = HashMap::new();
    hash.insert("GC".to_string(), vec!["test".to_string()]);
    hash.insert("FF".to_string(), vec!["4".to_string()]);

    let n = SgfNode::new(hash);
    println!("{:?}", n);
    assert!(false)
}

impl SgfNode {
    /// Constructor.
    /// Returns an SgfNode with given propertes.
    /// Properties should be stored in a HashMap in String name and a vector of String value.
    pub fn new(properties: HashMap<String, Vec<String>>) -> SgfNode {
        SgfNode {
            properties: properties,
            children: Vec::new(),
        }
    }

    /// Returns a mutable reference of a leaf node in main line
    /// This is for the parser.
    pub fn leaf_mut(&mut self) -> &mut SgfNode {
        if self.children.len() == 0 {
            self
        } else {
            self.children[0].leaf_mut()
        }
    }

    fn get_property(&self, id: &str) -> Result<&Vec<String>, SgfError> {
        self.properties.get(id).ok_or(SgfError::NoProperties)
    }

    fn set_property(&mut self, id: &str, value: Vec<String>) -> &mut Self {
        self.properties.remove(id);
        self.properties.insert(id.to_string(), value);
        self
    }

    /// Returns an iterator of its properties.
    pub fn iter(&self) -> Iter<String, Vec<String>> {
        self.properties.iter()
    }

    /// Returns a Result of id's value as SgfPoint.
    pub fn get_point(&self, id: &str) -> Result<SgfPoint, SgfError> {
        self.get_property(id).map(|v| v[0].clone())
    }

    /// Sets an SgfpPoint value to property id.
    pub fn set_point(&mut self, id: &str, value: SgfPoint) -> &mut Self {
        self.set_property(id, vec![value.to_string()]) // to_string is redundant but looks like consistent.
    }

    /// Returns a Result of id's value as SgfNumber.
    pub fn get_number(&self, id: &str) -> Result<SgfNumber, SgfError> {
        self.get_property(id).and_then(|v| v[0].parse::<i32>().map_err(|_| SgfError::ParseError))
    }

    /// Sets an SgfpNumber value to property id.
    pub fn set_number(&mut self, id: &str, value: SgfNumber) -> &mut Self {
        self.set_property(id, vec![value.to_string()])
    }

    /// Returns a Result of id's value as a vector of SgfPoint.
    pub fn get_points(&self, id: &str) -> Result<Vec<SgfPoint>, SgfError> {
        self.properties.get(id).cloned().ok_or(SgfError::NoProperties)
    }

    /// Sets an SgfPoint vector to property id.
    pub fn set_points(&mut self, id: &str, value: Vec<SgfPoint>) -> &mut Self {
        self.set_property(id, value)
    }

    /// Returns a Result of id's value as SgfColor.
    pub fn get_color(&self, id: &str) -> Result<SgfColor, SgfError> {
        self.get_property(id).and_then(|v| v[0].chars().next().ok_or(SgfError::EmptyProperty))
    }

    /// Sets an SgfColor to property id.
    pub fn set_color(&mut self, id: &str, value: SgfColor) -> &mut Self {
        self.set_property(id, vec![value.to_string()])
    }

    /// Returns a Result of id's value as SgfDouble.
    pub fn get_double(&self, id: &str) -> Result<SgfDouble, SgfError> {
        self.get_property(id).and_then(|v| v[0].chars().next().ok_or(SgfError::EmptyProperty))
    }

    /// Sets an SgfDouble to property id.
    pub fn set_double(&mut self, id: &str, value: SgfDouble) -> &mut Self {
        self.set_property(id, vec![value.to_string()])
    }

    /// Returns a Result of id's value as SgfText.
    pub fn get_text(&self, id: &str) -> Result<SgfText, SgfError> {
        self.get_property(id).map(|v| decode_text(&v[0]))
    }

    /// Sets an SgfText to property id.
    pub fn set_text(&mut self, id: &str, value: String) -> &mut Self {
        self.set_property(id, vec![encode_text(&value)])
    }

    /// Returns a Result of id's value as SgfSimpleText.
    pub fn get_simple_text(&self, id: &str) -> Result<SgfSimpleText, SgfError> {
        self.get_property(id).map(|v| decode_simple_text(&v[0]))
    }

    /// Sets an SgfSimpleText to property id.
    pub fn set_simple_text(&mut self, id: &str, value: String) -> &mut Self {
        self.set_property(id, vec![encode_text(&value)])
    }

    /// Returns a Result of id's value as SgfReal.
    pub fn get_real(&self, id: &str) -> Result<SgfReal, SgfError> {
        self.get_property(id).and_then(|v| v[0].parse::<f32>().map_err(|_| SgfError::ParseError))
    }

    /// Sets an SgfReal to property id.
    pub fn set_real(&mut self, id: &str, value: SgfReal) -> &mut Self {
        self.set_property(id, vec![value.to_string()])
    }

    /// Returns a Result of id's value as Compose of SgfPoints.
    pub fn get_point_point(&self, id: &str) -> Result<(SgfPoint, SgfPoint), SgfError> {
        self.get_property(id).and_then(|v| {
            let mut compose = v[0].splitn(2, ":");
            compose.next().ok_or(SgfError::EmptyProperty).and_then(|f|
                compose.next().ok_or(SgfError::EmptyProperty).map(|s| (f.to_string(), s.to_string())))
        })
    }

    /// Sets a compose of SgfPoints to property id.
    pub fn set_point_point(&mut self, id: &str, value: (SgfPoint, SgfPoint)) -> &mut Self {
        self.set_property(id, vec![format!("{}:{}", value.0, value.1)])
    }

    /// Returns a Result of id's value as Compose of SgfPoint and SgfSimpleText.
    pub fn get_point_simple_text(&self, id: &str) -> Result<(SgfPoint, SgfSimpleText), SgfError> {
        self.get_property(id).and_then(|v| {
            let mut compose = v[0].splitn(2, ":");
            compose.next().ok_or(SgfError::EmptyProperty).and_then(|f|
                compose.next().ok_or(SgfError::EmptyProperty).map(|s| (f.to_string(), decode_simple_text(s))))
        })
    }

    /// Sets a compose of SgfPoint and SgfSimpleText to property id.
    pub fn set_point_simple_text(&mut self, id: &str, value: (SgfPoint, SgfSimpleText)) -> &mut Self {
        self.set_property(id, vec![format!("{}:{}", value.0, encode_text(&value.1))])
    }

    /// Returns a Result of id's value as Compose of SgfSimpleTexts.
    pub fn get_simple_text_simple_text(&self, id: &str) -> Result<(SgfSimpleText, SgfSimpleText), SgfError> {
        self.get_property(id).and_then(|v| {
            let mut compose = v[0].splitn(2, ":");
            compose.next().ok_or(SgfError::EmptyProperty).and_then(|f|
                compose.next().ok_or(SgfError::EmptyProperty).map(|s| (decode_simple_text(f), decode_simple_text(s))))
        })
    }

    /// Sets a compose of SgfSimpleTexts to property id.
    pub fn set_simple_text_simple_text(&mut self, id: &str, value: (SgfSimpleText, SgfSimpleText)) -> &mut Self {
        self.set_property(id, vec![format!("{}:{}", encode_text(&value.0), encode_text(&value.1))])
    }

    /// Returns a Result of id's value as Compose of SgfNumbers.
    pub fn get_number_number(&self, id: &str) -> Result<(SgfNumber, SgfNumber), SgfError> {
        self.get_property(id).and_then(|v| {
            let mut compose = v[0].splitn(2, ":");
            compose.next().ok_or(SgfError::EmptyProperty)
                .and_then(|f| f.parse::<i32>().map_err(|_| SgfError::ParseError))
                .and_then(|f| {
                    compose.next().ok_or(SgfError::EmptyProperty).and_then(|s|
                        match s.parse::<i32>() {
                            Ok(s) => Ok((f, s)),
                            Err(_) => Err(SgfError::ParseError),
                        }
                    )
                })
        })
    }

    /// Sets a compose of SgfNumbers to property id.
    pub fn set_number_number(&mut self, id: &str, value: (SgfNumber, SgfNumber)) -> &mut Self {
        self.set_property(id, vec![format!("{}:{}", value.0, value.1)])
    }

    /// Returns a Result of id's value as Compose of SgfNumber and SgfSimpleText.
    pub fn get_number_simple_text(&self, id: &str) -> Result<(SgfNumber, SgfSimpleText), SgfError> {
        self.get_property(id).and_then(|v| {
            let mut compose = v[0].splitn(2, ":");
            compose.next().ok_or(SgfError::EmptyProperty)
                .and_then(|f| f.parse::<i32>().map_err(|_| SgfError::ParseError))
                .and_then(|f| compose.next().ok_or(SgfError::EmptyProperty).map(|s| (f, decode_simple_text(s))))
        })
    }

    /// Sets a compose of SgfNumber and SgfSimpleText to property id.
    pub fn set_number_simple_text(&mut self, id: &str, value: (SgfNumber, SgfSimpleText)) -> &mut Self {
        self.set_property(id, vec![format!("{}:{}", value.0, encode_text(&value.1))])
    }
}

fn decode_text(s: &str) -> String {
    let s = Regex::new(r"\\(\r\n|\n\r|\n|\r)").unwrap().replace_all(s, ""); // soft line break
    let s = Regex::new(r"\\(.)").unwrap().replace_all(&s, "$1"); // escaping
    s
}

#[test]
fn test_decode_text() {
    assert_eq!(decode_text("[test\\\ntest\\:\\]"), "[testtest:]".to_string());
}

fn decode_simple_text(s: &str) -> String {
    let s = decode_text(s);
    let s = Regex::new(r"\r\n|\n\r|\n|\r").unwrap().replace_all(&s, " ");
    s
}

#[test]
fn test_decode_simple_text() {
    assert_eq!(decode_simple_text("test\ntest\r\ntest\n\rtest\rtest"), "test test test test test".to_string());
}

fn encode_text(s: &str) -> String {
    Regex::new(r"([\]\\:])").unwrap().replace_all(&s, "\\$1") // escaping
}

#[test]
fn test_encode_text() {
    assert_eq!(encode_text("]\\:"), "\\]\\\\\\:".to_string());
}

#[cfg(test)]
mod sgf_node_tests {
    use sgf_node::*;
    #[test]
    fn test_get_number() {
        let node = &SgfCollection::from_sgf("(;CA[UTF-8]FF[4])").unwrap()[0];
        assert_eq!(node.get_number("FF").unwrap(), 4);
    }

    #[test]
    fn test_get_real() {
        let node = &SgfCollection::from_sgf("(;CA[UTF-8]FF[4]KM[6.5])").unwrap()[0];
        assert_eq!(node.get_real("KM").unwrap(), 6.5);
    }

    #[test]
    fn test_get_points() {
        let node = &SgfCollection::from_sgf("(;CA[UTF-8]FF[4]KM[6.5]AB[ab])").unwrap()[0];
        assert_eq!(node.get_points("AB").unwrap(), vec!["ab".to_string()]);
    }

    #[test]
    fn test_get_point() {
        let node = &SgfCollection::from_sgf("(;CA[UTF-8]FF[4]KM[6.5];B[ab])").unwrap()[0];
        assert_eq!(node.children[0].get_point("B").unwrap(), "ab".to_string());
    }

    #[test]
    fn test_get_text() {
        let node = &SgfCollection::from_sgf("(;CA[UTF-8]FF[4]GC[text\ntext])").unwrap()[0];
        assert_eq!(node.get_text("GC").unwrap(), "text\ntext".to_string());
    }

    #[test]
    fn test_get_simple_text() {
        let node = &SgfCollection::from_sgf("(;CA[UTF-8]FF[4]N[simple\\\ntext\nsimple])").unwrap()[0];
        assert_eq!(node.get_simple_text("N").unwrap(), "simpletext simple".to_string());
    }

    #[test]
    fn test_get_simple_text_simple_text() {
        let node = &SgfCollection::from_sgf("(;CA[UTF-8]FF[4]AP[mimiaka:1.0])").unwrap()[0];
        assert_eq!(node.get_simple_text_simple_text("AP").unwrap(), ("mimiaka".to_string(), "1.0".to_string()));
    }

    #[test]
    fn test_set_text() {
        let node = &mut SgfCollection::from_sgf("(;CA[UTF-8]FF[4]AP[mimiaka:1.0])").unwrap()[0];
        node.set_text("GC", "test:".to_string());
        assert_eq!(node.get_text("GC").unwrap(), "test:".to_string());
    }

    #[test]
    fn test_get_simple_text_simple_text_with_newline() {
        let node = &SgfCollection::from_sgf("(;CA[UTF-8]FF[4]AP[mimiaka:1.0]\n)").unwrap()[0];
        println!("foo {}", node);
        assert_eq!(node.get_simple_text_simple_text("AP").unwrap(), ("mimiaka".to_string(), "1.0".to_string()));
    }
}