litchee 0.1.5

Async, builder-pattern Rust client for the Lichess API: full endpoint coverage, NDJSON streaming, and OAuth2 PKCE ('Log in with Lichess').
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
//! The Swiss Tournaments API: create, run, join, and export swiss tournaments.
//!
//! Reached through [`LichessClient::swiss`].

use futures_util::stream::BoxStream;
use reqwest::{Method, StatusCode};
use serde::{Deserialize, Serialize};

use crate::api::gameplay::games::LichessGame;
use crate::client::LichessClient;
use crate::config::Host;
use crate::error::{ApiErrorKind, LichessError, Result};
use crate::http;
use crate::model::{GameExportOptions, LichessTitle, LichessVariantKey};

/// Reclassifies a `401` from a Swiss edit/schedule request as the distinct
/// [`ApiErrorKind::SwissUnauthorizedEdit`] ownership rejection — the spec's
/// `SwissUnauthorisedEdit` response — rather than a generic auth failure.
fn map_unauthorized_edit(err: LichessError) -> LichessError {
    match err {
        LichessError::Api(api) if api.status == StatusCode::UNAUTHORIZED => {
            LichessError::Api(api.with_kind(ApiErrorKind::SwissUnauthorizedEdit))
        }
        other => other,
    }
}

/// The interval between Swiss rounds.
///
/// Serializes to the wire integer the spec expects, including the two sentinel
/// values that a plain seconds count cannot express.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(into = "i32")]
#[non_exhaustive]
pub enum SwissRoundInterval {
    /// Let Lichess pick a sensible value automatically (wire `-1`).
    Auto,
    /// Schedule each round manually from the tournament UI (wire `99999999`).
    Manual,
    /// A fixed number of seconds between rounds.
    Seconds(u32),
}

impl From<SwissRoundInterval> for i32 {
    fn from(interval: SwissRoundInterval) -> Self {
        match interval {
            SwissRoundInterval::Auto => -1,
            SwissRoundInterval::Manual => 99_999_999,
            SwissRoundInterval::Seconds(seconds) => i32::try_from(seconds).unwrap_or(i32::MAX),
        }
    }
}

/// Form body for creating a swiss tournament (flat, non-`conditions` fields).
#[derive(Debug, Default, Serialize)]
struct CreateForm<'a> {
    #[serde(rename = "clock.limit")]
    clock_limit: u32,
    #[serde(rename = "clock.increment")]
    clock_increment: u32,
    #[serde(rename = "nbRounds")]
    nb_rounds: u32,
    #[serde(skip_serializing_if = "Option::is_none")]
    name: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    rated: Option<bool>,
    #[serde(rename = "roundInterval", skip_serializing_if = "Option::is_none")]
    round_interval: Option<SwissRoundInterval>,
    #[serde(rename = "startsAt", skip_serializing_if = "Option::is_none")]
    starts_at: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    variant: Option<LichessVariantKey>,
    #[serde(skip_serializing_if = "Option::is_none")]
    position: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    description: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    password: Option<&'a str>,
    #[serde(rename = "forbiddenPairings", skip_serializing_if = "Option::is_none")]
    forbidden_pairings: Option<&'a str>,
    #[serde(rename = "manualPairings", skip_serializing_if = "Option::is_none")]
    manual_pairings: Option<&'a str>,
    #[serde(rename = "chatFor", skip_serializing_if = "Option::is_none")]
    chat_for: Option<u32>,
}

/// Entry conditions for a swiss tournament, serialized as `conditions.*` keys.
#[derive(Debug, Clone, Default, Serialize)]
pub struct SwissConditions<'a> {
    #[serde(
        rename = "conditions.minRating.rating",
        skip_serializing_if = "Option::is_none"
    )]
    min_rating: Option<u32>,
    #[serde(
        rename = "conditions.maxRating.rating",
        skip_serializing_if = "Option::is_none"
    )]
    max_rating: Option<u32>,
    #[serde(
        rename = "conditions.nbRatedGame.nb",
        skip_serializing_if = "Option::is_none"
    )]
    nb_rated_games: Option<u32>,
    #[serde(
        rename = "conditions.allowList",
        skip_serializing_if = "Option::is_none"
    )]
    allow_list: Option<&'a str>,
    #[serde(
        rename = "conditions.playYourGames",
        skip_serializing_if = "Option::is_none"
    )]
    play_your_games: Option<bool>,
}

impl<'a> SwissConditions<'a> {
    /// Minimum rating to join.
    #[must_use]
    pub fn min_rating(mut self, rating: u32) -> Self {
        self.min_rating = Some(rating);
        self
    }

    /// Maximum rating to join.
    #[must_use]
    pub fn max_rating(mut self, rating: u32) -> Self {
        self.max_rating = Some(rating);
        self
    }

    /// Minimum number of rated games required to join.
    #[must_use]
    pub fn nb_rated_games(mut self, count: u32) -> Self {
        self.nb_rated_games = Some(count);
        self
    }

    /// Comma-separated usernames allowed to join (append `%titled` to also allow
    /// any titled player).
    #[must_use]
    pub fn allow_list(mut self, usernames: &'a str) -> Self {
        self.allow_list = Some(usernames);
        self
    }

    /// Require players to have played their games (no repeated no-shows).
    #[must_use]
    pub fn play_your_games(mut self, value: bool) -> Self {
        self.play_your_games = Some(value);
        self
    }
}

/// Accessor for the Swiss Tournaments API.
#[derive(Debug)]
pub struct SwissApi<'a> {
    client: &'a LichessClient,
}

impl<'a> SwissApi<'a> {
    /// Binds the accessor to a client.
    pub(crate) fn new(client: &'a LichessClient) -> Self {
        Self { client }
    }

    /// Gets a swiss tournament. `GET /api/swiss/{id}`
    pub async fn get(&self, id: &str) -> Result<LichessSwiss> {
        let path = format!("/api/swiss/{}", http::segment(id));
        let request = self.client.request(Method::GET, Host::Default, &path);
        http::json(request, "LichessSwiss").await
    }

    /// Creates a swiss tournament for a team. `POST /api/swiss/new/{teamId}`
    #[must_use]
    pub fn create(
        &self,
        team_id: &'a str,
        clock_limit: u32,
        clock_increment: u32,
        nb_rounds: u32,
    ) -> CreateSwissRequest<'a> {
        CreateSwissRequest::new(
            self.client,
            team_id,
            false,
            clock_limit,
            clock_increment,
            nb_rounds,
        )
    }

    /// Updates a swiss tournament. `POST /api/swiss/{id}/edit`
    #[must_use]
    pub fn edit(
        &self,
        id: &'a str,
        clock_limit: u32,
        clock_increment: u32,
        nb_rounds: u32,
    ) -> CreateSwissRequest<'a> {
        CreateSwissRequest::new(
            self.client,
            id,
            true,
            clock_limit,
            clock_increment,
            nb_rounds,
        )
    }

    /// Joins a swiss tournament, optionally with an entry `password`.
    /// `POST /api/swiss/{id}/join`
    pub async fn join(&self, id: &str, password: Option<&str>) -> Result<()> {
        let path = format!("/api/swiss/{}/join", http::segment(id));
        let request = self
            .client
            .request(Method::POST, Host::Default, &path)
            .form(&[("password", password)]);
        http::ok(request).await
    }

    /// Withdraws from a swiss tournament. `POST /api/swiss/{id}/withdraw`
    pub async fn withdraw(&self, id: &str) -> Result<()> {
        self.post_action(id, "withdraw").await
    }

    /// Terminates a swiss tournament. `POST /api/swiss/{id}/terminate`
    pub async fn terminate(&self, id: &str) -> Result<()> {
        self.post_action(id, "terminate").await
    }

    /// Manually schedules the next round at `date` (Unix milliseconds).
    /// `POST /api/swiss/{id}/schedule-next-round`
    pub async fn schedule_next_round(&self, id: &str, date: Option<i64>) -> Result<()> {
        let path = format!("/api/swiss/{}/schedule-next-round", http::segment(id));
        let request = self
            .client
            .request(Method::POST, Host::Default, &path)
            .form(&[("date", date)]);
        http::ok(request).await.map_err(map_unauthorized_edit)
    }

    /// Downloads the tournament in TRF format. `GET /swiss/{id}.trf`
    pub async fn trf(&self, id: &str) -> Result<String> {
        let path = format!("/swiss/{}.trf", http::segment(id));
        http::text(self.client.request(Method::GET, Host::Default, &path)).await
    }

    /// Streams a swiss tournament's results. `GET /api/swiss/{id}/results`
    ///
    /// `nb` limits the number of results.
    pub async fn results(
        &self,
        id: &str,
        nb: Option<u32>,
    ) -> Result<BoxStream<'static, Result<LichessSwissResult>>> {
        let path = format!("/api/swiss/{}/results", http::segment(id));
        let request = self
            .client
            .request(Method::GET, Host::Default, &path)
            .query(&[("nb", nb)]);
        http::stream(request, self.client.max_line_bytes()).await
    }

    /// Starts an export of a swiss tournament's games. `GET /api/swiss/{id}/games`
    ///
    /// Finish with [`stream`](SwissGamesRequest::stream) or
    /// [`pgn`](SwissGamesRequest::pgn).
    #[must_use]
    pub fn games(&self, id: &'a str) -> SwissGamesRequest<'a> {
        SwissGamesRequest::new(self.client, id)
    }

    /// Issues a no-argument `POST` action on a swiss tournament.
    async fn post_action(&self, id: &str, action: &str) -> Result<()> {
        let path = format!("/api/swiss/{}/{}", http::segment(id), http::segment(action));
        http::ok(self.client.request(Method::POST, Host::Default, &path)).await
    }
}

/// Builder for creating or editing a swiss tournament.
#[derive(Debug)]
pub struct CreateSwissRequest<'a> {
    client: &'a LichessClient,
    /// Team id for creation, or tournament id when editing.
    target_id: &'a str,
    edit: bool,
    form: CreateForm<'a>,
    conditions: SwissConditions<'a>,
}

impl<'a> CreateSwissRequest<'a> {
    /// Creates the request builder.
    fn new(
        client: &'a LichessClient,
        target_id: &'a str,
        edit: bool,
        clock_limit: u32,
        clock_increment: u32,
        nb_rounds: u32,
    ) -> Self {
        Self {
            client,
            target_id,
            edit,
            form: CreateForm {
                clock_limit,
                clock_increment,
                nb_rounds,
                ..Default::default()
            },
            conditions: SwissConditions::default(),
        }
    }

    /// Sets the tournament name.
    #[must_use]
    pub fn name(mut self, name: &'a str) -> Self {
        self.form.name = Some(name);
        self
    }

    /// Sets whether the tournament is rated.
    #[must_use]
    pub fn rated(mut self, rated: bool) -> Self {
        self.form.rated = Some(rated);
        self
    }

    /// Sets the interval between rounds.
    ///
    /// Use [`SwissRoundInterval::Seconds`] for a fixed gap, or `Auto`/`Manual`
    /// for the spec's sentinel values.
    #[must_use]
    pub fn round_interval(mut self, interval: SwissRoundInterval) -> Self {
        self.form.round_interval = Some(interval);
        self
    }

    /// Starts the tournament at this timestamp (Unix milliseconds).
    #[must_use]
    pub fn starts_at(mut self, timestamp: i64) -> Self {
        self.form.starts_at = Some(timestamp);
        self
    }

    /// Sets the variant.
    #[must_use]
    pub fn variant(mut self, variant: LichessVariantKey) -> Self {
        self.form.variant = Some(variant);
        self
    }

    /// Sets a custom starting position (FEN).
    #[must_use]
    pub fn position(mut self, fen: &'a str) -> Self {
        self.form.position = Some(fen);
        self
    }

    /// Sets the tournament description.
    #[must_use]
    pub fn description(mut self, description: &'a str) -> Self {
        self.form.description = Some(description);
        self
    }

    /// Makes the tournament private, restricted by this password.
    #[must_use]
    pub fn password(mut self, password: &'a str) -> Self {
        self.form.password = Some(password);
        self
    }

    /// Sets pairings that must not occur (newline-separated username pairs).
    #[must_use]
    pub fn forbidden_pairings(mut self, pairings: &'a str) -> Self {
        self.form.forbidden_pairings = Some(pairings);
        self
    }

    /// Sets manual pairings for the next round (newline-separated username pairs).
    #[must_use]
    pub fn manual_pairings(mut self, pairings: &'a str) -> Self {
        self.form.manual_pairings = Some(pairings);
        self
    }

    /// Sets who may use the chat (Lichess `chatFor` code).
    #[must_use]
    pub fn chat_for(mut self, chat_for: u32) -> Self {
        self.form.chat_for = Some(chat_for);
        self
    }

    /// Sets the entry conditions.
    #[must_use]
    pub fn conditions(mut self, conditions: SwissConditions<'a>) -> Self {
        self.conditions = conditions;
        self
    }

    /// Creates or updates the tournament.
    pub async fn send(self) -> Result<LichessSwiss> {
        let path = self.path();
        let request = self
            .client
            .request(Method::POST, Host::Default, &path)
            .form_parts(&self.form, &self.conditions);
        let result = http::json(request, "LichessSwiss").await;
        if self.edit {
            result.map_err(map_unauthorized_edit)
        } else {
            result
        }
    }

    /// The create or edit path for this request.
    fn path(&self) -> String {
        if self.edit {
            format!("/api/swiss/{}/edit", http::segment(self.target_id))
        } else {
            format!("/api/swiss/new/{}", http::segment(self.target_id))
        }
    }
}

/// Builder for exporting a swiss tournament's games
/// (`GET /api/swiss/{id}/games`).
#[derive(Debug)]
pub struct SwissGamesRequest<'a> {
    client: &'a LichessClient,
    id: &'a str,
    player: Option<&'a str>,
    export: GameExportOptions,
}

impl<'a> SwissGamesRequest<'a> {
    /// Creates the request builder.
    pub(crate) fn new(client: &'a LichessClient, id: &'a str) -> Self {
        Self {
            client,
            id,
            player: None,
            export: GameExportOptions::default(),
        }
    }

    /// Only games featuring this player.
    #[must_use]
    pub fn player(mut self, player: &'a str) -> Self {
        self.player = Some(player);
        self
    }

    /// Sets the shared export-format options (moves, clocks, evals, …).
    #[must_use]
    pub fn export(mut self, options: GameExportOptions) -> Self {
        self.export = options;
        self
    }

    /// Executes the export, streaming games as decoded JSON values.
    pub async fn stream(self) -> Result<BoxStream<'static, Result<LichessGame>>> {
        let request = self.request(http::ACCEPT_NDJSON);
        http::stream(request, self.client.max_line_bytes()).await
    }

    /// Executes the export, returning all games as one PGN string.
    pub async fn pgn(self) -> Result<String> {
        http::text(self.request(http::ACCEPT_PGN)).await
    }

    /// Builds the request with the given `Accept` representation.
    fn request(&self, accept: &'static str) -> http::ApiRequest {
        let path = format!("/api/swiss/{}/games", http::segment(self.id));
        self.client
            .request(Method::GET, Host::Default, &path)
            .header(reqwest::header::ACCEPT, accept)
            .query(&[("player", self.player)])
            .query(&self.export)
    }
}

impl LichessClient {
    /// Swiss Tournaments API.
    #[must_use]
    pub fn swiss(&self) -> SwissApi<'_> {
        SwissApi::new(self)
    }
}

/// A swiss clock (`limit` + `increment`, in seconds).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct LichessSwissClock {
    /// Initial time in seconds.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
    /// Increment per move in seconds.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub increment: Option<u32>,
}

/// When the next round of a swiss starts.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct LichessSwissNextRound {
    /// Absolute start time (Unix milliseconds).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub at: Option<i64>,
    /// Seconds until the next round starts.
    #[serde(rename = "in", default, skip_serializing_if = "Option::is_none")]
    pub in_seconds: Option<i64>,
}

/// A swiss tournament.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct LichessSwiss {
    /// The tournament id.
    pub id: String,
    /// The creator's username.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub created_by: Option<String>,
    /// Start time (Unix milliseconds).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub starts_at: Option<i64>,
    /// The tournament name.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// The clock.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub clock: Option<LichessSwissClock>,
    /// The variant.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub variant: Option<String>,
    /// The current round number.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub round: Option<u32>,
    /// The total number of rounds.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub nb_rounds: Option<u32>,
    /// The number of players.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub nb_players: Option<u32>,
    /// The number of ongoing games.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub nb_ongoing: Option<u32>,
    /// The status (`created`, `started`, or `finished`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub status: Option<String>,
    /// Whether the tournament is rated.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rated: Option<bool>,
    /// When the next round starts.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub next_round: Option<LichessSwissNextRound>,
}

/// One entry in a swiss results stream.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct LichessSwissResult {
    /// The player's final rank.
    pub rank: u32,
    /// The player's points.
    pub points: f64,
    /// The player's tie-break score.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tie_break: Option<f64>,
    /// The player's rating.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rating: Option<u32>,
    /// The player's username.
    pub username: String,
    /// The player's title.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub title: Option<LichessTitle>,
    /// The player's tournament performance rating.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub performance: Option<u32>,
}

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

    #[test]
    fn maps_401_to_swiss_unauthorized_edit() {
        let err = LichessError::Api(ApiError::new(StatusCode::UNAUTHORIZED, None, None));
        match map_unauthorized_edit(err) {
            LichessError::Api(api) => assert_eq!(api.kind, ApiErrorKind::SwissUnauthorizedEdit),
            other => panic!("expected Api error, got {other:?}"),
        }
    }

    #[test]
    fn leaves_non_401_errors_unchanged() {
        let err = LichessError::Api(ApiError::new(StatusCode::NOT_FOUND, None, None));
        match map_unauthorized_edit(err) {
            LichessError::Api(api) => assert_eq!(api.kind, ApiErrorKind::NotFound),
            other => panic!("expected Api error, got {other:?}"),
        }
    }

    #[test]
    fn parses_swiss_with_next_round() {
        let json = r#"{"id":"abc","name":"Weekly","clock":{"limit":300,"increment":0},
            "variant":"standard","round":2,"nbRounds":7,"nbPlayers":40,
            "status":"started","rated":true,"nextRound":{"at":1700000000000,"in":120}}"#;
        let swiss: LichessSwiss = serde_json::from_str(json).unwrap();
        assert_eq!(swiss.nb_rounds, Some(7));
        assert_eq!(swiss.next_round.unwrap().in_seconds, Some(120));
    }

    #[test]
    fn parses_swiss_result_with_fractional_points() {
        let json = r#"{"rank":1,"points":5.5,"tieBreak":18.0,"username":"A","rating":2400}"#;
        let result: LichessSwissResult = serde_json::from_str(json).unwrap();
        assert!((result.points - 5.5).abs() < f64::EPSILON);
    }

    #[test]
    fn conditions_serialize_to_dotted_keys() {
        let query = serde_urlencoded::to_string(
            SwissConditions::default()
                .max_rating(2200)
                .play_your_games(true),
        )
        .unwrap();
        assert!(query.contains("conditions.maxRating.rating=2200"));
        assert!(query.contains("conditions.playYourGames=true"));
    }

    #[test]
    fn empty_conditions_serialize_to_nothing() {
        assert_eq!(
            serde_urlencoded::to_string(SwissConditions::default()).unwrap(),
            ""
        );
    }

    #[test]
    fn round_interval_serializes_sentinels_and_seconds() {
        let cases = [
            (SwissRoundInterval::Auto, "roundInterval=-1"),
            (SwissRoundInterval::Manual, "roundInterval=99999999"),
            (SwissRoundInterval::Seconds(60), "roundInterval=60"),
        ];
        for (interval, expected) in cases {
            let form = serde_urlencoded::to_string([("roundInterval", interval)]).unwrap();
            assert_eq!(form, expected);
        }
    }
}