libgtp 0.1.2

A library implmenting the gtp protocol
Documentation
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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
use crate::model::Entity;
use alloc::borrow::ToOwned;
use alloc::fmt::Display;
use core::fmt;
use alloc::format;
use alloc::string::String;
use alloc::string::ToString;
use alloc::vec::Vec;
use core::iter::FromIterator;
use core::ops::IndexMut;
use core::ops::Index;
use core::str::FromStr;
use super::ParseError;

//use log::debug;


// MACROS
#[macro_export]
macro_rules! collection {
    ($($elem:expr),*) => {
        {
            let mut v : Vec<crate::model::SimpleEntity> = Vec::new();

            $(
                v.push($elem);
            )*
            crate::model::Collection::from_vec(v)
        }
    };
}

#[macro_export]
macro_rules! list {
    ($t:ty; $($elem:expr),*) => {
        {
            let mut v : Vec<$t> = Vec::new();

            $(
                v.push($elem);
            )*
            crate::model::types::List::from_vec(v)
        }
    };
}

#[derive(Debug, Clone, Copy)]
pub enum Boolean {
    True,
    False,
}

impl Display for Boolean {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::True => write!(f, "true"),
            Self::False => write!(f, "false"),
        }
    }
}

impl FromStr for Boolean {
    type Err = crate::model::ParseError;

    fn from_str(str: &str) -> Result<Self, Self::Err> {
        match str.to_uppercase().as_str() {
            "TRUE" => Ok(Self::True),
            "FALSE" => Ok(Self::False),
            _ => Err(Self::Err::WrongBool),
        }
    }
}

#[derive(Debug, Clone)]
pub struct Score(String);

impl FromStr for Score {
    type Err = crate::model::ParseError;

    fn from_str(str: &str) -> Result<Self, Self::Err> {
        if str.is_empty() {
            return Err(Self::Err::EmptyString);
        } else if str == "0" {
            Ok(Self(str.to_string()))
        } else {
            let split: Vec<&str> = str.split('+').collect();
            if split.len() > 2 {
                return Err(Self::Err::WrongScore);
            }

            match split[0] {
                "W" | "B" => (),
                _ => {return Err(Self::Err::WrongColor);}
            }

            split[1].parse::<f32>()?;

            Ok(Self(str.to_string()))
        }
    }
}

impl Display for Score {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Vertex {
    Coord(u8, u8),
    Pass,
    Resign,
}

impl Entity for Vertex {}

impl FromStr for Vertex {
    type Err = ParseError;

    fn from_str(str: &str) -> Result<Self, Self::Err> {
        if str.is_empty() {
            return Err(Self::Err::EmptyString);
        }
        let str = str.to_uppercase();
        if str == "PASS" {
            return Ok(Self::Pass)
        } else if str == "RESIGN" {
            return Ok(Self::Resign)
        } else if str == "" {
            return Err(ParseError::WrongCoordinates)
        }

        let mut c = str.bytes().next().unwrap() - 64;
        if (1..=20).contains(&c) {
            if c > 9 { // We skip I on the goban for readability
                c -= 1;
            }

            if let Ok(number) = str[1..].parse::<u8>() {
                Ok(Self::Coord(c, number))
            } else {
                Err(ParseError::WrongCoordinates)
            }
        } else {
            Err(ParseError::WrongCoordinates)
        }
    }
}

impl Display for Vertex {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        match self {
            Self::Coord(x, y) => {
                let mut x : u8 = x.clone();
                if x > 8 { // We skip I on the goban for readability
                    x = x + 1;
                }
                write!(f, "{}{}", ((x+64) as char).to_uppercase(), y)
            },
            Self::Pass => write!(f, "PASS"),
            Self::Resign => write!(f, "RESIGN"),
        }
    }
}

impl From<Vertex> for String {
    fn from(vertex: Vertex) -> Self {
        format!("{}", vertex)
    }
}

impl core::cmp::PartialEq<&str> for Vertex {
    fn eq(&self, rhs: &&str) -> bool {
        format!("{}", self) == *rhs.to_uppercase()
    }
}

impl core::cmp::PartialEq<String> for Vertex {
    fn eq(&self, rhs: &String) -> bool {
        format!("{}", self) == *rhs.to_uppercase()
    }
}

impl Vertex {
    pub const fn to_tuple(&self) -> Option<(u8, u8)> {
        match self {
            Self::Coord(x, y) => Some((*x, *y)),
            Self::Pass => None,
            Self::Resign => None,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Color {
    Black,
    White,
}

impl Entity for Color {}

impl Display for Color {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        match self {
            Self::Black => write!(f, "B"),
            Self::White => write!(f, "W"),
        }
    }
}

impl FromStr for Color {
    type Err = ParseError;

    fn from_str(str: &str) -> Result<Self, Self::Err> {
        if str.is_empty() {
            return Err(Self::Err::EmptyString);
        }
        let str = str.to_uppercase();
        match &*str {
            "B" | "BLACK" => Ok(Self::Black),
            "W" | "WHITE" => Ok(Self::White),
            _ => Err(ParseError::WrongColor),
        }
    }
}

impl From<Color> for String {
    fn from(col: Color) -> Self {
        format!("{}", col)
    }
}

impl core::cmp::PartialEq<&str> for Color {
    fn eq(&self, rhs: &&str) -> bool {
        format!("{}", self) == *rhs.to_uppercase()
    }
}

impl core::cmp::PartialEq<String> for Color {
    fn eq(&self, rhs: &String) -> bool {
        format!("{}", self) == *rhs.to_uppercase()
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Move {
    pub color: Color,
    pub vertex: Vertex,
}

impl Entity for Move {}

impl Display for Move {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        write!(f, "{} {}", self.color, self.vertex)
    }
}

impl FromStr for Move {
    type Err = ParseError;

    fn from_str(str: &str) -> Result<Self, Self::Err> {
        if str.is_empty() {
            return Err(ParseError::EmptyString);
        }
        let str = str.to_uppercase();
        let mut str = str.split_ascii_whitespace();
        Ok(Move {
            color: str.next().unwrap().parse()?,
            vertex: str.next().unwrap().parse()?,
        })
    }
}

impl From<Move> for String {
    fn from(mov: Move) -> Self {
        format!("{}", mov)
    }
}

impl core::cmp::PartialEq<&str> for Move {
    fn eq(&self, rhs: &&str) -> bool {
        format!("{}", self) == *rhs.to_uppercase()
    }
}

impl core::cmp::PartialEq<String> for Move {
    fn eq(&self, rhs: &String) -> bool {
        format!("{}", self) == *rhs.to_uppercase()
    }
}

#[derive(Debug, Clone, Copy, Hash)]
pub enum SimpleEntity {
    Vertex(Vertex),
    Color(Color),
    Move(Move),
}

impl alloc::fmt::Display for SimpleEntity {
    fn fmt(&self, f: &mut alloc::fmt::Formatter) -> alloc::fmt::Result {
        match self {
            SimpleEntity::Vertex(v) => write!(f, "{}", v),
            SimpleEntity::Color(c) => write!(f, "{}", c),
            SimpleEntity::Move(m) => write!(f, "{}", m),
        }
    }
}

impl FromStr for SimpleEntity {
    type Err = ParseError;

    fn from_str(str: &str) -> Result<SimpleEntity, Self::Err> {
        if let Ok(v) = str.parse::<Vertex>() {
            Ok(SimpleEntity::Vertex(v))
        } else if let Ok(c) = str.parse::<Color>() {
            Ok(SimpleEntity::Color(c))
        } else if let Ok(m) = str.parse::<Move>() {
            Ok(SimpleEntity::Move(m))
        } else {
            Err(ParseError::WrongSimpleEntity)
        }
    }
}

impl From<Vertex> for SimpleEntity {
    fn from(v: Vertex) -> Self {
        SimpleEntity::Vertex(v)
    }
}

impl From<Color> for SimpleEntity {
    fn from(c: Color) -> Self {
        SimpleEntity::Color(c)
    }
}

impl From<Move> for SimpleEntity {
    fn from(m: Move) -> Self {
        SimpleEntity::Move(m)
    }
}

impl SimpleEntity {
    pub fn as_vertex(self) -> Option<Vertex> {
        match self {
            Self::Vertex(v) => Some(v),
            _ => None,
        }
    }

    pub fn as_color(self) -> Option<Color> {
        match self {
            Self::Color(c) => Some(c),
            _ => None,
        }
    }

    pub fn as_move(self) -> Option<Move> {
        match self {
            Self::Move(m) => Some(m),
            _ => None,
        }
    }
}

#[derive(Debug, Clone, Hash)]
pub struct Collection(Vec<SimpleEntity>);

impl Entity for Collection {}

impl Display for Collection {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        if !self.0.is_empty() {
            write!(f, "{}", self.0[0])?;
            if self.0.len() > 1 {
                for entity in &self.0[1..] {
                    write!(f, " {}", entity)?;
                }
            }
            Ok(())
        } else {
            Ok(())
        }
    }
}

impl FromStr for Collection {
    type Err = ParseError;

    fn from_str(str: &str) -> Result<Self, Self::Err> {
        let elems : Vec<SimpleEntity> = str.to_uppercase().split_ascii_whitespace()
            .map(|e| if let Ok(elem) = e.parse::<SimpleEntity>() {
                elem
            } else {
                panic!()
            }).collect();

        Ok(Self(elems))
    }
}

impl Index<usize> for Collection {
    type Output = SimpleEntity;

    fn index(&self, i: usize) -> &Self::Output {
        &self.0[i]
    }
}

impl IndexMut<usize> for Collection {
    fn index_mut<'a>(&'a mut self, i: usize) -> &'a mut Self::Output {
        &mut self.0[i]
    }
}

impl Default for Collection {
    fn default() -> Self {
        Self {
            0: Vec::new(),
        }
    }
}

impl From<Vec<SimpleEntity>> for Collection {
    fn from(vec: Vec<SimpleEntity>) -> Self {
        Self(vec)
    }
}

impl FromIterator<SimpleEntity> for Collection {
    fn from_iter<I: IntoIterator<Item=SimpleEntity>>(it: I) -> Self {
        Self(it.into_iter().collect())
    }
}

impl IntoIterator for Collection {
    type Item = SimpleEntity;
    type IntoIter = alloc::vec::IntoIter<Self::Item>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

impl<'a> IntoIterator for &'a Collection {
    type Item = SimpleEntity;
    type IntoIter = alloc::vec::IntoIter<Self::Item>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.to_owned().into_iter()
    }
}

impl<'a> IntoIterator for &'a mut Collection {
    type Item = SimpleEntity;
    type IntoIter = alloc::vec::IntoIter<Self::Item>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.to_owned().into_iter()
    }
}

impl Collection {
    pub fn new() -> Self {
        Self::default()
    }

    pub const fn from_vec(vec: Vec<SimpleEntity>) -> Self {
        Self(vec)
    }

    pub fn push(&mut self, elem: SimpleEntity) {
        self.0.push(elem);
    }

    pub fn remove(&mut self, index: usize) -> SimpleEntity {
        self.0.remove(index)
    }

    pub fn into_vec(self) -> Vec<SimpleEntity> {
        self.0
    }

    pub const fn inner(&self) -> &Vec<SimpleEntity> {
        &self.0
    }

    pub fn mut_inner(&mut self) -> &mut Vec<SimpleEntity> {
        &mut self.0
    }

    pub fn iter(&self) -> core::slice::Iter<'_, SimpleEntity> {
        self.0.iter()
    }

    pub fn iter_mut(&mut self) -> core::slice::IterMut<'_, SimpleEntity> {
        self.0.iter_mut()
    }
}

#[derive(Debug, Clone, Hash)]
pub struct List<T : Entity>(Vec<T>);

impl<T: Entity> Entity for List<T> {}

impl<T: Entity> Display for List<T> {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        if !self.0.is_empty() {
            write!(f, "{}", self.0[0])?;
            if self.0.len() > 1 {
                for entity in &self.0[1..] {
                    write!(f, " {}", entity)?;
                }
            }
            Ok(())
        } else {
            Ok(())
        }
    }
}

impl<T: Entity> FromStr for List<T> {
    type Err = ParseError;

    fn from_str(str: &str) -> Result<Self, Self::Err> {
        let check_line_return: Vec<&str> = str.split('\n').collect();
        if check_line_return.len() > 2 {
            return Err(Self::Err::WrongArgs);
        }

        let elems : Vec<T> = str.split_ascii_whitespace()
            .take_while(|e| e.clone() != "".to_string())
            .map(|e| if let Ok(elem) = e.parse::<T>() {
                elem
            } else {
                panic!()
            }).collect();

        Ok(Self(elems))
    }
}

impl<T: Entity> Index<usize> for List<T> {
    type Output = T;

    fn index(&self, i: usize) -> &Self::Output {
        &self.0[i]
    }
}

impl<T: Entity> IndexMut<usize> for List<T> {
    fn index_mut<'a>(&'a mut self, i: usize) -> &'a mut Self::Output {
        &mut self.0[i]
    }
}

impl<T: Entity> Default for List<T> {
    fn default() -> Self {
        Self {
            0: Vec::new(),
        }
    }
}

impl<T: Entity> From<Vec<T>> for List<T> {
    fn from(vec: Vec<T>) -> Self {
        Self(vec)
    }
}

impl<T: Entity> FromIterator<T> for List<T> {
    fn from_iter<I: IntoIterator<Item=T>>(it: I) -> Self {
        Self(it.into_iter().collect())
    }
}

impl<T: Entity> IntoIterator for List<T> {
    type Item = T;
    type IntoIter = alloc::vec::IntoIter<Self::Item>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

impl<'a, T: Entity> IntoIterator for &'a List<T> {
    type Item = T;
    type IntoIter = alloc::vec::IntoIter<Self::Item>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.to_owned().into_iter()
    }
}

impl<'a, T: Entity> IntoIterator for &'a mut List<T> {
    type Item = T;
    type IntoIter = alloc::vec::IntoIter<Self::Item>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.to_owned().into_iter()
    }
}

impl<T: Entity> List<T> {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn from_vec(vec: Vec<T>) -> Self {
        Self(vec)
    }

    pub fn push(&mut self, elem: T) {
        self.0.push(elem);
    }

    pub fn remove(&mut self, index: usize) -> T {
        self.0.remove(index)
    }

    pub fn into_vec(self) -> Vec<T> {
        self.0
    }

    pub fn inner(&self) -> &Vec<T> {
        &self.0
    }

    pub fn mut_inner(&mut self) -> &mut Vec<T> {
        &mut self.0
    }

    pub fn iter(&self) -> core::slice::Iter<'_, T> {
        self.0.iter()
    }

    pub fn iter_mut(&mut self) -> core::slice::IterMut<'_, T> {
        self.0.iter_mut()
    }
}