shakmaty-uci 0.2.0

Universal Chess Interface (UCI) message parser
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
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
/*
 * SPDX-FileCopyrightText: Copyright: 2019 vampirc-uci authors
 * SPDX-FileCopyrightText: Copyright: 2024-2026 Contributors to shakmaty-uci <https://gitlab.com/Arcaik/shakmaty-uci>
 * SPDX-License-Identifier: GPL-3.0-or-later
 *
 * This file is based on vampirc-uci, licenced under the Apache License 2.0
 * by the vampirc-uci authors.
 *
 * Special thanks to Matija Kejžar for their work.
 */

#[allow(unused_imports)]
use alloc::string::ToString as _;
use alloc::{string::String, vec::Vec};
use core::{default::Default, fmt, str::FromStr, time::Duration};

use shakmaty::{fen::Fen, uci::UciMove};

use crate::parser::parse;

/// Error when parsing an invalid UCI message.
#[derive(Clone, Debug, PartialEq)]
pub struct ParseUciMessageError;

impl fmt::Display for ParseUciMessageError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "invalid UCI message")
    }
}

#[cfg(feature = "std")]
impl std::error::Error for ParseUciMessageError {}

/// A representation of a message going to and coming from an UCI engine.
///
/// See [Description of the Universal Chess Interface (UCI)] for details about the UCI protocol.
///
/// [Description of the Universal Chess Interface (UCI)]: https://gist.github.com/DOBRO/2592c6dad754ba67e6dcaec8c90165bf
#[must_use]
#[derive(Clone, Eq, PartialEq, Debug, Hash)]
pub enum UciMessage {
    /// The `uci` engine-bound message.
    Uci,

    /// The `debug` engine-bound message.
    Debug(bool),

    /// The `isready` engine-bound message.
    IsReady,

    /// The `register` engine-bound message.
    Register {
        /// The `register later` engine-bound message.
        later: bool,

        /// The name part of the `register name <name> code <code>` engine-bound message.
        name: Option<String>,

        /// The code part of the `register name <name> code <code>` engine-bound message.
        code: Option<String>,
    },

    /// The `position` engine-bound message.
    Position {
        /// If `true`, it denotes the starting chess position. Generally, if this property is `true`, then the value of
        /// the `fen` property will be `None`.
        startpos: bool,

        /// The [FEN format](https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation) representation of a chess
        /// position.
        fen: Option<Fen>,

        /// A list of moves to apply to the position.
        moves: Vec<UciMove>,
    },

    /// The `setoption` engine-bound message.
    SetOption {
        /// The name of the option to set.
        name: String,

        /// The value of the option to set. If the option has no value, this should be `None`.
        value: Option<String>,
    },

    /// The `ucinewgame` engine-bound message.
    UciNewGame,

    /// The `stop` engine-bound message.
    Stop,

    /// The `ponderhit` engine-bound message.
    PonderHit,

    /// The `quit` engine-bound message.
    Quit,

    /// The `go` engine-bound message.
    Go {
        /// Time-control-related `go` parameters (sub-commands).
        time_control: Option<UciTimeControl>,

        /// Search-related `go` parameters (sub-commands).
        search_control: Option<UciSearchControl>,
    },

    /// The `id` GUI-bound message.
    Id {
        /// The name of the engine, possibly including the version.
        name: Option<String>,

        /// The name of the author of the engine.
        author: Option<String>,
    },

    /// The `uciok` GUI-bound message.
    UciOk,

    /// The `readyok` GUI-bound message.
    ReadyOk,

    /// The `bestmove` GUI-bound message.
    BestMove {
        /// The move the engine thinks is the best one in the position.
        best_move: UciMove,

        /// The move the engine would like to ponder on.
        ponder: Option<UciMove>,
    },

    /// The `copyprotection` GUI-bound message.
    CopyProtection(ProtectionState),

    /// The `registration` GUI-bound message.
    Registration(ProtectionState),

    /// The `option` GUI-bound message.
    Option(UciOptionConfig),

    /// The `info` GUI-bound message.
    Info(UciInfo),
}

impl UciMessage {
    /// Constructs a [`UciMessage::Register`] message (`register later`)
    pub fn register_later() -> UciMessage {
        UciMessage::Register {
            later: true,
            name: None,
            code: None,
        }
    }

    /// Constructs a [`UciMessage::Register`] message (`register <code> <name>`)
    pub fn register_code(name: &str, code: &str) -> UciMessage {
        UciMessage::Register {
            later: false,
            name: Some(String::from(name)),
            code: Some(String::from(code)),
        }
    }

    /// Constructs an empty [`UciMessage::Go`] message.
    pub fn go() -> UciMessage {
        UciMessage::Go {
            search_control: None,
            time_control: None,
        }
    }

    /// Constructs a [`UciMessage::Go`] message to start calculation in ponder mode (`go ponder`).
    pub fn go_ponder() -> UciMessage {
        UciMessage::Go {
            search_control: None,
            time_control: Some(UciTimeControl::Ponder),
        }
    }

    /// Constructs a [`UciMessage::Go`] message to start infinite calculation (`go infinite`).
    pub fn go_infinite() -> UciMessage {
        UciMessage::Go {
            search_control: None,
            time_control: Some(UciTimeControl::Infinite),
        }
    }

    /// Constructs a [`UciMessage::Go`] message to start calculation for up to `milliseconds` (`go
    /// movetime <milliseconds>`).
    pub fn go_movetime(milliseconds: Duration) -> UciMessage {
        UciMessage::Go {
            search_control: None,
            time_control: Some(UciTimeControl::MoveTime(milliseconds)),
        }
    }
}

impl fmt::Display for UciMessage {
    #[allow(clippy::too_many_lines)]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let uci: String = match self {
            UciMessage::Debug(on) => {
                if *on {
                    String::from("debug on")
                } else {
                    String::from("debug off")
                }
            }
            UciMessage::Register { later, name, code } => {
                let mut s = String::from("register");

                if *later {
                    s += " later";
                } else {
                    if let Some(n) = name {
                        s += format!(" name {}", *n).as_str();
                    }
                    if let Some(c) = code {
                        s += format!(" code {}", *c).as_str();
                    }
                }

                s
            }
            UciMessage::Position {
                startpos,
                fen,
                moves,
            } => {
                let mut s = String::from("position ");
                if *startpos {
                    s += "startpos";
                } else if let Some(fen) = fen {
                    s += format!("fen {fen}").as_str();
                }

                if !moves.is_empty() {
                    s += " moves";

                    for m in moves {
                        s += format!(" {}", *m).as_str();
                    }
                }

                s
            }
            UciMessage::SetOption { name, value } => {
                let mut s: String = format!("setoption name {name}");

                if let Some(val) = value {
                    if val.is_empty() {
                        s += " value <empty>";
                    } else {
                        s += format!(" value {}", *val).as_str();
                    }
                } else {
                    s += " value <empty>";
                }

                s
            }
            UciMessage::Go {
                time_control,
                search_control,
            } => {
                let mut s = String::from("go");

                if let Some(tc) = time_control {
                    match tc {
                        UciTimeControl::Infinite => {
                            s += " infinite";
                        }
                        UciTimeControl::Ponder => {
                            s += " ponder";
                        }
                        UciTimeControl::MoveTime(duration) => {
                            s += format!(" movetime {}", duration.as_millis()).as_str();
                        }
                        UciTimeControl::TimeLeft {
                            white_time,
                            black_time,
                            white_increment,
                            black_increment,
                            moves_to_go,
                        } => {
                            if let Some(wt) = white_time {
                                s += format!(" wtime {}", wt.as_millis()).as_str();
                            }

                            if let Some(bt) = black_time {
                                s += format!(" btime {}", bt.as_millis()).as_str();
                            }

                            if let Some(wi) = white_increment {
                                s += format!(" winc {}", wi.as_millis()).as_str();
                            }

                            if let Some(bi) = black_increment {
                                s += format!(" binc {}", bi.as_millis()).as_str();
                            }

                            if let Some(mtg) = moves_to_go {
                                s += format!(" movestogo {}", *mtg).as_str();
                            }
                        }
                    }
                }

                if let Some(sc) = search_control {
                    if let Some(depth) = sc.depth {
                        s += format!(" depth {depth}").as_str();
                    }

                    if let Some(nodes) = sc.nodes {
                        s += format!(" nodes {nodes}").as_str();
                    }

                    if let Some(mate) = sc.mate {
                        s += format!(" mate {mate}").as_str();
                    }

                    if !sc.search_moves.is_empty() {
                        s += " searchmoves";
                        for m in &sc.search_moves {
                            s += format!(" {m}").as_str();
                        }
                    }
                }

                s
            }
            UciMessage::Uci => String::from("uci"),
            UciMessage::IsReady => String::from("isready"),
            UciMessage::UciNewGame => String::from("ucinewgame"),
            UciMessage::Stop => String::from("stop"),
            UciMessage::PonderHit => String::from("ponderhit"),
            UciMessage::Quit => String::from("quit"),

            // GUI-bound from this point on
            UciMessage::Id { name, author } => {
                let mut s = String::from("id ");
                if let Some(n) = name {
                    s += format!("name {n}").as_str();
                } else if let Some(a) = author {
                    s += format!("author {a}").as_str();
                }

                s
            }
            UciMessage::UciOk => String::from("uciok"),
            UciMessage::ReadyOk => String::from("readyok"),
            UciMessage::BestMove { best_move, ponder } => {
                let mut s = format!("bestmove {}", *best_move);

                if let Some(p) = ponder {
                    s += format!(" ponder {}", *p).as_str();
                }

                s
            }
            UciMessage::CopyProtection(cp_state) | UciMessage::Registration(cp_state) => {
                let mut s = match self {
                    UciMessage::CopyProtection(..) => String::from("copyprotection "),
                    UciMessage::Registration(..) => String::from("registration "),
                    _ => unreachable!(),
                };

                match cp_state {
                    ProtectionState::Checking => s += "checking",
                    ProtectionState::Ok => s += "ok",
                    ProtectionState::Error => s += "error",
                }

                s
            }
            UciMessage::Option(config) => config.to_string(),
            UciMessage::Info(info) => info.to_string(),
        };

        write!(f, "{uci}")
    }
}

impl FromStr for UciMessage {
    type Err = ParseUciMessageError;

    /// Parses a UCI message from a line (with or without a terminating newline) and returns a
    /// [`UciMessage`] or [`ParseUciMessageError`] if message is unknown or invalid.
    ///
    /// Usually used in a loop that reads a single line from an input stream, such as the stdin.
    ///
    /// # Errors
    ///
    /// Returns a [`ParseUciMessageError`] when message cannot be parsed
    ///
    /// # Examples
    ///
    /// ```
    /// use shakmaty_uci::{UciMessage};
    ///
    /// let msg: UciMessage = "uci\n".parse().unwrap();
    /// println!("Received message: {}", msg);
    /// ```
    fn from_str(line: &str) -> Result<UciMessage, ParseUciMessageError> {
        match parse(line) {
            Ok((_, msg)) => Ok(msg),
            Err(_) => Err(ParseUciMessageError),
        }
    }
}

/// This enum represents the possible variants of the `go` UCI message that deal with the chess game's time controls
/// and the engine's thinking time.
#[must_use]
#[derive(Clone, Eq, PartialEq, Debug, Hash)]
pub enum UciTimeControl {
    /// The `go ponder` message.
    Ponder,

    /// The `go infinite` message.
    Infinite,

    /// The information about the game's time controls.
    TimeLeft {
        /// White's time on the clock, in milliseconds.
        white_time: Option<Duration>,

        /// Black's time on the clock, in milliseconds.
        black_time: Option<Duration>,

        /// White's increment per move, in milliseconds.
        white_increment: Option<Duration>,

        /// Black's increment per move, in milliseconds.
        black_increment: Option<Duration>,

        /// The number of moves to go to the next time control.
        moves_to_go: Option<u8>,
    },

    /// Specifies how much time the engine should think about the move, in milliseconds.
    MoveTime(Duration),
}

impl UciTimeControl {
    /// Returns a [`UciTimeControl::TimeLeft`] with all members set to `None`.
    pub fn time_left() -> UciTimeControl {
        UciTimeControl::TimeLeft {
            white_time: None,
            black_time: None,
            white_increment: None,
            black_increment: None,
            moves_to_go: None,
        }
    }
}

/// A struct that controls the engine's (non-time-related) search settings.
#[must_use]
#[derive(Clone, Eq, PartialEq, Debug, Hash)]
pub struct UciSearchControl {
    /// Limits the search to these moves.
    pub search_moves: Vec<UciMove>,

    /// Search for mate in this many moves.
    pub mate: Option<u8>,

    /// Search to this ply depth.
    pub depth: Option<u8>,

    /// Search no more than this many nodes (positions).
    pub nodes: Option<u64>,
}

impl UciSearchControl {
    /// Creates an `UciSearchControl` with `depth` set to the parameter and everything else set to empty or `None`.
    pub fn depth(depth: u8) -> UciSearchControl {
        UciSearchControl {
            search_moves: vec![],
            mate: None,
            depth: Some(depth),
            nodes: None,
        }
    }

    /// Creates an `UciSearchControl` with `mate` set to the parameter and everything else set to empty or `None`.
    pub fn mate(mate: u8) -> UciSearchControl {
        UciSearchControl {
            search_moves: vec![],
            mate: Some(mate),
            depth: None,
            nodes: None,
        }
    }

    /// Creates an `UciSearchControl` with `nodes` set to the parameter and everything else set to empty or `None`.
    pub fn nodes(nodes: u64) -> UciSearchControl {
        UciSearchControl {
            search_moves: vec![],
            mate: None,
            depth: None,
            nodes: Some(nodes),
        }
    }

    /// Returns `true` if all of the struct's settings are either `None` or empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.search_moves.is_empty()
            && self.mate.is_none()
            && self.depth.is_none()
            && self.nodes.is_none()
    }
}

impl Default for UciSearchControl {
    /// Creates an empty `UciSearchControl`.
    fn default() -> Self {
        UciSearchControl {
            search_moves: vec![],
            mate: None,
            depth: None,
            nodes: None,
        }
    }
}

/// Represents the copy protection or registration state.
#[must_use]
#[derive(Copy, Clone, Eq, PartialEq, Debug, Hash)]
pub enum ProtectionState {
    /// Signifies the engine is checking the copy protection or registration.
    Checking,

    /// Signifies the copy protection or registration has been validated.
    Ok,

    /// Signifies error in copy protection or registratin validation.
    Error,
}

/// Represents a UCI option definition.
#[must_use]
#[derive(Clone, Eq, PartialEq, Debug, Hash)]
pub enum UciOptionConfig {
    /// The option of type `check` (a boolean).
    Check {
        /// The name of the option.
        name: String,

        /// The default value of this `bool` property.
        default: Option<bool>,
    },

    /// The option of type `spin` (a signed integer).
    Spin {
        /// The name of the option.
        name: String,

        /// The default value of this integer property.
        default: Option<i64>,

        /// The minimal value of this integer property.
        min: Option<i64>,

        /// The maximal value of this integer property.
        max: Option<i64>,
    },

    /// The option of type `combo` (a list of strings).
    Combo {
        /// The name of the option.
        name: String,

        /// The default value for this list of strings.
        default: Option<String>,

        /// The list of acceptable strings.
        var: Vec<String>,
    },

    /// The option of type `button` (an action).
    Button {
        /// The name of the option.
        name: String,
    },

    /// The option of type `string` (a string, unsurprisingly).
    String {
        /// The name of the option.
        name: String,

        /// The default value of this string option.
        default: Option<String>,
    },
}

impl UciOptionConfig {
    /// Returns the name of the option.
    #[must_use]
    pub fn get_name(&self) -> &str {
        match self {
            UciOptionConfig::Check { name, .. }
            | UciOptionConfig::Spin { name, .. }
            | UciOptionConfig::Combo { name, .. }
            | UciOptionConfig::Button { name }
            | UciOptionConfig::String { name, .. } => name.as_str(),
        }
    }

    /// Returns the type string of the option (ie. `"check"`, `"spin"` ...)
    #[must_use]
    pub fn get_type_str(&self) -> &'static str {
        match self {
            UciOptionConfig::Check { .. } => "check",
            UciOptionConfig::Spin { .. } => "spin",
            UciOptionConfig::Combo { .. } => "combo",
            UciOptionConfig::Button { .. } => "button",
            UciOptionConfig::String { .. } => "string",
        }
    }
}

impl fmt::Display for UciOptionConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut s = format!(
            "option name {} type {}",
            self.get_name(),
            self.get_type_str()
        );
        match self {
            UciOptionConfig::Check { default, .. } => {
                if let Some(def) = default {
                    s += format!(" default {}", *def).as_str();
                }
            }
            UciOptionConfig::Spin {
                default, min, max, ..
            } => {
                if let Some(def) = default {
                    s += format!(" default {}", *def).as_str();
                }

                if let Some(m) = min {
                    s += format!(" min {}", *m).as_str();
                }

                if let Some(m) = max {
                    s += format!(" max {}", *m).as_str();
                }
            }
            UciOptionConfig::Combo { default, var, .. } => {
                if let Some(def) = default {
                    s += format!(" default {}", *def).as_str();
                }

                for v in var {
                    s += format!(" var {}", *v).as_str();
                }
            }
            UciOptionConfig::String { default, .. } => {
                if let Some(def) = default {
                    s += format!(" default {}", *def).as_str();
                }
            }
            UciOptionConfig::Button { .. } => {
                // Do nothing, we're already good
            }
        }

        write!(f, "{s}")
    }
}

#[must_use]
#[derive(Clone, Eq, PartialEq, Debug, Hash, Default)]
pub struct UciInfo {
    /// The `info depth` message.
    pub depth: Option<u8>,

    /// The `info seldepth` message.
    pub sel_depth: Option<u8>,

    /// The `info time` message.
    pub time: Option<Duration>,

    /// The `info nodes` message.
    pub nodes: Option<u64>,

    /// The `info pv` message (best line move sequence).
    pub pv: Vec<UciMove>,

    /// The `info pv ... multipv` message (the pv line number in a multi pv sequence).
    pub multi_pv: Option<u16>,

    /// The `info score ...` message.
    pub score: Option<UciInfoScore>,

    /// The `info currmove` message (current move).
    pub curr_move: Option<UciMove>,

    /// The `info currmovenumber` message (current move number).
    pub curr_move_num: Option<u16>,

    /// The `info hashfull` message (the occupancy of hashing tables in permills).
    pub hash_full: Option<u16>,

    /// The `info nps` message (nodes per second).
    pub nps: Option<u64>,

    /// The `info tbhits` message (end-game table-base hits).
    pub tb_hits: Option<u64>,

    /// The `info sbhits` message (I guess some Shredder-specific end-game table-base stuff. I dunno, probably best to
    /// ignore).
    pub sb_hits: Option<u64>,

    /// The `info cpuload` message (CPU load in permills).
    pub cpu_load: Option<u16>,

    /// The `info string` message (a string the GUI should display).
    pub string: Option<String>,

    /// The `info refutation` message (the first move is the move being refuted).
    pub refutation: Vec<UciMove>,

    /// The `info currline` message (current line being calculated on a CPU).
    pub curr_line: Vec<UciInfoCurrLine>,
}

impl fmt::Display for UciInfo {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut s = String::from("info");

        if let Some(depth) = self.depth {
            s += format!(" depth {depth}").as_str();
        }

        if let Some(sel_depth) = self.sel_depth {
            s += format!(" seldepth {sel_depth}").as_str();
        }

        if let Some(time) = self.time {
            s += format!(" time {}", time.as_millis()).as_str();
        }

        if let Some(nodes) = self.nodes {
            s += format!(" nodes {nodes}").as_str();
        }

        if !self.pv.is_empty() {
            s += " pv";

            for m in &self.pv {
                s += format!(" {m}").as_str();
            }
        }

        if !self.refutation.is_empty() {
            s += " refutation";

            for m in &self.refutation {
                s += format!(" {m}").as_str();
            }
        }

        if let Some(multi_pv) = self.multi_pv {
            s += format!(" multipv {multi_pv}").as_str();
        }

        if let Some(score) = &self.score {
            s += format!(" score {score}").as_str();
        }

        if let Some(curr_move) = &self.curr_move {
            s += format!(" currmove {curr_move}").as_str();
        }

        if let Some(curr_move_num) = self.curr_move_num {
            s += format!(" currmovenumber {curr_move_num}").as_str();
        }

        if let Some(hash_full) = self.hash_full {
            s += format!(" hashfull {hash_full}").as_str();
        }

        if let Some(nps) = self.nps {
            s += format!(" nps {nps}").as_str();
        }

        if let Some(tb_hits) = self.tb_hits {
            s += format!(" tbhits {tb_hits}").as_str();
        }

        if let Some(sb_hits) = self.sb_hits {
            s += format!(" sbhits {sb_hits}").as_str();
        }

        if let Some(cpu_load) = self.cpu_load {
            s += format!(" cpuload {cpu_load}").as_str();
        }

        if let Some(string) = &self.string {
            s += format!(" string {string}").as_str();
        }

        for c in &self.curr_line {
            s += format!(" currline {c}").as_str();
        }

        /*
        UciInfoAttribute::Any(_, value) => {
            s += &format!(" {value}");
        }
        */

        write!(f, "{s}")
    }
}

#[derive(Clone, Eq, PartialEq, Debug, Hash)]
pub struct UciInfoCurrLine {
    /// The CPU number calculating this line.
    pub cpu_nr: Option<u16>,

    /// The line being calculated.
    pub moves: Vec<UciMove>,
}

impl fmt::Display for UciInfoCurrLine {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut s = String::new();

        if let Some(c) = self.cpu_nr {
            s += format!(" cpunr {c}").as_str();
        }

        if !self.moves.is_empty() {
            for m in &self.moves {
                s += format!(" {m}").as_str();
            }
        }

        write!(f, "{}", s.trim())
    }
}

#[must_use]
#[derive(Clone, Eq, PartialEq, Debug, Hash, Default)]
pub struct UciInfoScore {
    /// The score in centipawns.
    pub cp: Option<i32>,

    /// Mate coming up in this many moves. Negative value means the engine is getting mated.
    pub mate: Option<i8>,

    /// The value sent is the lower bound.
    pub lower_bound: bool,

    /// The value sent is the upper bound.
    pub upper_bound: bool,
}

impl UciInfoScore {
    pub fn from_centipawns(cp: i32) -> UciInfoScore {
        UciInfoScore {
            cp: Some(cp),
            ..Default::default()
        }
    }
}

impl fmt::Display for UciInfoScore {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut s = String::new();

        if let Some(c) = self.cp {
            s += format!(" cp {c}").as_str();
        }

        if let Some(m) = self.mate {
            s += format!(" mate {m}").as_str();
        }

        if self.lower_bound {
            s += " lowerbound";
        } else if self.upper_bound {
            s += " upperbound";
        }

        write!(f, "{}", s.trim())
    }
}