mrrc 0.7.6

A Rust library for reading, writing, and manipulating MARC bibliographic records in ISO 2709 binary format
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
//! Format-specific query traits for different MARC record types.
//!
//! This module provides specialized query traits for bibliographic, authority,
//! and holdings records, enabling domain-specific helper methods tailored to
//! each record type's purpose.

use crate::authority_record::AuthorityRecord;
use crate::holdings_record::HoldingsRecord;
use crate::record::{Field, Record};

/// Query helpers specific to bibliographic records.
///
/// This trait provides methods for navigating and querying bibliographic-specific
/// fields like titles, authors, subjects, and linked field information.
pub trait BibliographicQueries {
    /// Get all main titles and their statement of responsibility (245 fields).
    ///
    /// In MARC, there is typically only one 245 field, but this method returns
    /// any additional title fields that may be present.
    ///
    /// # Returns
    ///
    /// Vector of title fields (245) with their indicators and subfields.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let record = Record::new(leader);
    /// for title_field in record.get_titles() {
    ///     if let Some(title) = title_field.get_subfield('a') {
    ///         println!("Title: {}", title);
    ///     }
    /// }
    /// ```
    #[must_use]
    fn get_titles(&self) -> Vec<&Field>;

    /// Get all subject fields (6XX range).
    ///
    /// Returns all subject authority fields including:
    /// - 600: Personal name subject
    /// - 610: Corporate name subject
    /// - 611: Meeting name subject
    /// - 630: Uniform title subject
    /// - 648: Chronological term subject
    /// - 650: Topical term subject
    /// - 651: Geographic name subject
    /// - 655: Genre/form term
    ///
    /// # Returns
    ///
    /// Vector of all subject fields in the record.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let record = Record::new(leader);
    /// for subject in record.get_all_subjects() {
    ///     if let Some(label) = subject.get_subfield('a') {
    ///         println!("Subject: {}", label);
    ///     }
    /// }
    /// ```
    #[must_use]
    fn get_all_subjects(&self) -> Vec<&Field>;

    /// Get all topical subjects (650 fields).
    ///
    /// Topical subjects describe the main subject content of the work.
    ///
    /// # Returns
    ///
    /// Vector of all 650 fields in the record.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let record = Record::new(leader);
    /// for subject in record.get_topical_subjects() {
    ///     if let Some(term) = subject.get_subfield('a') {
    ///         println!("Topic: {}", term);
    ///     }
    /// }
    /// ```
    #[must_use]
    fn get_topical_subjects(&self) -> Vec<&Field>;

    /// Get all geographic subjects (651 fields).
    ///
    /// Geographic subjects describe places discussed or depicted in the work.
    ///
    /// # Returns
    ///
    /// Vector of all 651 fields in the record.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let record = Record::new(leader);
    /// for subject in record.get_geographic_subjects() {
    ///     if let Some(place) = subject.get_subfield('a') {
    ///         println!("Place: {}", place);
    ///     }
    /// }
    /// ```
    #[must_use]
    fn get_geographic_subjects(&self) -> Vec<&Field>;

    /// Get all name fields (1XX, 6XX name fields, 7XX).
    ///
    /// Returns all name-based fields including:
    /// - 100: Main entry—personal name
    /// - 600: Subject added entry—personal name
    /// - 610: Subject added entry—corporate name
    /// - 611: Subject added entry—meeting name
    /// - 700: Added entry—personal name
    /// - 710: Added entry—corporate name
    /// - 711: Added entry—meeting name
    ///
    /// # Returns
    ///
    /// Vector of all name fields in the record.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let record = Record::new(leader);
    /// for name in record.get_all_names() {
    ///     if let Some(label) = name.get_subfield('a') {
    ///         println!("Name: {}", label);
    ///     }
    /// }
    /// ```
    #[must_use]
    fn get_all_names(&self) -> Vec<&Field>;

    /// Get linked field pairs (original field with optional 880 counterpart).
    ///
    /// For a specified tag, returns tuples of the original field paired with its
    /// linked 880 (alternate graphical representation) if one exists.
    ///
    /// # Arguments
    ///
    /// * `tag` - The original field tag (e.g., "100", "245", "650")
    ///
    /// # Returns
    ///
    /// Vector of (`original_field`, Option<`880_field`>) tuples.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let record = Record::new(leader);
    /// for (original, linked_880) in record.get_linked_field_pairs("100") {
    ///     if let Some(name) = original.get_subfield('a') {
    ///         println!("Name: {}", name);
    ///         if let Some(field_880) = linked_880 {
    ///             if let Some(alt) = field_880.get_subfield('a') {
    ///                 println!("  Alternate: {}", alt);
    ///             }
    ///         }
    ///     }
    /// }
    /// ```
    #[must_use]
    fn get_linked_field_pairs(&self, tag: &str) -> Vec<(&Field, Option<&Field>)>;

    /// Get all 880 fields (alternate graphical representations).
    ///
    /// These fields provide alternate script forms (romanized, vernacular, etc.)
    /// linked to original fields via subfield 6 linkage.
    ///
    /// # Returns
    ///
    /// Vector of all 880 fields in the record.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let record = Record::new(leader);
    /// for field_880 in record.get_all_880_fields() {
    ///     println!("Alternate graphical: {:?}", field_880);
    /// }
    /// ```
    #[must_use]
    fn get_all_880_fields(&self) -> Vec<&Field>;
}

impl BibliographicQueries for Record {
    fn get_titles(&self) -> Vec<&Field> {
        self.get_fields("245")
            .map(|f| f.iter().collect())
            .unwrap_or_default()
    }

    fn get_all_subjects(&self) -> Vec<&Field> {
        let mut results = Vec::new();
        for tag in &["600", "610", "611", "630", "648", "650", "651", "655"] {
            if let Some(fields) = self.get_fields(tag) {
                results.extend(fields.iter());
            }
        }
        results
    }

    fn get_topical_subjects(&self) -> Vec<&Field> {
        self.get_fields("650")
            .map(|f| f.iter().collect())
            .unwrap_or_default()
    }

    fn get_geographic_subjects(&self) -> Vec<&Field> {
        self.get_fields("651")
            .map(|f| f.iter().collect())
            .unwrap_or_default()
    }

    fn get_all_names(&self) -> Vec<&Field> {
        let mut results = Vec::new();
        for tag in &["100", "600", "610", "611", "700", "710", "711"] {
            if let Some(fields) = self.get_fields(tag) {
                results.extend(fields.iter());
            }
        }
        results
    }

    fn get_linked_field_pairs(&self, tag: &str) -> Vec<(&Field, Option<&Field>)> {
        self.get_field_pairs(tag)
    }

    fn get_all_880_fields(&self) -> Vec<&Field> {
        self.get_all_880_fields()
    }
}

/// Query helpers specific to authority records.
///
/// This trait provides methods for navigating authority-specific fields
/// like see-from tracings, see-also fields, and relationship information.
pub trait AuthoritySpecificQueries {
    /// Get the preferred heading from the record.
    ///
    /// Authority records have one main heading (1XX field) that represents
    /// the established form of the term.
    ///
    /// # Returns
    ///
    /// The preferred heading field, or `None` if not found.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let record = AuthorityRecord::new(leader);
    /// if let Some(heading) = record.get_preferred_heading() {
    ///     if let Some(label) = heading.get_subfield('a') {
    ///         println!("Preferred heading: {}", label);
    ///     }
    /// }
    /// ```
    #[must_use]
    fn get_preferred_heading(&self) -> Option<&Field>;

    /// Get all variant forms (4XX fields) for this heading.
    ///
    /// These are non-preferred forms that users might search for,
    /// with instructions to "see" the preferred heading instead.
    ///
    /// # Returns
    ///
    /// Vector of all 4XX fields in the record.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let record = AuthorityRecord::new(leader);
    /// for variant in record.get_variant_headings() {
    ///     if let Some(label) = variant.get_subfield('a') {
    ///         println!("Variant: {}", label);
    ///     }
    /// }
    /// ```
    #[must_use]
    fn get_variant_headings(&self) -> Vec<&Field>;

    /// Get all related headings (5XX fields) for this term.
    ///
    /// These are established headings that are related but not synonymous,
    /// with instructions to "see also" these related terms.
    ///
    /// # Returns
    ///
    /// Vector of all 5XX fields in the record.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let record = AuthorityRecord::new(leader);
    /// for related in record.get_broader_related_headings() {
    ///     if let Some(label) = related.get_subfield('a') {
    ///         println!("Related: {}", label);
    ///     }
    /// }
    /// ```
    #[must_use]
    fn get_broader_related_headings(&self) -> Vec<&Field>;

    /// Get the scope note from the record.
    ///
    /// Scope notes (field 680) explain the meaning and usage of the heading.
    ///
    /// # Returns
    ///
    /// The scope note text, or `None` if not found.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let record = AuthorityRecord::new(leader);
    /// if let Some(note) = record.get_scope_note() {
    ///     println!("Scope: {}", note);
    /// }
    /// ```
    #[must_use]
    fn get_scope_note(&self) -> Option<&str>;
}

impl AuthoritySpecificQueries for AuthorityRecord {
    fn get_preferred_heading(&self) -> Option<&Field> {
        self.heading()
    }

    fn get_variant_headings(&self) -> Vec<&Field> {
        self.see_from_tracings()
    }

    fn get_broader_related_headings(&self) -> Vec<&Field> {
        self.see_also_tracings()
    }

    fn get_scope_note(&self) -> Option<&str> {
        self.get_fields("680")
            .and_then(|fields| fields.first())
            .and_then(|f| f.get_subfield('a'))
    }
}

/// Query helpers specific to holdings records.
///
/// This trait provides methods for navigating holdings-specific information
/// like item locations, call numbers, and holdings notes.
pub trait HoldingsSpecificQueries {
    /// Get the call number from field 050 or 090.
    ///
    /// Call numbers are used to organize and locate items in a library.
    /// Tries field 090 (local call number) first, then 050 (LC call number).
    ///
    /// # Returns
    ///
    /// The call number, or `None` if not found.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let record = HoldingsRecord::new(leader);
    /// if let Some(call_num) = record.get_call_number() {
    ///     println!("Call number: {}", call_num);
    /// }
    /// ```
    #[must_use]
    fn get_call_number(&self) -> Option<&str>;

    /// Get the holding location from field 852 (Location).
    ///
    /// Specifies the physical location or repository of the item.
    ///
    /// # Returns
    ///
    /// The location text, or `None` if not found.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let record = HoldingsRecord::new(leader);
    /// if let Some(location) = record.get_holding_location() {
    ///     println!("Location: {}", location);
    /// }
    /// ```
    #[must_use]
    fn get_holding_location(&self) -> Option<&str>;

    /// Get all notes on holdings (5XX fields).
    ///
    /// General notes that apply to the holdings information.
    ///
    /// # Returns
    ///
    /// Vector of all note text values from 5XX fields.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let record = HoldingsRecord::new(leader);
    /// for note in record.get_holding_notes() {
    ///     println!("Note: {}", note);
    /// }
    /// ```
    #[must_use]
    fn get_holding_notes(&self) -> Vec<&str>;
}

impl HoldingsSpecificQueries for HoldingsRecord {
    fn get_call_number(&self) -> Option<&str> {
        // Try local call number first (090), then LC call number (050)
        self.get_fields("090")
            .and_then(|f| f.first())
            .and_then(|f| f.get_subfield('a'))
            .or_else(|| {
                self.get_fields("050")
                    .and_then(|f| f.first())
                    .and_then(|f| f.get_subfield('a'))
            })
    }

    fn get_holding_location(&self) -> Option<&str> {
        self.get_fields("852")
            .and_then(|f| f.first())
            .and_then(|f| f.get_subfield('b'))
    }

    fn get_holding_notes(&self) -> Vec<&str> {
        let mut notes = Vec::new();
        for tag in &[
            "500", "501", "502", "503", "504", "505", "506", "507", "508", "509",
        ] {
            if let Some(fields) = self.get_fields(tag) {
                for field in fields {
                    if let Some(note) = field.get_subfield('a') {
                        notes.push(note);
                    }
                }
            }
        }
        notes
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::leader::Leader;
    use crate::record::Subfield;

    fn make_bib_leader() -> Leader {
        Leader {
            record_length: 1000,
            record_status: 'a',
            record_type: 'a', // Bibliographic record
            bibliographic_level: 'm',
            control_record_type: 'a',
            character_coding: ' ',
            indicator_count: 2,
            subfield_code_count: 2,
            data_base_address: 100,
            encoding_level: ' ',
            cataloging_form: ' ',
            multipart_level: ' ',
            reserved: "4500".to_string(),
        }
    }

    fn make_auth_leader() -> Leader {
        Leader {
            record_length: 1000,
            record_status: 'a',
            record_type: 'z', // Authority record
            bibliographic_level: ' ',
            control_record_type: 'a',
            character_coding: ' ',
            indicator_count: 2,
            subfield_code_count: 2,
            data_base_address: 100,
            encoding_level: ' ',
            cataloging_form: ' ',
            multipart_level: ' ',
            reserved: "4500".to_string(),
        }
    }

    fn make_hold_leader() -> Leader {
        Leader {
            record_length: 1000,
            record_status: 'a',
            record_type: 'x', // Holdings record
            bibliographic_level: ' ',
            control_record_type: 'a',
            character_coding: ' ',
            indicator_count: 2,
            subfield_code_count: 2,
            data_base_address: 100,
            encoding_level: ' ',
            cataloging_form: ' ',
            multipart_level: ' ',
            reserved: "4500".to_string(),
        }
    }

    #[test]
    fn test_bibliographic_get_titles() {
        let mut record = Record::new(make_bib_leader());
        let mut title_field = Field::new("245".to_string(), '1', '0');
        title_field.subfields.push(Subfield {
            code: 'a',
            value: "Test title".to_string(),
        });
        record.add_field(title_field);

        let titles = record.get_titles();
        assert_eq!(titles.len(), 1);
        assert_eq!(titles[0].tag, "245");
    }

    #[test]
    fn test_bibliographic_get_all_subjects() {
        let mut record = Record::new(make_bib_leader());
        let mut subject1 = Field::new("650".to_string(), ' ', '0');
        subject1.subfields.push(Subfield {
            code: 'a',
            value: "Topic".to_string(),
        });
        record.add_field(subject1);

        let mut subject2 = Field::new("651".to_string(), ' ', '0');
        subject2.subfields.push(Subfield {
            code: 'a',
            value: "Place".to_string(),
        });
        record.add_field(subject2);

        let subjects = record.get_all_subjects();
        assert_eq!(subjects.len(), 2);
    }

    #[test]
    fn test_bibliographic_get_all_names() {
        let mut record = Record::new(make_bib_leader());
        let mut name1 = Field::new("100".to_string(), '1', ' ');
        name1.subfields.push(Subfield {
            code: 'a',
            value: "Author".to_string(),
        });
        record.add_field(name1);

        let mut name2 = Field::new("700".to_string(), '1', ' ');
        name2.subfields.push(Subfield {
            code: 'a',
            value: "Contributor".to_string(),
        });
        record.add_field(name2);

        let names = record.get_all_names();
        assert_eq!(names.len(), 2);
    }

    #[test]
    fn test_authority_get_preferred_heading() {
        let mut record = AuthorityRecord::new(make_auth_leader());
        let mut heading = Field::new("150".to_string(), ' ', ' ');
        heading.subfields.push(Subfield {
            code: 'a',
            value: "Computer science".to_string(),
        });
        record.set_heading(heading);

        assert!(record.get_preferred_heading().is_some());
    }

    #[test]
    fn test_authority_get_variant_headings() {
        let mut record = AuthorityRecord::new(make_auth_leader());
        let mut variant = Field::new("450".to_string(), ' ', ' ');
        variant.subfields.push(Subfield {
            code: 'a',
            value: "Computing".to_string(),
        });
        record.add_see_from_tracing(variant);

        let variants = record.get_variant_headings();
        assert_eq!(variants.len(), 1);
    }

    #[test]
    fn test_holdings_get_call_number() {
        let mut record = HoldingsRecord::new(make_hold_leader());
        let mut call_field = Field::new("090".to_string(), ' ', ' ');
        call_field.subfields.push(Subfield {
            code: 'a',
            value: "QA76.9.D3".to_string(),
        });
        record.add_field(call_field);

        assert_eq!(record.get_call_number(), Some("QA76.9.D3"));
    }

    #[test]
    fn test_holdings_get_holding_location() {
        let mut record = HoldingsRecord::new(make_hold_leader());
        let mut loc_field = Field::new("852".to_string(), ' ', ' ');
        loc_field.subfields.push(Subfield {
            code: 'b',
            value: "Main Library".to_string(),
        });
        record.add_field(loc_field);

        assert_eq!(record.get_holding_location(), Some("Main Library"));
    }
}