discid 0.7.0

Bindings for MusicBrainz libdiscid
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
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
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
// Copyright (C) 2019-2025 Philipp Wolfer <ph.wolfer@gmail.com>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

//! `discid` allows you to calculate MusicBrainz or FreeDB disc IDs for audio CDs.
//!
//! `discid` provides bindings to the MusicBrainz [libdiscid](https://musicbrainz.org/doc/libdiscid)
//! library. In addition to calculating the disc IDs you can also get advanced data from the
//! audio CD such as MCN (media catalogue number) and per-track ISRCs.
//!
//! To get started see the documentation and examples of [`DiscId::read`], [`DiscId::read_features`],
//! [`DiscId::put`] and [`DiscId::parse`].
//!
//! Details about the use and calculation of disc IDs can be found at the [MusicBrainz
//! disc ID documentation](https://musicbrainz.org/doc/Disc_ID).
//!
//! The source code of this library is available on [SourceHut](https://git.sr.ht/~phw/rust-discid)
//! under the terms of the GNU Lesser General Public License version 3 or later.
//!
//! [`DiscId::read`]: ./struct.DiscId.html#method.read
//! [`DiscId::read_features`]: ./struct.DiscId.html#method.read_features
//! [`DiscId::put`]: ./struct.DiscId.html#method.put
//! [`DiscId::parse`]: ./struct.DiscId.html#method.parse

#![deny(
    missing_docs,
    missing_debug_implementations,
    missing_copy_implementations,
    trivial_casts,
    trivial_numeric_casts,
    unstable_features,
    unused_import_braces,
    unused_qualifications,
    clippy::manual_assert
)]
#![warn(
    clippy::missing_errors_doc,
    clippy::missing_panics_doc,
    clippy::must_use_candidate,
    clippy::ptr_cast_constness,
    clippy::range_plus_one,
    clippy::undocumented_unsafe_blocks
)]

use discid_sys::*;
use std::error::Error;
use std::ffi::{CStr, CString};
use std::fmt;
use std::num::ParseIntError;
use std::os::raw::c_char;
use std::os::raw::c_int;
use std::ptr;
use std::rc::Rc;

#[macro_use]
extern crate bitflags;

bitflags! {
    /// Constants representing the features supported by libdiscid.
    ///
    /// See [`DiscId::read_features`] for details.
    ///
    /// [`DiscId::read_features`]: ./struct.DiscId.html#method.read_features
    #[derive(PartialEq, Debug)]
    pub struct Features: u32 {
        /// Read the CD TOC.
        ///
        /// This is supported on all platforms and indicates that only the
        /// table of contents (TOC), from which the disc ID gets calculated,
        /// will be read.
        const READ = discid_feature::DISCID_FEATURE_READ.0;

        /// Read the MCN (aka barcode) information.
        ///
        /// Read the MCN field from the CD. Not all CDs provide this information.
        /// Without this feature [`DiscId::mcn`] will always return an empty string.
        ///
        /// [`DiscId::mcn`]: ./struct.DiscId.html#method.mcn
        const MCN  = discid_feature::DISCID_FEATURE_MCN.0;

        /// Supports reading the ISRCs per track.
        ///
        /// For each track read the ISRC encoded in the subchannel data. Not all CDs provide this
        /// information. Without this feature [`Track::isrc`] will always be an empty string.
        ///
        /// [`Track::isrc`]: ./struct.Track.html#structfield.isrc
        const ISRC = discid_feature::DISCID_FEATURE_ISRC.0;
    }
}

impl From<Features> for discid_feature {
    fn from(item: Features) -> Self {
        Self(item.bits())
    }
}

/// This is returned on errors reading the disc or setting the TOC.
#[derive(Debug)]
#[must_use]
pub struct DiscError {
    reason: String,
}

impl DiscError {
    fn new(message: &str) -> Self {
        Self {
            reason: message.to_string(),
        }
    }
}

impl Error for DiscError {}

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

impl From<ParseIntError> for DiscError {
    fn from(err: ParseIntError) -> Self {
        Self {
            reason: err.to_string(),
        }
    }
}

#[derive(Debug)]
#[must_use]
struct DiscIdHandle {
    real_handle: ptr::NonNull<discid_sys::DiscId>,
}

impl DiscIdHandle {
    fn new(handle: *mut discid_sys::DiscId) -> Result<Self, DiscError> {
        if handle.is_null() {
            Err(DiscError::new("handle must not be null"))
        } else {
            // SAFETY: handle is non-null.
            unsafe {
                Ok(Self {
                    real_handle: ptr::NonNull::new_unchecked(handle),
                })
            }
        }
    }

    fn as_ptr(&self) -> *mut discid_sys::DiscId {
        self.real_handle.as_ptr()
    }
}

impl Drop for DiscIdHandle {
    fn drop(&mut self) {
        // SAFETY: DiscIdHandle.handle is always non-null.
        unsafe { discid_free(self.as_ptr()) }
    }
}

/// `DiscId` holds information about a disc (TOC, MCN, ISRCs).
///
/// Use [`DiscId::read`], [`DiscId::read_features`], [`DiscId::put`] or [`DiscId::parse`]
/// to initialize an instance of `DiscId`.
///
/// Internally this type uses libdiscid handles which must not be accessed
/// concurrently or moved across threads. Consequently, `DiscId` does not
/// implement `Send` or `Sync`.
///
/// [`DiscId::read`]: #method.read
/// [`DiscId::read_features`]: #method.read_features
/// [`DiscId::put`]: #method.put
/// [`DiscId::parse`]: #method.parse
#[must_use]
pub struct DiscId {
    handle: Rc<DiscIdHandle>,
}

impl DiscId {
    fn new() -> Result<Self, DiscError> {
        // SAFETY: FFI call with no preconditions.
        let handle = unsafe { discid_new() };
        if handle.is_null() {
            Err(DiscError::new(
                "discid_new() failed, could not allocate memory",
            ))
        } else {
            let result = DiscIdHandle::new(handle);
            match result {
                Ok(handle_t) => Ok(Self {
                    handle: Rc::new(handle_t),
                }),
                // This should never happen, as we checked handle for null
                // beforehand.
                Err(err) => Err(err),
            }
        }
    }

    /// Read the disc in the given CD-ROM/DVD-ROM drive extracting only the TOC.
    ///
    /// This function reads the disc in the drive specified by the given device
    /// identifier. If the device is `None`, the default device, as returned by
    /// [`DiscId::default_device`], is used.
    ///
    /// This function will only read the TOC, hence only the disc ID itself will be
    /// available. Use [`DiscId::read_features`] if you want to read also MCN and ISRCs.
    ///
    /// # Errors
    ///
    /// Will return `Err` if reading the disc failed for any reason, e.g. no CD drive
    /// available or no disc inserted.
    ///
    /// # Examples
    ///
    /// Read from default device
    /// ```no_run
    /// use discid::DiscId;
    ///
    /// let disc = DiscId::read(None).expect("Reading disc failed");
    /// println!("ID: {}", disc.id());
    /// ```
    ///
    /// Read from specific device
    /// ```no_run
    /// # use discid::DiscId;
    /// let disc = DiscId::read(Some("/dev/sr1")).expect("Reading disc failed");
    /// println!("ID: {}", disc.id());
    /// ```
    ///
    /// [`DiscId::read_features`]: #method.read_features
    /// [`DiscId::default_device`]: #method.default_device
    pub fn read(device: Option<&str>) -> Result<Self, DiscError> {
        Self::read_features(device, Features::READ)
    }

    /// Read the disc in the given CD-ROM/DVD-ROM drive with additional features.
    ///
    /// This function is similar to [`DiscId::read`] but allows to read information about MCN
    /// and per-track ISRCs in addition to the normal TOC data.
    ///
    /// The parameter `features` accepts a bitwise combination of values defined in [`Features`].
    /// [`Features::READ`] is always implied, so it is not necessary to specify it.
    ///
    /// Reading MCN and ISRCs is not available on all platforms. You can use the
    /// [`has_feature`] method to check if a specific feature is available. Passing unsupported
    /// features here will just be ignored.
    ///
    /// Note that reading MCN and ISRC data is significantly slower than just reading the TOC, so
    /// only request the features you actually need.
    ///
    /// # Errors
    ///
    /// Will return `Err` if reading the disc failed for any reason, e.g. no CD drive
    /// available or no disc inserted.
    ///
    /// # Examples
    ///
    /// Read both ISRC and MCN from default device
    /// ```no_run
    /// use discid::{DiscId, Features};
    ///
    /// let features = Features::MCN | Features::ISRC;
    /// let disc = DiscId::read_features(None, features).expect("Reading disc failed");
    /// println!("ID : {}", disc.id());
    /// println!("MCN: {}", disc.mcn());
    /// for track in disc.tracks() {
    ///     println!("#{} ISRC: {}", track.number, track.isrc);
    /// }
    /// ```
    ///
    /// [`DiscId::read`]: #method.read
    /// [`has_feature`]: #method.has_feature
    /// [`Features`]: ./struct.Features.html
    /// [`Features::READ`]: ./struct.Features.html#associatedconstant.READ
    pub fn read_features(device: Option<&str>, features: Features) -> Result<Self, DiscError> {
        let disc = Self::new()?;
        let c_device = device.map(|d| CString::new(d).unwrap_or_default());
        let c_device_ptr = c_device.as_ref().map_or(ptr::null(), |c| c.as_ptr());

        // SAFETY:
        // - disc.handle is always non-null.
        // - c_device is a proper null terminated C string or a null pointer.
        let status =
            unsafe { discid_read_sparse(disc.handle.as_ptr(), c_device_ptr, features.bits()) };
        if status == 0 {
            Err(disc.error())
        } else {
            Ok(disc)
        }
    }

    /// Provides the TOC of a known CD.
    ///
    /// This function may be used if the TOC has been read earlier and you want to calculate
    /// the disc ID afterwards, without accessing the disc drive.
    ///
    /// `first` is the track number of the first track (1-99).
    /// The `offsets` parameter points to an array which contains the track offsets for each track.
    /// The first element, `offsets[0]`, is the lead-out track. It must contain the total number of
    /// sectors on the disc. `offsets` must not be longer than 100 elements (lead-out + 99 tracks).
    ///
    /// # Errors
    ///
    /// Will return `Err` if the provided offsets are invalid.
    ///
    /// # Examples:
    ///
    /// ```
    /// use discid::DiscId;
    ///
    /// let first_track = 1;
    /// // The offsets contain the total number of sectors as first element, followed by
    /// // the start sectors of each track.
    /// let offsets = [
    ///    242457, 150, 44942, 61305, 72755, 96360, 130485, 147315, 164275, 190702, 205412, 220437,
    /// ];
    /// let disc = DiscId::put(first_track, &offsets).expect("DiscId::put() failed");
    /// assert_eq!("lSOVc5h6IXSuzcamJS1Gp4_tRuA-", disc.id());
    /// ```
    pub fn put(first: i32, offsets: &[i32]) -> Result<Self, DiscError> {
        let disc = Self::new()?;
        let last = first + offsets.len() as i32 - 2;
        let offset_ptr: *mut c_int;
        let mut full_offsets: [c_int; 100];

        if first > 1 && last <= 99 {
            // libdiscid always expects an array of 100 integers, no matter the track count.
            // If the first track is larger 1 empty tracks must be filled with 0.
            full_offsets = [0; 100];
            full_offsets[0] = offsets[0]; // Total sectors on disc
            full_offsets[first as usize..=last as usize].copy_from_slice(&offsets[1..]);
            offset_ptr = full_offsets.as_mut_ptr();
        } else {
            // In case the track count starts at 1 we do not have to copy the array.
            // libdiscid will not read beyond the boundary of `last`, which in our case
            // equals `offsets.length - 1` or less.
            offset_ptr = offsets.as_ptr().cast_mut();
        }

        // SAFETY:
        // - disc.handle is always non-null.
        // - first and last are validated by discid_put.
        // - the code above ensures offsets to be inside the bounds set by last.
        let status = unsafe { discid_put(disc.handle.as_ptr(), first, last, offset_ptr) };
        if status == 0 {
            Err(disc.error())
        } else {
            Ok(disc)
        }
    }

    /// Parses a TOC string and returns a [`DiscId`] instance for it.
    ///
    /// The TOC string provided here must have the same format as returned by [`toc_string`].
    ///
    /// This function can be used if you already have a TOC string like e.g.
    /// `1 11 242457 150 44942 61305 72755 96360 130485 147315 164275 190702 205412 220437`.
    ///
    /// # Errors
    ///
    /// Will return `Err` if the provided `toc` is invalid.
    ///
    /// # Examples:
    ///
    /// ```
    /// use discid::DiscId;
    ///
    /// let toc = "1 11 242457 150 44942 61305 72755 96360 130485 147315 164275 190702 205412 220437";
    /// let disc = DiscId::parse(toc).expect("DiscId::put() failed");
    /// assert_eq!("lSOVc5h6IXSuzcamJS1Gp4_tRuA-", disc.id());
    /// assert_eq!(toc, disc.toc_string());
    /// ```
    ///
    /// [`DiscId`]: ./struct.DiscId.html
    /// [`toc_string`]: #method.toc_string
    pub fn parse(toc: &str) -> Result<Self, DiscError> {
        let mut i: usize = 0;
        let mut first_track: c_int = 1;
        let mut last_track: c_int = 1;
        let mut offsets: [c_int; 100] = [0; 100];
        for part in toc.split(' ') {
            let parsed_int = part.parse::<c_int>()?;
            if i == 0 {
                first_track = parsed_int;
            } else if i == 1 {
                last_track = parsed_int;
            } else if i > 1 {
                if i > (last_track as usize + 2) || i > 99 + 2 {
                    return Err(DiscError::new(
                        "TOC string contains too many offsets (max. 100)",
                    ));
                }

                offsets[i - 2] = parsed_int;
            }

            i += 1;
        }

        if i < 3 {
            return Err(DiscError::new(&format!("Invalid TOC string {toc:?}")));
        }

        let offset_count = (i - 3) as c_int;
        let track_count = last_track - first_track + 1;
        if track_count != offset_count {
            return Err(DiscError::new(&format!(
                "Number of offsets {offset_count} does not match track count {track_count}",
            )));
        }

        Self::put(first_track, &offsets[0..(i - 2)])
    }

    /// Check if a certain feature is implemented on the current platform.
    ///
    /// Support for multiple features can be tested by providing a bit masks of features.
    /// The function will return true only if all features are supported.
    ///
    /// See the [libdiscid feature matrix](https://musicbrainz.org/doc/libdiscid#Feature_Matrix)
    /// for a list of supported features per platform.
    ///
    /// # Examples
    /// Check for a single feature:
    /// ```
    /// use discid::{DiscId, Features};
    ///
    /// let can_read = DiscId::has_feature(Features::READ);
    /// assert!(can_read);
    /// ```
    ///
    /// Check support of multiple features:
    /// ```no_run
    /// use discid::{DiscId, Features};
    ///
    /// let can_read = DiscId::has_feature(Features::READ | Features::ISRC);
    /// assert!(can_read);
    /// ```
    #[must_use]
    pub fn has_feature(feature: Features) -> bool {
        for feature in feature.iter() {
            // SAFETY: FFI call with no preconditions.
            let result = unsafe { discid_has_feature(feature.into()) };
            if result != 1 {
                return false;
            }
        }
        true
    }

    /// Return version information about libdiscid.
    ///
    /// The returned string will be e.g. `"libdiscid 0.6.2"`.
    ///
    /// # Examples
    /// ```
    /// use discid::DiscId;
    ///
    /// println!("{}", DiscId::version_string());
    /// ```
    #[must_use]
    pub fn version_string() -> String {
        // SAFETY: FFI call with no preconditions.
        let str_ptr = unsafe { discid_get_version_string() };
        to_str(str_ptr)
    }

    /// Return the name of the default disc drive for this operating system.
    ///
    /// The default device is system dependent, e.g. `/dev/cdrom` on Linux and `D:` on Windows.
    ///
    /// # Examples
    /// ```
    /// use discid::DiscId;
    ///
    /// println!("{}", DiscId::default_device());
    /// ```
    #[must_use]
    pub fn default_device() -> String {
        // SAFETY: FFI call with no preconditions.
        let version_ptr = unsafe { discid_get_default_device() };
        to_str(version_ptr)
    }

    fn error(&self) -> DiscError {
        // SAFETY: self.handle is always non-null.
        let str_ptr = unsafe { discid_get_error_msg(self.handle.as_ptr()) };
        DiscError::new(&to_str(str_ptr))
    }

    /// The MusicBrainz disc ID.
    #[must_use]
    pub fn id(&self) -> String {
        // SAFETY: self.handle is always non-null.
        let str_ptr = unsafe { discid_get_id(self.handle.as_ptr()) };
        to_str(str_ptr)
    }

    /// The FreeDB disc ID.
    #[must_use]
    pub fn freedb_id(&self) -> String {
        // SAFETY: self.handle is always non-null.
        let str_ptr = unsafe { discid_get_freedb_id(self.handle.as_ptr()) };
        to_str(str_ptr)
    }

    /// Return a string representing CD Table Of Contents (TOC).
    ///
    /// The TOC string is a list of integers separated by a single space character. The integers
    /// represent (in order):
    ///
    /// - First track number (normally one)
    /// - Last track number
    /// - Lead-out track offset
    /// - Up to 99 frame offsets
    ///
    /// See also [`DiscId::parse`] and the documentation for [Disc ID Calculation](https://musicbrainz.org/doc/Disc_ID_Calculation).
    ///
    /// [`DiscId::parse`]: #method.parse
    #[must_use]
    pub fn toc_string(&self) -> String {
        // SAFETY: self.handle is always non-null.
        let str_ptr = unsafe { discid_get_toc_string(self.handle.as_ptr()) };
        to_str(str_ptr)
    }

    /// An URL for submitting the DiscID to MusicBrainz.
    #[must_use]
    pub fn submission_url(&self) -> String {
        // SAFETY: self.handle is always non-null.
        let str_ptr = unsafe { discid_get_submission_url(self.handle.as_ptr()) };
        to_str(str_ptr)
    }

    /// The number of the first track on this disc.
    #[must_use]
    pub fn first_track_num(&self) -> i32 {
        // SAFETY: self.handle is always non-null.
        unsafe { discid_get_first_track_num(self.handle.as_ptr()) }
    }

    /// The number of the last track on this disc.
    #[must_use]
    pub fn last_track_num(&self) -> i32 {
        // SAFETY: self.handle is always non-null.
        unsafe { discid_get_last_track_num(self.handle.as_ptr()) }
    }

    /// The length of the disc in sectors.
    #[must_use]
    pub fn sectors(&self) -> i32 {
        // SAFETY: self.handle is always non-null.
        unsafe { discid_get_sectors(self.handle.as_ptr()) }
    }

    /// The media catalogue number on the disc, if present.
    #[must_use]
    pub fn mcn(&self) -> String {
        // SAFETY: self.handle is always non-null.
        let str_ptr = unsafe { discid_get_mcn(self.handle.as_ptr()) };
        to_str(str_ptr)
    }

    /// Returns an iterator to access information about each track on the disc.
    ///
    /// Returns an instance of [`Track`] for each track.
    ///
    /// # Examples
    ///
    /// ```
    /// use discid::DiscId;
    ///
    /// let offsets = [
    ///    242457, 150, 44942, 61305, 72755, 96360, 130485, 147315, 164275, 190702, 205412, 220437,
    /// ];
    /// let disc = DiscId::put(1, &offsets).expect("DiscId::put() failed");
    /// for track in disc.tracks() {
    ///     println!("Track #{}", track.number);
    ///     println!("    ISRC    : {}", track.isrc);
    ///     println!("    Offset  : {}", track.offset);
    ///     println!("    Sectors : {}", track.sectors);
    /// }
    /// ```
    ///
    /// [`Track`]: ./struct.Track.html
    pub fn tracks(&self) -> TrackIter {
        TrackIter::new(Rc::clone(&self.handle))
    }

    /// Returns information about a specific track on the disc.
    ///
    /// This method retrieves a [`Track`] instance for the given track number, if it
    /// exists on the disc. If the requested track number is outside the valid range of
    /// [`first_track_num`] to [`last_track_num`], `None` is returned.
    ///
    /// # Parameters
    ///
    /// - `number`: The track number (1-99) you want to access.
    ///
    /// # Returns
    ///
    /// - `Some(Track)` if the track exists.
    /// - `None` if the track number is out of bounds.
    ///
    /// # Examples
    ///
    /// ```
    /// use discid::DiscId;
    ///
    /// let offsets = [242457, 150, 44942, 61305, 72755];
    /// let disc = DiscId::put(1, &offsets).expect("DiscId::put() failed");
    ///
    /// if let Some(track) = disc.get_track(3) {
    ///     println!("Track #{} offset: {}", track.number, track.offset);
    /// } else {
    ///     println!("Track not found");
    /// }
    /// ```
    ///
    /// [`Track`]: ./struct.Track.html
    /// [`first_track_num`]: #method.first_track_num
    /// [`last_track_num`]: #method.last_track_num
    #[must_use]
    pub fn get_track(&self, number: i32) -> Option<Track> {
        if self.is_valid_track_number(number) {
            Some(get_track(Rc::clone(&self.handle), number))
        } else {
            None
        }
    }

    /// Returns a [`Track`] instance for the nth track.
    ///
    /// # Panics
    /// Panics if `number` is outside the range given by [`first_track_num`]
    /// and [`last_track_num`].
    ///
    /// Consider using [`get_track`] for accessing tracks without the possibility
    /// of panicking.
    ///
    /// # Examples
    ///
    /// ```
    /// use discid::DiscId;
    ///
    /// let offsets = [
    ///    242457, 150, 44942, 61305, 72755, 96360, 130485, 147315, 164275, 190702, 205412, 220437,
    /// ];
    /// let disc = DiscId::put(1, &offsets).expect("DiscId::put() failed");
    /// let track = disc.nth_track(7);
    /// assert_eq!(7, track.number);
    /// assert_eq!(147315, track.offset);
    /// assert_eq!(16960, track.sectors);
    /// ```
    ///
    /// [`Track`]: ./struct.Track.html
    /// [`first_track_num`]: #method.first_track_num
    /// [`last_track_num`]: #method.last_track_num
    /// [`get_track`]: #method.get_track
    pub fn nth_track(&self, number: i32) -> Track {
        assert!(
            self.is_valid_track_number(number),
            "track number out of bounds: {number}"
        );
        get_track(Rc::clone(&self.handle), number)
    }

    fn is_valid_track_number(&self, number: i32) -> bool {
        let first = self.first_track_num();
        let last = self.last_track_num();
        number >= first && number <= last
    }
}

impl fmt::Debug for DiscId {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "DiscId {}", self.toc_string())
    }
}

/// Holds information about a single track
#[derive(Debug)]
#[must_use]
pub struct Track {
    /// Track number (1-99) of the track.
    pub number: i32,

    /// Start offset in sectors.
    pub offset: i32,

    /// Track length in sectors.
    pub sectors: i32,

    /// ISRC for this track (might be empty).
    ///
    /// This will only bet set if [`DiscId::read_features`] is called with [`Features::ISRC`].
    ///
    /// [`DiscId::read_features`]: ./struct.DiscId.html#method.read_features
    /// [`Features::ISRC`]: ./struct.Features.html#associatedconstant.ISRC
    pub isrc: String,
}

/// Allows iterating over all tracks of a read disc.
///
/// Returns an instance of [`Track`] for each track.
///
/// [`Track`]: ./struct.Track.html
#[derive(Debug)]
#[must_use]
pub struct TrackIter {
    handle: Rc<DiscIdHandle>,
    curr: i32,
    last_track: i32,
}

impl TrackIter {
    fn new(handle: Rc<DiscIdHandle>) -> Self {
        let handle_ptr = handle.as_ptr();
        // SAFETY: self.handle is always non-null.
        let first_track = unsafe { discid_get_first_track_num(handle_ptr) };
        // SAFETY: See previous comment.
        let last_track = unsafe { discid_get_last_track_num(handle_ptr) };
        Self {
            handle,
            curr: first_track,
            last_track,
        }
    }
}

impl Iterator for TrackIter {
    type Item = Track;

    fn next(&mut self) -> Option<Track> {
        let track_num = self.curr;
        self.curr += 1;
        if track_num <= self.last_track {
            Some(get_track(Rc::clone(&self.handle), track_num))
        } else {
            None
        }
    }
}

fn get_track(handle: Rc<DiscIdHandle>, number: i32) -> Track {
    let handle_ptr = handle.as_ptr();
    // SAFETY:
    // - self.handle is always non-null.
    // - track number is validated by libdiscid.
    let isrc_ptr = unsafe { discid_get_track_isrc(handle_ptr, number) };
    Track {
        number,
        // SAFETY: See previous comment.
        offset: unsafe { discid_get_track_offset(handle_ptr, number) },
        // SAFETY: See previous comment.
        sectors: unsafe { discid_get_track_length(handle_ptr, number) },
        isrc: to_str(isrc_ptr),
    }
}

fn to_str(c_buf: *const c_char) -> String {
    if c_buf.is_null() {
        return String::new();
    }

    // SAFETY: The caller has provided a pointer that points to a valid C string.
    let c_str: &CStr = unsafe { CStr::from_ptr(c_buf) };
    let str_slice = c_str.to_string_lossy();
    str_slice.into_owned()
}

#[cfg(test)]
mod tests {
    use super::{DiscError, DiscId, Features, Track};

    #[test]
    #[ignore = "requires a CD inserted into the default CD drive"]
    fn discid_read_default_device() {
        let disc = DiscId::read(None).expect("DiscId::read failed");
        assert_eq!(28, disc.id().len());
    }

    #[test]
    fn discid_read_invalid_device() {
        let err = DiscId::read(Some("notadevice")).expect_err("DiscId::read failed");
        assert!(err.to_string().contains("cannot open"));
    }

    #[test]
    #[ignore = "requires a CD containing MCN and ISRC info inserted into the default CD drive"]
    #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
    fn discid_read_features_all() {
        let disc =
            DiscId::read_features(None, Features::all()).expect("DiscId::read_features failed");
        assert_eq!(28, disc.id().len());
        assert!(!disc.mcn().is_empty());
        assert_eq!(12, disc.nth_track(1).isrc.len());
    }

    #[test]
    fn discid_read_features_invalid_device() {
        let err = DiscId::read_features(Some("notadevice"), Features::READ)
            .expect_err("DiscId::read_features failed");
        assert!(err.to_string().contains("cannot open"));
    }

    #[test]
    fn discid_put() {
        let first = 1;
        let offsets = [
            206535, 150, 18901, 39738, 59557, 79152, 100126, 124833, 147278, 166336, 182560,
        ];
        let disc = DiscId::put(first, &offsets).expect("DiscId::put failed");
        let last_track = disc.last_track_num();
        assert_eq!("Wn8eRBtfLDfM0qjYPdxrz.Zjs_U-", disc.id());
        assert_eq!("830abf0a", disc.freedb_id());
        assert_eq!(1, disc.first_track_num());
        assert_eq!(10, last_track);
        assert_eq!(206535, disc.sectors());
        assert_eq!(
            "1 10 206535 150 18901 39738 59557 79152 100126 124833 147278 166336 182560",
            disc.toc_string()
        );
        assert_eq!(
            "http://musicbrainz.org/cdtoc/attach?id=Wn8eRBtfLDfM0qjYPdxrz.Zjs_U-&tracks=10&toc=1+10+206535+150+18901+39738+59557+79152+100126+124833+147278+166336+182560",
            disc.submission_url()
        );
        for track in disc.tracks() {
            let offset = offsets[track.number as usize];
            let next = if track.number < last_track {
                track.number + 1
            } else {
                0
            };
            let length = offsets[next as usize] - offset;
            assert_eq!(
                offset, track.offset,
                "track {} expected offset {}",
                track.number, offset
            );
            assert_eq!(
                length, track.sectors,
                "track {} expected sectors {}",
                track.number, length
            );
        }
    }

    #[test]
    fn discid_put_first_track_not_one() {
        let first = 3;
        let offsets = [
            206535, 150, 18901, 39738, 59557, 79152, 100126, 124833, 147278, 166336, 182560,
        ];
        let disc = DiscId::put(first, &offsets).expect("DiscId::put failed");
        assert_eq!("ByBKvJM1hBL7XtvsPyYtIjlX0Bw-", disc.id());
        assert_eq!(3, disc.first_track_num());
        assert_eq!(12, disc.last_track_num());
        assert_eq!(206535, disc.sectors());
    }

    #[test]
    fn discid_put_too_many_offsets() {
        let first = 1;
        let offsets: [i32; 101] = [0; 101];
        let err = DiscId::put(first, &offsets).expect_err("DiscId::put failed");
        assert!(err.to_string().contains("Illegal track limits"));
    }

    #[test]
    fn discid_put_too_many_tracks() {
        let first = 11;
        let offsets: [i32; 101] = [0; 101];
        let err = DiscId::put(first, &offsets).expect_err("DiscId::put failed");
        assert!(err.to_string().contains("Illegal track limits"));
    }

    #[test]
    fn discid_parse() {
        let toc =
            "1 11 242457 150 44942 61305 72755 96360 130485 147315 164275 190702 205412 220437";
        let disc = DiscId::parse(toc).expect("DiscId::parse failed");
        assert_eq!("lSOVc5h6IXSuzcamJS1Gp4_tRuA-", disc.id());
        assert_eq!(toc, disc.toc_string());
    }

    #[test]
    fn discid_parse_minimal() {
        let toc = "1 1 44942 150";
        let disc = DiscId::parse(toc).expect("DiscId::parse failed");
        assert_eq!("ANJa4DGYN_ktpzOwvVPtcjwP7mE-", disc.id());
        assert_eq!(toc, disc.toc_string());
    }

    #[test]
    fn discid_parse_first_track_not_one() {
        let toc = "3 12 242457 150 18901 39738 59557 79152 100126 124833 147278 166336 182560";
        let disc = DiscId::parse(toc).expect("DiscId::parse failed");
        assert_eq!("fC1yNbC5bVjbvphqlAY9JyYoWEY-", disc.id());
        assert_eq!(toc, disc.toc_string());
    }

    #[test]
    fn discid_parse_invalid_nan() {
        let toc = "1 2 242457 150 a";
        let err = DiscId::parse(toc).expect_err("DiscId::parse failed");
        assert!(err.to_string().contains("invalid digit found in string"));
    }

    #[test]
    fn discid_parse_invalid_too_many_offsets() {
        let toc = "1 2 242457 150 200 300";
        let err = DiscId::parse(toc).expect_err("DiscId::parse failed");
        assert!(
            err.to_string()
                .contains("TOC string contains too many offsets")
        );
    }

    #[test]
    fn discid_parse_invalid_too_many_offsets_total() {
        let mut indexes = vec!["0"; 103];
        indexes[0] = "1";
        indexes[1] = "100";
        let toc = indexes.join(" ");
        let err = DiscId::parse(&toc).expect_err("DiscId::parse failed");
        assert!(
            err.to_string()
                .contains("TOC string contains too many offsets")
        );
    }

    #[test]
    fn discid_parse_invalid_missing_offsets() {
        let toc = "1 2 242457 150";
        let err = DiscId::parse(toc).expect_err("DiscId::parse failed");
        assert!(
            err.to_string()
                .contains("Number of offsets 1 does not match track count 2")
        );
    }

    #[test]
    fn discid_parse_invalid_not_enough_elements() {
        let toc = "1";
        let err = DiscId::parse(toc).expect_err("DiscId::parse failed");
        assert!(err.to_string().contains("Invalid TOC string"));
    }

    #[test]
    fn discid_parse_invalid_empty() {
        let toc = "";
        let err = DiscId::parse(toc).expect_err("DiscId::parse failed");
        assert!(
            err.to_string()
                .contains("cannot parse integer from empty string")
        );
    }

    #[test]
    fn discid_get_track() {
        let offsets = [242457, 150, 44942, 61305, 72755];
        let disc = DiscId::put(1, &offsets).expect("DiscId::put() failed");
        assert!(disc.get_track(0).is_none());
        assert!(disc.get_track(1).is_some());
        assert!(disc.get_track(4).is_some());
        assert!(disc.get_track(5).is_none());
        let track = disc.get_track(2).unwrap();
        assert_eq!(2, track.number);
        assert_eq!(offsets[2], track.offset);
        assert_eq!(offsets[3] - offsets[2], track.sectors);
    }

    #[test]
    fn discid_nth_track() {
        let first = 1;
        let offsets = [
            206535, 150, 18901, 39738, 59557, 79152, 100126, 124833, 147278, 166336, 182560,
        ];
        let disc = DiscId::put(first, &offsets).expect("DiscId::put failed");
        let track = disc.nth_track(4);
        let expected_offset = offsets[4];
        let expected_sectors = offsets[5] - offsets[4];
        assert_eq!(4, track.number);
        assert_eq!("", track.isrc); // Always empty for DiscId::put
        assert_eq!(
            expected_offset, track.offset,
            "track {} expected offset {}",
            track.number, expected_offset
        );
        assert_eq!(
            expected_sectors, track.sectors,
            "track {} expected sectors {}",
            track.number, expected_sectors
        );
    }

    #[test]
    #[should_panic(expected = "track number out of bounds: 11")]
    fn discid_nth_track_out_of_bounds() {
        let first = 1;
        let offsets = [
            206535, 150, 18901, 39738, 59557, 79152, 100126, 124833, 147278, 166336, 182560,
        ];
        let disc = DiscId::put(first, &offsets).expect("DiscId::put failed");
        let _ = disc.nth_track(11);
    }

    #[test]
    fn discid_default_device() {
        let device = DiscId::default_device();
        assert!(!device.is_empty());
    }

    #[test]
    fn discid_has_feature() {
        assert_eq!(true, DiscId::has_feature(Features::READ));
    }

    #[test]
    #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
    fn discid_has_feature_all() {
        assert_eq!(true, DiscId::has_feature(Features::READ));
        assert_eq!(true, DiscId::has_feature(Features::MCN));
        assert_eq!(true, DiscId::has_feature(Features::ISRC));
        assert_eq!(true, DiscId::has_feature(Features::all()));
    }

    #[test]
    fn discid_version_string() {
        let version = DiscId::version_string();
        assert!(version.starts_with("libdiscid"));
    }

    #[test]
    fn discid_debug() {
        let first = 1;
        let offsets = [2000, 150, 1000];
        let disc = DiscId::put(first, &offsets).expect("DiscId::put failed");
        assert_eq!("DiscId 1 2 2000 150 1000", format!("{:?}", disc));
    }

    #[test]
    fn features() {
        assert_eq!(3, (Features::READ | Features::MCN).bits());
        assert_eq!(
            Features::all(),
            Features::READ | Features::MCN | Features::ISRC
        );
    }

    #[test]
    fn track_debug() {
        let track = Track {
            number: 3,
            offset: 57402,
            sectors: 32960,
            isrc: "DED831801578".to_string(),
        };

        assert_eq!(
            "Track { number: 3, offset: 57402, sectors: 32960, isrc: \"DED831801578\" }",
            format!("{:?}", track)
        );
    }

    #[test]
    fn disc_error_new() {
        let message = "The message";
        let error = DiscError::new(message);
        assert_eq!(message, error.reason);
    }

    #[test]
    fn disc_error_fmt() {
        let error = DiscError::new("The message");
        assert_eq!("DiscError: The message", error.to_string());
    }

    #[test]
    fn disc_error_debug() {
        let error = DiscError::new("The message");
        assert_eq!(
            "DiscError { reason: \"The message\" }",
            format!("{:?}", error)
        );
    }
}