trackaudio 0.2.2

A high-level async client for the TrackAudio WebSocket API, enabling programmatic control, automation, and custom integrations for VATSIM voice communication.
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
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
//! Commands for controlling TrackAudio.
//!
//! This module contains all commands that can be sent to TrackAudio to control radio behavior,
//! manage stations, and adjust audio settings.
//!
//! # Overview
//!
//! Commands are sent to TrackAudio as JSON messages via its WebSocket API and typically trigger
//! corresponding [`Event`]s in response. The main [`Command`] enum contains all available commands
//! including associated payload structs for commands that require additional data.
//!
//! # Request pattern
//!
//! Some commands (their respective payloads, to be precise) implement the [`Request`] trait,
//! allowing them to be used in a request-response pattern where you can await the corresponding
//! event response.
//!
//! # Examples
//!
//! ```rust
//! use trackaudio::Command;
//! use trackaudio::messages::commands::AddStation;
//!
//! // Simple command without a payload
//! let cmd = Command::PttPressed;
//!
//! // Command with payload
//! let cmd = Command::AddStation(AddStation {
//!     callsign: "LOVV_CTR".to_string(),
//! });
//! ```
//!
//! # External documentation
//!
//! For more details on TrackAudio's command protocol, see the
//! [SDK documentation](https://github.com/pierr3/TrackAudio/wiki/SDK-documentation#incoming-messages)
//! as well as the [respective implementation](https://github.com/pierr3/TrackAudio/blob/main/backend/src/sdk.cpp).

use crate::messages::Request;
use crate::messages::events::StationState;
use crate::{Event, Frequency};
use serde::Serialize;

/// Commands sent to the TrackAudio instance.
///
/// These messages are sent to TrackAudio to control its behavior and change the state programmatically.
///
/// # Serialization
///
/// Events are serialized to JSON strings sent to TrackAudio with a `type` field indicating the
/// variant name and a `value` field containing the variant's data.
///
/// # Notes
///
/// - TrackAudio's incoming messages SDK documentation can be found on
///   [GitHub](https://github.com/pierr3/TrackAudio/wiki/SDK-documentation#incoming-messages).
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(tag = "type", content = "value")]
pub enum Command {
    /// Start transmission by pressing the push-to-talk button.
    ///
    /// Initiates transmission on all active (TX/XC enabled) frequencies. Should be followed
    /// by [`Command::PttReleased`] when transmission ends.
    /// TrackAudio emits [`Event::TxBegin`] when the transmission starts.
    #[serde(rename = "kPttPressed")]
    PttPressed,

    /// End transmission by releasing the push-to-talk button.
    ///
    /// Stops a transmission started with [`Command::PttPressed`].
    /// TrackAudio emits [`Event::TxEnd`] when the transmission ends.
    #[serde(rename = "kPttReleased")]
    PttReleased,

    /// Add a new station to monitor.
    ///
    /// Tries to add a station with the specified callsign, allowing the user to receive and transmit
    /// on the associated frequency.
    /// TrackAudio emits [`Event::StationStateUpdate`], indicating success or failure adding the station.
    #[serde(rename = "kAddStation")]
    AddStation(AddStation),

    /// Update an existing station's state.
    ///
    /// Modifies properties of a station such as its rx/tx state, cross-couple mode, or other
    /// configuration settings.
    /// TrackAudio emits [`Event::StationStateUpdate`] with the updated state.
    #[serde(rename = "kSetStationState")]
    SetStationState(SetStationState),

    /// Adjust the volume of a specific station.
    ///
    /// Changes the audio level for a single station's received transmissions.
    /// TrackAudio emits [`Event::StationStateUpdate`] with the updated state.
    #[serde(rename = "kChangeStationVolume")]
    ChangeStationVolume(ChangeStationVolume),

    /// Adjust the main volume.
    ///
    /// Changes the main volume level for all audio outputs.
    /// TrackAudio emits [`Event::MainVolumeChange`] with the updated volume.
    #[serde(rename = "kChangeMainVolume")]
    ChangeMainVolume(ChangeMainVolume),

    /// Request the current main volume.
    ///
    /// Queries TrackAudio for the current main volume level.
    /// TrackAudio emits [`Event::MainVolumeChange`] with the updated volume.
    #[serde(rename = "kGetMainVolume")]
    GetMainVolume,

    /// Request the state of a specific station.
    ///
    /// Queries TrackAudio for the current configuration and station of a station.
    /// TrackAudio emits [`Event::StationStateUpdate`] with the current state.
    #[serde(rename = "kGetStationState")]
    GetStationState(GetStationState),

    /// Request the state of all monitored stations.
    ///
    /// Queries the complete state of all configured stations.
    /// TrackAudio emits [`Event::StationStates`] with all station data.
    #[serde(rename = "kGetStationStates")]
    GetStationStates,

    /// Request the current voice connection state.
    ///
    /// Queries whether the connection to the voice server is established.
    /// TrackAudio emits [`Event::VoiceConnectedState`] with the current state.
    #[serde(rename = "kGetVoiceConnectedState")]
    GetVoiceConnectedState,
}

/// Payload for adding a new station.
///
/// Specifies the callsign of the station to add. TrackAudio will look up the associated frequency
/// and transmitters for this callsign and monitor it accordingly.
///
/// This command implements the [`Request`] trait and can be used in a request-response pattern.
///
/// Furthermore, the [`TrackAudioApi`](crate::TrackAudioApi) provides a convenience wrapper
/// [`add_station`](crate::TrackAudioApi::add_station), which can be used to easily add a station
/// and await the associated response from TrackAudio.
/// # Examples
///
/// ```rust
/// use trackaudio::messages::commands::AddStation;
///
/// let cmd = AddStation {
///     callsign: "LOVV_CTR".to_string(),
/// };
/// ```
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct AddStation {
    /// Callsign of the station to add (e.g., "LOVV_CTR").
    pub callsign: String,
}

impl Request for AddStation {
    type Response = StationState;

    fn into_command(self) -> Command {
        Command::AddStation(self)
    }

    fn extract(event: &Event, cmd: &Command) -> Option<Self::Response> {
        let Command::AddStation(AddStation { callsign }) = cmd else {
            return None;
        };
        match event {
            Event::StationStateUpdate(state)
                if state.callsign.as_ref().is_some_and(|c| c == callsign) =>
            {
                Some(state.clone())
            }
            _ => None,
        }
    }
}

/// Payload for updating a station's state.
///
/// The station to update is identified by its `frequency` (in Hz/Hertz). All other fields are
/// optional and will not be changed if omitted.
/// Use [`BoolOrToggle::Toggle`] to toggle a boolean field without knowing its current state.
///
/// This command implements the [`Request`] trait and can be used in a request-response pattern.
///
/// # Examples
///
/// ```rust
/// use trackaudio::Frequency;
/// use trackaudio::messages::commands::{BoolOrToggle, SetStationState};
///
/// let cmd = SetStationState {
///     frequency: Frequency::from_mhz(132.600), // 132.600 MHz
///     rx: Some(BoolOrToggle::Bool(true)), // enable RX
///     tx: Some(BoolOrToggle::Bool(true)), // enable TX
///     xca: Some(BoolOrToggle::Bool(false)), // disable XCA
///     is_output_muted: None,
///     headset: Some(BoolOrToggle::Toggle), // toggle headset/speaker output
/// };
/// ```
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SetStationState {
    /// Frequency of station to set state for in Hz (Hertz, e.g., 132_600_000 for 132.600 MHz)
    pub frequency: Frequency,

    /// Whether to mute the audio output of the station.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub is_output_muted: Option<BoolOrToggle>,

    /// Whether to receive (RX) on this frequency.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rx: Option<BoolOrToggle>,

    /// Whether to transmit (TX) on this frequency.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tx: Option<BoolOrToggle>,

    /// Whether cross-coupling (XCA) mode is enabled on this frequency.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub xca: Option<BoolOrToggle>,

    /// Whether to route audio to the headset audio device only (`true`) or output to both
    /// speaker and headset (`false`) on this frequency.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub headset: Option<BoolOrToggle>,
}

impl SetStationState {
    /// Creates a new [`SetStationState`] command for the given frequency with all fields set to
    /// `None` (no changes). Use the builder methods to set the desired fields.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use trackaudio::Frequency;
    /// use trackaudio::messages::commands::SetStationState;
    ///
    /// let cmd = SetStationState::new(Frequency::from_mhz(132.600))
    ///     .rx(true)
    ///     .tx(true);
    /// ```
    #[must_use]
    pub fn new(frequency: impl Into<Frequency>) -> Self {
        Self {
            frequency: frequency.into(),
            is_output_muted: None,
            rx: None,
            tx: None,
            xca: None,
            headset: None,
        }
    }

    /// Sets the RX (receive) state.
    #[must_use]
    pub fn rx(mut self, value: impl Into<BoolOrToggle>) -> Self {
        self.rx = Some(value.into());
        self
    }

    /// Sets the TX (transmit) state.
    #[must_use]
    pub fn tx(mut self, value: impl Into<BoolOrToggle>) -> Self {
        self.tx = Some(value.into());
        self
    }

    /// Sets the XCA (cross-coupling) state.
    #[must_use]
    pub fn xca(mut self, value: impl Into<BoolOrToggle>) -> Self {
        self.xca = Some(value.into());
        self
    }

    /// Sets the headset routing state.
    ///
    /// When `true`, audio is routed to the headset device only.
    /// When `false`, audio is output to both speaker and headset.
    #[must_use]
    pub fn headset(mut self, value: impl Into<BoolOrToggle>) -> Self {
        self.headset = Some(value.into());
        self
    }

    /// Sets the output mute state.
    #[must_use]
    pub fn output_muted(mut self, value: impl Into<BoolOrToggle>) -> Self {
        self.is_output_muted = Some(value.into());
        self
    }
}

impl Request for SetStationState {
    type Response = StationState;

    fn into_command(self) -> Command {
        Command::SetStationState(self)
    }

    fn extract(event: &Event, cmd: &Command) -> Option<Self::Response> {
        let Command::SetStationState(SetStationState { frequency, .. }) = cmd else {
            return None;
        };
        match event {
            Event::StationStateUpdate(state)
                if state.frequency.is_some_and(|f| f == *frequency) =>
            {
                Some(state.clone())
            }
            _ => None,
        }
    }
}

/// Payload for adjusting a station's volume.
///
/// The volume change is relative to the current volume level.
///
/// This command implements the [`Request`] trait and can be used in a request-response pattern.
///
/// Furthermore, the [`TrackAudioApi`](crate::TrackAudioApi) provides a convenience wrapper
/// [`change_station_volume`](crate::TrackAudioApi::change_station_volume), which can be used to
/// easily change an existing station's volume and await the associated response from TrackAudio.
///
/// # Examples
///
/// ```rust
/// use trackaudio::Frequency;
/// use trackaudio::messages::commands::ChangeStationVolume;
///
/// let cmd = ChangeStationVolume {
///     frequency: Frequency::from_mhz(132.600), // 132.600 MHz
///     amount: 50, // 50% volume increase
/// };
///
/// let cmd = ChangeStationVolume {
///     frequency: Frequency::from_mhz(132.600), // 132.600 MHz
///     amount: -100, // -100% volume increase (effectively mute)
/// };
///
/// let cmd = ChangeStationVolume::new(Frequency::from_mhz(132.600), 127);
/// assert_eq!(cmd.amount, 100); // clamped to 100
///
/// let cmd = ChangeStationVolume::new(132_600_000, -127);
/// assert_eq!(cmd.amount, -100); // clamped to -100
/// ```
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct ChangeStationVolume {
    /// Frequency of station to change volume for in Hz (Hertz, e.g., 132_600_000 for 132.600 MHz)
    pub frequency: Frequency,

    /// Amount to adjust the volume by, in the range -100..=100.
    ///
    /// This is added to the current volume. The resulting volume will be clamped to the range 0..=100.
    pub amount: i8,
}

impl ChangeStationVolume {
    pub fn new(frequency: impl Into<Frequency>, amount: i8) -> Self {
        Self {
            frequency: frequency.into(),
            amount: amount.clamp(-100, 100),
        }
    }
}

impl Request for ChangeStationVolume {
    type Response = StationState;

    fn into_command(self) -> Command {
        Command::ChangeStationVolume(self)
    }

    fn extract(event: &Event, cmd: &Command) -> Option<Self::Response> {
        let Command::ChangeStationVolume(ChangeStationVolume { frequency, .. }) = cmd else {
            return None;
        };
        match event {
            Event::StationStateUpdate(state)
                if state.frequency.is_some_and(|f| f == *frequency) =>
            {
                Some(state.clone())
            }
            _ => None,
        }
    }
}

/// Payload for adjusting the main volume.
///
/// The volume change is relative to the current main volume level.
///
/// This command implements the [`Request`] trait and can be used in a request-response pattern.
///
/// Furthermore, the [`TrackAudioApi`](crate::TrackAudioApi) provides a convenience wrapper
/// [`change_main_volume`](crate::TrackAudioApi::change_main_volume), which can be
/// used to easily change the main volume and await the associated response from TrackAudio.
///
/// # Examples
///
/// ```rust
/// use trackaudio::messages::commands::ChangeMainVolume;
///
/// let cmd = ChangeMainVolume {
///     amount: 50, // 50% volume increase
/// };
///
/// let cmd = ChangeMainVolume {
///     amount: -100, // -100% volume increase (effectively mute)
/// };
///
/// let cmd = ChangeMainVolume::new(127);
/// assert_eq!(cmd.amount, 100); // clamped to 100
///
/// let cmd = ChangeMainVolume::new(-127);
/// assert_eq!(cmd.amount, -100); // clamped to -100
/// ```
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct ChangeMainVolume {
    /// Amount to adjust the volume by, in the range -100..=100.
    ///
    /// This is added to the current volume. The resulting volume will be clamped to the range 0..=100.
    pub amount: i8,
}

impl ChangeMainVolume {
    #[must_use]
    pub fn new(amount: i8) -> Self {
        Self {
            amount: amount.clamp(-100, 100),
        }
    }
}

impl Request for ChangeMainVolume {
    type Response = f32;

    fn into_command(self) -> Command {
        Command::ChangeMainVolume(self)
    }

    fn extract(event: &Event, _cmd: &Command) -> Option<Self::Response> {
        match event {
            Event::MainVolumeChange(change) => Some(change.volume),
            _ => None,
        }
    }
}

/// Payload for requesting a specific station's state.
///
/// This command implements the [`Request`] trait and can be used in a request-response pattern.
///
/// Furthermore, the [`TrackAudioApi`](crate::TrackAudioApi) provides a convenience wrapper
/// [`get_station_state`](crate::TrackAudioApi::get_station_state), which can be
/// used to easily request a station's state and await the associated response from TrackAudio.
///
/// # Examples
///
/// ```rust
/// use trackaudio::messages::commands::GetStationState;
///
/// let cmd = GetStationState {
///     callsign: "LOVV_CTR".to_string(),
/// };
/// ```
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct GetStationState {
    /// Callsign of station to request state for.
    pub callsign: String,
}

impl Request for GetStationState {
    type Response = StationState;

    fn into_command(self) -> Command {
        Command::GetStationState(self)
    }

    fn extract(event: &Event, cmd: &Command) -> Option<Self::Response> {
        let Command::GetStationState(GetStationState { callsign }) = cmd else {
            return None;
        };
        match event {
            Event::StationStateUpdate(state)
                if state.callsign.as_ref().is_some_and(|c| c == callsign) =>
            {
                Some(state.clone())
            }
            _ => None,
        }
    }
}

/// Payload for requesting all station states.
///
/// This is a unit struct as the command requires no additional data.
///
/// This command implements the [`Request`] trait and can be used in a request-response pattern.
///
/// Furthermore, the [`TrackAudioApi`](crate::TrackAudioApi) provides a convenience wrapper
/// [`get_station_states`](crate::TrackAudioApi::get_station_states), which can be used to easily
/// request the state of all stations and await the associated response from TrackAudio.
///
/// # Examples
///
/// ```rust
/// use trackaudio::messages::commands::GetStationStates;
///
/// let cmd = GetStationStates;
/// ```
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct GetStationStates;

impl Request for GetStationStates {
    type Response = Vec<StationState>;

    fn into_command(self) -> Command {
        Command::GetStationStates
    }

    fn extract(event: &Event, _cmd: &Command) -> Option<Self::Response> {
        match event {
            Event::StationStates(states) => Some(
                states
                    .stations
                    .iter()
                    .map(|s| s.value.clone())
                    .collect::<_>(),
            ),
            _ => None,
        }
    }
}

/// Payload for requesting voice connection state.
///
/// This is a unit struct as the command requires no additional data.
///
/// This command implements the [`Request`] trait and can be used in a request-response pattern.
///
/// Furthermore, the [`TrackAudioApi`](crate::TrackAudioApi) provides a convenience wrapper
/// [`get_voice_connected_state`](crate::TrackAudioApi::get_voice_connected_state), which can be used
/// to easily request the current voice connection state and await the associated response from TrackAudio.
///
/// # Examples
///
/// ```rust
/// use trackaudio::messages::commands::GetVoiceConnectedState;
///
/// let cmd = GetVoiceConnectedState;
/// ```
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct GetVoiceConnectedState;

impl Request for GetVoiceConnectedState {
    type Response = bool;

    fn into_command(self) -> Command {
        Command::GetVoiceConnectedState
    }

    fn extract(event: &Event, _cmd: &Command) -> Option<Self::Response> {
        match event {
            Event::VoiceConnectedState(state) => Some(state.connected),
            _ => None,
        }
    }
}

/// A boolean value or a toggle instruction.
///
/// Used in station state updates to either set a specific boolean value or toggle the current state
/// without needing to know its current value. TrackAudio represents toggles as the string literal
/// `"toggle"` in its JSON messages.
///
/// # Examples
///
/// ```rust
/// use trackaudio::messages::commands::BoolOrToggle;
///
/// // Set to a specific bool value
/// let enabled = BoolOrToggle::Bool(false);
/// assert_eq!(enabled, BoolOrToggle::Bool(false));
///
/// // Toggle the current state
/// let toggle = BoolOrToggle::Toggle;
/// assert_eq!(toggle, BoolOrToggle::Toggle);
///
/// // Convert from bool
/// let from_bool: BoolOrToggle = true.into();
/// assert_eq!(from_bool, BoolOrToggle::Bool(true));
///
/// // Convert from Option<bool>
/// let from_opt_some: BoolOrToggle = Some(true).into();
/// assert_eq!(from_opt_some, BoolOrToggle::Bool(true));
///
/// let from_opt_none: BoolOrToggle = None.into();
/// assert_eq!(from_opt_none, BoolOrToggle::Toggle);
/// ```
#[derive(Debug, Clone, PartialEq)]
pub enum BoolOrToggle {
    /// A specific boolean value.
    Bool(bool),
    /// Toggle the current state. Serializable as `"toggle"`.
    Toggle,
}

impl serde::Serialize for BoolOrToggle {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        match self {
            BoolOrToggle::Bool(b) => serializer.serialize_bool(*b),
            BoolOrToggle::Toggle => serializer.serialize_str("toggle"),
        }
    }
}

impl<'de> serde::Deserialize<'de> for BoolOrToggle {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        struct BoolOrToggleVisitor;

        impl serde::de::Visitor<'_> for BoolOrToggleVisitor {
            type Value = BoolOrToggle;

            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
                formatter.write_str("a boolean or \"toggle\"")
            }

            fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                Ok(BoolOrToggle::Bool(value))
            }

            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                if value == "toggle" {
                    Ok(BoolOrToggle::Toggle)
                } else {
                    Err(E::custom(format!("expected \"toggle\", got {value}")))
                }
            }
        }

        deserializer.deserialize_any(BoolOrToggleVisitor)
    }
}

impl From<bool> for BoolOrToggle {
    fn from(b: bool) -> Self {
        BoolOrToggle::Bool(b)
    }
}

impl From<Option<bool>> for BoolOrToggle {
    fn from(opt: Option<bool>) -> Self {
        match opt {
            Some(b) => BoolOrToggle::Bool(b),
            None => BoolOrToggle::Toggle,
        }
    }
}

impl TryFrom<BoolOrToggle> for bool {
    type Error = ();
    fn try_from(b: BoolOrToggle) -> Result<Self, Self::Error> {
        match b {
            BoolOrToggle::Bool(b) => Ok(b),
            BoolOrToggle::Toggle => Err(()),
        }
    }
}

impl BoolOrToggle {
    #[must_use]
    pub fn is_toggle(&self) -> bool {
        matches!(self, BoolOrToggle::Toggle)
    }

    #[must_use]
    pub fn is_true(&self) -> bool {
        matches!(self, BoolOrToggle::Bool(true))
    }

    #[must_use]
    pub fn is_false(&self) -> bool {
        matches!(self, BoolOrToggle::Bool(false))
    }

    #[must_use]
    pub fn as_bool(&self) -> Option<bool> {
        match self {
            BoolOrToggle::Bool(b) => Some(*b),
            BoolOrToggle::Toggle => None,
        }
    }

    #[must_use]
    pub fn unwrap_or(&self, default: bool) -> bool {
        self.as_bool().unwrap_or(default)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    mod bool_or_toggle {
        use super::BoolOrToggle;
        use serde_json;

        #[test]
        fn from_bool() {
            let b = BoolOrToggle::from(true);
            assert_eq!(b, BoolOrToggle::Bool(true));
        }

        #[test]
        fn from_option_bool() {
            let b = BoolOrToggle::from(Some(true));
            assert_eq!(b, BoolOrToggle::Bool(true));
        }

        #[test]
        fn from_option_none() {
            let b = BoolOrToggle::from(None);
            assert_eq!(b, BoolOrToggle::Toggle);
        }

        #[test]
        fn bool_try_from() {
            let b = BoolOrToggle::Bool(true);
            assert_eq!(bool::try_from(b), Ok(true));
        }

        #[test]
        fn toggle_try_from() {
            let b = BoolOrToggle::Toggle;
            assert_eq!(bool::try_from(b), Err(()));
        }

        #[test]
        fn is_toggle() {
            let b = BoolOrToggle::Toggle;
            assert!(b.is_toggle());
        }

        #[test]
        fn is_true() {
            let b = BoolOrToggle::Bool(true);
            assert!(b.is_true());
        }

        #[test]
        fn is_false() {
            let b = BoolOrToggle::Bool(false);
            assert!(b.is_false());
        }

        #[test]
        fn bool_as_bool() {
            let b = BoolOrToggle::Bool(true);
            assert_eq!(b.as_bool(), Some(true));
        }

        #[test]
        fn toggle_as_bool() {
            let b = BoolOrToggle::Toggle;
            assert_eq!(b.as_bool(), None);
        }

        #[test]
        fn bool_unwrap_or() {
            let b = BoolOrToggle::Bool(true);
            assert!(b.unwrap_or(false));
        }

        #[test]
        fn toggle_unwrap_or() {
            let b = BoolOrToggle::Toggle;
            assert!(!b.unwrap_or(false));
        }

        #[test]
        fn serialize_bool() {
            assert_eq!(
                serde_json::to_string(&BoolOrToggle::Bool(true)).unwrap(),
                "true"
            );
            assert_eq!(
                serde_json::to_string(&BoolOrToggle::Bool(false)).unwrap(),
                "false"
            );
        }

        #[test]
        fn serialize_toggle() {
            assert_eq!(
                serde_json::to_string(&BoolOrToggle::Toggle).unwrap(),
                "\"toggle\""
            );
        }

        #[test]
        fn deserialize_bool() {
            assert_eq!(
                serde_json::from_str::<BoolOrToggle>("true").unwrap(),
                BoolOrToggle::Bool(true)
            );
            assert_eq!(
                serde_json::from_str::<BoolOrToggle>("false").unwrap(),
                BoolOrToggle::Bool(false)
            );
        }

        #[test]
        fn deserialize_toggle() {
            assert_eq!(
                serde_json::from_str::<BoolOrToggle>("\"toggle\"").unwrap(),
                BoolOrToggle::Toggle
            );
        }
    }
}