cdx-core 0.7.1

Core library for reading, writing, and validating Codex Document Format (.cdx) files
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
//! Bibliography management for academic documents.

use serde::{Deserialize, Serialize};

/// A bibliography containing all references cited in a document.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Bibliography {
    /// Citation style used for formatting.
    #[serde(default)]
    pub style: CitationStyle,

    /// Bibliography entries.
    pub entries: Vec<BibliographyEntry>,
}

impl Bibliography {
    /// Create a new empty bibliography.
    #[must_use]
    pub fn new(style: CitationStyle) -> Self {
        Self {
            style,
            entries: Vec::new(),
        }
    }

    /// Add an entry to the bibliography.
    pub fn add_entry(&mut self, entry: BibliographyEntry) {
        self.entries.push(entry);
    }

    /// Find an entry by its ID.
    #[must_use]
    pub fn get(&self, id: &str) -> Option<&BibliographyEntry> {
        self.entries.iter().find(|e| e.id == id)
    }

    /// Check if the bibliography contains an entry with the given ID.
    #[must_use]
    pub fn contains(&self, id: &str) -> bool {
        self.entries.iter().any(|e| e.id == id)
    }

    /// Get the number of entries.
    #[must_use]
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Check if the bibliography is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }
}

impl Default for Bibliography {
    fn default() -> Self {
        Self::new(CitationStyle::default())
    }
}

/// Citation style for formatting references.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, strum::Display)]
#[serde(rename_all = "lowercase")]
pub enum CitationStyle {
    /// APA (American Psychological Association) style.
    #[default]
    #[strum(serialize = "APA")]
    Apa,
    /// MLA (Modern Language Association) style.
    #[strum(serialize = "MLA")]
    Mla,
    /// Chicago Manual of Style.
    Chicago,
    /// IEEE style.
    #[strum(serialize = "IEEE")]
    Ieee,
    /// Harvard style.
    Harvard,
    /// Vancouver style.
    Vancouver,
    /// ACM style.
    #[strum(serialize = "ACM")]
    Acm,
    /// Custom style (implementation-defined).
    Custom,
}

/// A bibliography entry representing a single reference.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BibliographyEntry {
    /// Unique identifier for the entry (used in citations).
    pub id: String,

    /// Type of the entry.
    pub entry_type: EntryType,

    /// Title of the work.
    pub title: String,

    /// Authors of the work.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub authors: Vec<Author>,

    /// Publication date.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub issued: Option<PartialDate>,

    /// Container title (e.g., journal name, book title for chapters).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub container_title: Option<String>,

    /// Volume number.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub volume: Option<String>,

    /// Issue number.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub issue: Option<String>,

    /// Page range.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub page: Option<String>,

    /// Digital Object Identifier.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub doi: Option<String>,

    /// URL to the work.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,

    /// ISBN for books.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub isbn: Option<String>,

    /// ISSN for journals.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub issn: Option<String>,

    /// Publisher name.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub publisher: Option<String>,

    /// Publication location.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub publisher_place: Option<String>,

    /// Edition number or description.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub edition: Option<String>,

    /// Editors (for edited volumes).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub editors: Vec<Author>,

    /// Abstract text.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub abstract_text: Option<String>,

    /// Keywords or tags.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub keywords: Vec<String>,

    /// Language of the work.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub language: Option<String>,

    /// Access date for online resources.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub accessed: Option<PartialDate>,

    /// Additional notes.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub note: Option<String>,
}

impl BibliographyEntry {
    /// Create a new bibliography entry.
    #[must_use]
    pub fn new(id: impl Into<String>, entry_type: EntryType, title: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            entry_type,
            title: title.into(),
            authors: Vec::new(),
            issued: None,
            container_title: None,
            volume: None,
            issue: None,
            page: None,
            doi: None,
            url: None,
            isbn: None,
            issn: None,
            publisher: None,
            publisher_place: None,
            edition: None,
            editors: Vec::new(),
            abstract_text: None,
            keywords: Vec::new(),
            language: None,
            accessed: None,
            note: None,
        }
    }

    /// Add an author.
    #[must_use]
    pub fn with_author(mut self, author: Author) -> Self {
        self.authors.push(author);
        self
    }

    /// Add multiple authors.
    #[must_use]
    pub fn with_authors(mut self, authors: Vec<Author>) -> Self {
        self.authors = authors;
        self
    }

    /// Set the publication date.
    #[must_use]
    pub fn with_issued(mut self, date: PartialDate) -> Self {
        self.issued = Some(date);
        self
    }

    /// Set the container title.
    #[must_use]
    pub fn with_container(mut self, container: impl Into<String>) -> Self {
        self.container_title = Some(container.into());
        self
    }

    /// Set volume and issue.
    #[must_use]
    pub fn with_volume_issue(mut self, volume: impl Into<String>, issue: Option<String>) -> Self {
        self.volume = Some(volume.into());
        self.issue = issue;
        self
    }

    /// Set page range.
    #[must_use]
    pub fn with_pages(mut self, pages: impl Into<String>) -> Self {
        self.page = Some(pages.into());
        self
    }

    /// Set DOI.
    #[must_use]
    pub fn with_doi(mut self, doi: impl Into<String>) -> Self {
        self.doi = Some(doi.into());
        self
    }

    /// Set URL.
    #[must_use]
    pub fn with_url(mut self, url: impl Into<String>) -> Self {
        self.url = Some(url.into());
        self
    }

    /// Set publisher information.
    #[must_use]
    pub fn with_publisher(mut self, publisher: impl Into<String>, place: Option<String>) -> Self {
        self.publisher = Some(publisher.into());
        self.publisher_place = place;
        self
    }
}

/// Type of bibliography entry.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, strum::Display)]
#[serde(rename_all = "camelCase")]
#[strum(serialize_all = "lowercase")]
pub enum EntryType {
    /// Journal article.
    Article,
    /// Book.
    Book,
    /// Chapter in a book.
    Chapter,
    /// Conference paper.
    Conference,
    /// Thesis or dissertation.
    Thesis,
    /// Technical report.
    Report,
    /// Website or webpage.
    Webpage,
    /// Patent.
    Patent,
    /// Dataset.
    Dataset,
    /// Software.
    Software,
    /// Legal case.
    #[strum(serialize = "legal-case")]
    LegalCase,
    /// Legislation or statute.
    Legislation,
    /// Personal communication.
    Personal,
    /// Manuscript.
    Manuscript,
    /// Other type.
    Other,
}

/// An author or contributor.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Author {
    /// Given name (first name).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub given: Option<String>,

    /// Family name (last name).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub family: Option<String>,

    /// Full literal name (for non-standard names or organizations).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub literal: Option<String>,

    /// ORCID identifier.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub orcid: Option<String>,

    /// Affiliation.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub affiliation: Option<String>,
}

impl Author {
    /// Create an author from given and family names.
    #[must_use]
    pub fn new(given: impl Into<String>, family: impl Into<String>) -> Self {
        Self {
            given: Some(given.into()),
            family: Some(family.into()),
            literal: None,
            orcid: None,
            affiliation: None,
        }
    }

    /// Create an author from a literal name (e.g., organization).
    #[must_use]
    pub fn literal(name: impl Into<String>) -> Self {
        Self {
            given: None,
            family: None,
            literal: Some(name.into()),
            orcid: None,
            affiliation: None,
        }
    }

    /// Set ORCID.
    #[must_use]
    pub fn with_orcid(mut self, orcid: impl Into<String>) -> Self {
        self.orcid = Some(orcid.into());
        self
    }

    /// Set affiliation.
    #[must_use]
    pub fn with_affiliation(mut self, affiliation: impl Into<String>) -> Self {
        self.affiliation = Some(affiliation.into());
        self
    }

    /// Get the display name.
    #[must_use]
    pub fn display_name(&self) -> String {
        if let Some(literal) = &self.literal {
            return literal.clone();
        }
        match (&self.family, &self.given) {
            (Some(family), Some(given)) => format!("{family}, {given}"),
            (Some(family), None) => family.clone(),
            (None, Some(given)) => given.clone(),
            (None, None) => String::new(),
        }
    }
}

/// A partial date (year, year-month, or full date).
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PartialDate {
    /// Year.
    pub year: i32,

    /// Month (1-12).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub month: Option<u8>,

    /// Day (1-31).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub day: Option<u8>,

    /// Season (for quarterly publications).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub season: Option<String>,
}

impl PartialDate {
    /// Create a year-only date.
    #[must_use]
    pub const fn year(year: i32) -> Self {
        Self {
            year,
            month: None,
            day: None,
            season: None,
        }
    }

    /// Create a year-month date.
    ///
    /// Note: `month` should be in the range 1-12. Use [`Self::try_year_month`]
    /// for validated construction.
    #[must_use]
    pub const fn year_month(year: i32, month: u8) -> Self {
        Self {
            year,
            month: Some(month),
            day: None,
            season: None,
        }
    }

    /// Create a year-month date with validation.
    ///
    /// # Errors
    ///
    /// Returns an error if month is not in the range 1-12.
    pub fn try_year_month(year: i32, month: u8) -> Result<Self, String> {
        if !(1..=12).contains(&month) {
            return Err(format!("month must be 1-12, got {month}"));
        }
        Ok(Self::year_month(year, month))
    }

    /// Create a full date.
    ///
    /// Note: `month` should be 1-12 and `day` should be 1-31.
    /// Use [`Self::try_full`] for validated construction.
    #[must_use]
    pub const fn full(year: i32, month: u8, day: u8) -> Self {
        Self {
            year,
            month: Some(month),
            day: Some(day),
            season: None,
        }
    }

    /// Create a full date with validation.
    ///
    /// # Errors
    ///
    /// Returns an error if month is not 1-12 or day is not 1-31.
    pub fn try_full(year: i32, month: u8, day: u8) -> Result<Self, String> {
        if !(1..=12).contains(&month) {
            return Err(format!("month must be 1-12, got {month}"));
        }
        if !(1..=31).contains(&day) {
            return Err(format!("day must be 1-31, got {day}"));
        }
        Ok(Self::full(year, month, day))
    }

    /// Create a seasonal date.
    #[must_use]
    pub fn seasonal(year: i32, season: impl Into<String>) -> Self {
        Self {
            year,
            month: None,
            day: None,
            season: Some(season.into()),
        }
    }
}

impl<'de> Deserialize<'de> for PartialDate {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(Deserialize)]
        #[serde(rename_all = "camelCase")]
        struct Raw {
            year: i32,
            #[serde(default)]
            month: Option<u8>,
            #[serde(default)]
            day: Option<u8>,
            #[serde(default)]
            season: Option<String>,
        }
        let raw = Raw::deserialize(deserializer)?;
        if let Some(m) = raw.month {
            if !(1..=12).contains(&m) {
                return Err(serde::de::Error::custom(format!(
                    "month must be 1-12, got {m}"
                )));
            }
        }
        if let Some(d) = raw.day {
            if !(1..=31).contains(&d) {
                return Err(serde::de::Error::custom(format!(
                    "day must be 1-31, got {d}"
                )));
            }
        }
        Ok(PartialDate {
            year: raw.year,
            month: raw.month,
            day: raw.day,
            season: raw.season,
        })
    }
}

impl std::fmt::Display for PartialDate {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if let Some(season) = &self.season {
            return write!(f, "{} {}", season, self.year);
        }
        match (self.month, self.day) {
            (Some(month), Some(day)) => write!(f, "{}-{:02}-{:02}", self.year, month, day),
            (Some(month), None) => write!(f, "{}-{:02}", self.year, month),
            _ => write!(f, "{}", self.year),
        }
    }
}

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

    #[test]
    fn test_try_year_month_valid() {
        assert!(PartialDate::try_year_month(2024, 1).is_ok());
        assert!(PartialDate::try_year_month(2024, 12).is_ok());
    }

    #[test]
    fn test_try_year_month_invalid() {
        assert!(PartialDate::try_year_month(2024, 0).is_err());
        assert!(PartialDate::try_year_month(2024, 13).is_err());
    }

    #[test]
    fn test_try_full_valid() {
        assert!(PartialDate::try_full(2024, 6, 15).is_ok());
    }

    #[test]
    fn test_try_full_invalid() {
        assert!(PartialDate::try_full(2024, 0, 15).is_err());
        assert!(PartialDate::try_full(2024, 6, 0).is_err());
        assert!(PartialDate::try_full(2024, 6, 32).is_err());
    }

    #[test]
    fn test_partial_date_deser_rejects_invalid_month() {
        let json = r#"{"year":2024,"month":13}"#;
        let result: Result<PartialDate, _> = serde_json::from_str(json);
        assert!(result.is_err());
    }

    #[test]
    fn test_partial_date_deser_rejects_invalid_day() {
        let json = r#"{"year":2024,"month":6,"day":32}"#;
        let result: Result<PartialDate, _> = serde_json::from_str(json);
        assert!(result.is_err());
    }

    #[test]
    fn test_partial_date_deser_accepts_valid() {
        let json = r#"{"year":2024,"month":6,"day":15}"#;
        let result: PartialDate = serde_json::from_str(json).unwrap();
        assert_eq!(result.year, 2024);
        assert_eq!(result.month, Some(6));
        assert_eq!(result.day, Some(15));
    }
}