marctk 0.8.0

MARC21 Binary, Breaker, and XML Toolkit
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
//! Routines for reading and writing binary MARC data.
use super::Controlfield;
use super::Field;
use super::Record;
use super::Subfield;
use std::fs::File;
use std::io::prelude::*;

const END_OF_FIELD: u8 = 30; // '\x1E';
const END_OF_RECORD: u8 = 29; // '\x1D';
const RECORD_SIZE_ENTRY: usize = 5;
const LEADER_SIZE: usize = 24;
const DATA_OFFSET_START: usize = 12;
const DATA_OFFSET_SIZE: usize = 5;
const DATA_LENGTH_SIZE: usize = 4;
const DIRECTORY_ENTRY_LEN: usize = 12;
const SUBFIELD_SEPARATOR: &str = "\x1F";
const MAX_RECORD_BYTES: usize = 99999;

/// Parses a binary MARC file and emits [`Record`] values.
pub struct BinaryRecordIterator {
    file: File,
}

impl Iterator for BinaryRecordIterator {
    type Item = Result<Record, String>;

    /// Returns the next [`Record`] extracted from the binary content.
    fn next(&mut self) -> Option<Self::Item> {
        let mut bytes: Vec<u8> = Vec::new();

        loop {
            // Read the file one byte at a time until we encounter an
            // END_OF_RECORD byte.  Pass the bytes to the Record binary parser.

            let mut buf: [u8; 1] = [0];
            match self.file.read(&mut buf) {
                Ok(count) => {
                    if count == 1 {
                        bytes.push(buf[0]);
                        if buf[0] == END_OF_RECORD {
                            break;
                        }
                    } else {
                        break; // EOF
                    }
                }
                Err(e) => {
                    return Some(Err(format!("Error reading file: {:?} {}", self.file, e)));
                }
            }
        }

        if !bytes.is_empty() {
            match Record::from_binary(bytes.as_slice()) {
                Ok(r) => return Some(Ok(r)),
                Err(e) => return Some(Err(format!("Error processing bytes: {:?} {}", bytes, e))),
            }
        }

        None
    }
}

impl BinaryRecordIterator {
    /// Create a new [`BinaryRecordIterator`] from a file
    fn from_file(filename: &str) -> Result<Self, String> {
        let file = match File::open(filename) {
            Ok(f) => f,
            Err(e) => return Err(format!("Cannot read MARC file: {filename} {e}")),
        };

        Ok(BinaryRecordIterator { file })
    }
}

/// Translates a slice of bytes into a String which represents a number,
/// then extracts and returns the number.
///
/// ```
/// use marctk::binary;
///
/// let b = &[49, 50, 51, 52]; // "1234"
/// assert_eq!(binary::bytes_to_usize(b), Ok(1234))
/// ```
pub fn bytes_to_usize(bytes: &[u8]) -> Result<usize, String> {
    match std::str::from_utf8(bytes) {
        Ok(bytes_str) => match bytes_str.parse::<usize>() {
            Ok(num) => Ok(num),
            Err(e) => Err(format!(
                "Error translating string to usize str={bytes_str} {e}"
            )),
        },
        Err(e) => Err(format!("Error translating bytes to string: {bytes:?} {e}")),
    }
}

/// Models the position/size data for a single, variable-length (control
/// or data) field.
pub struct DirectoryEntry {
    tag: String,
    field_start_idx: usize,
    field_end_idx: usize,
}

impl DirectoryEntry {
    /// Create a new directory entry from a set of bytes and positional
    /// information.
    ///
    /// * `which` - Which entry is this in the directory
    /// * `data_start_idx` - Where in the record as a whole does the data
    ///   we care about start.
    /// * `dir_bytes` - Bytes of this directory entry.
    ///
    /// # References
    ///
    /// * <https://www.loc.gov/marc/bibliographic/bddirectory.html>
    pub fn new(which: usize, data_start_idx: usize, dir_bytes: &[u8]) -> Result<Self, String> {
        let start = which * DIRECTORY_ENTRY_LEN;
        let end = start + DIRECTORY_ENTRY_LEN;
        let bytes = dir_bytes
            .get(start..end)
            .ok_or_else(|| format!("No directory entry {which}"))?;

        let entry_str = match std::str::from_utf8(bytes) {
            Ok(s) => s,
            Err(e) => return Err(format!("Invalid directory bytes: {:?} {}", bytes, e)),
        };

        // None where a character straddles a boundary.
        let (Some(field_tag), Some(field_len_str), Some(field_pos_str)) = (
            entry_str.get(0..3),
            entry_str.get(3..7),
            entry_str.get(7..12),
        ) else {
            return Err(format!("Invalid directory entry: {entry_str:?}"));
        };

        let field_len = match field_len_str.parse::<usize>() {
            Ok(l) => l,
            Err(e) => return Err(format!("Invalid data length value {} {}", field_len_str, e)),
        };

        // A field's length includes its terminator.
        if field_len == 0 {
            return Err(format!("Invalid data length 0 for tag={field_tag}"));
        }

        // Where does this field start in the record as a whole
        let field_start_idx = match field_pos_str.parse::<usize>() {
            Ok(l) => l,
            Err(e) => {
                return Err(format!(
                    "Invalid data position value {} {}",
                    field_pos_str, e
                ));
            }
        };

        let start = field_start_idx + data_start_idx;
        let last = start + field_len - 1; // Discard END_OF_FIELD char

        Ok(DirectoryEntry {
            tag: field_tag.to_string(),
            field_start_idx: start,
            field_end_idx: last,
        })
    }
}

impl Record {
    /// Returns an iterator over MARC records produced from a binary file.
    pub fn from_binary_file(filename: &str) -> Result<BinaryRecordIterator, String> {
        BinaryRecordIterator::from_file(filename)
    }

    /// Creates a single MARC Record from a series of bytes.
    ///
    /// # References
    ///
    /// * <https://www.loc.gov/marc/bibliographic/bdleader.html>
    /// * <https://www.loc.gov/marc/bibliographic/bddirectory.html>
    pub fn from_binary(rec_bytes: &[u8]) -> Result<Record, String> {
        let mut record = Record::new();

        let rec_byte_count = rec_bytes.len();

        if rec_byte_count < LEADER_SIZE {
            return Err(format!("Binary record is too short: {:?}", rec_bytes));
        }

        let leader_bytes = &rec_bytes[0..LEADER_SIZE];

        // Reported size of the record byte chunk
        let size_bytes = &leader_bytes[0..RECORD_SIZE_ENTRY];

        // Repported size of the record as a number
        let rec_size = bytes_to_usize(size_bytes)?;

        if rec_byte_count != rec_size {
            return Err(format!(
                "Record has incorrect size reported={} real={}",
                rec_size, rec_byte_count
            ));
        }

        record.set_leader_bytes(leader_bytes)?;

        // Where in this pile of bytes do the control/data fields tart.
        let data_offset_bytes =
            &leader_bytes[DATA_OFFSET_START..(DATA_OFFSET_START + DATA_OFFSET_SIZE)];

        let data_start_idx = bytes_to_usize(data_offset_bytes)?;

        // The directory and its terminator lie between the leader and the
        // data.
        if data_start_idx <= LEADER_SIZE || data_start_idx > rec_byte_count {
            return Err(format!(
                "Invalid data offset {} for a record of {} bytes",
                data_start_idx, rec_byte_count
            ));
        }

        // The full directory as bytes.
        // -1 to skip the END_OF_FIELD
        let dir_bytes = &rec_bytes[LEADER_SIZE..(data_start_idx - 1)];

        // Directory byte length should be divisible by the directry entry length.
        let dir_len = dir_bytes.len();
        if dir_len == 0 || !dir_len.is_multiple_of(DIRECTORY_ENTRY_LEN) {
            return Err(format!("Invalid directory length {}", dir_len));
        }

        // How many directory entries are in this record.
        let dir_count = dir_bytes.len() / DIRECTORY_ENTRY_LEN;
        let mut dir_idx = 0;

        while dir_idx < dir_count {
            let dir_entry = DirectoryEntry::new(dir_idx, data_start_idx, dir_bytes)?;

            if let Err(e) = record.process_directory_entry(rec_bytes, rec_byte_count, &dir_entry) {
                return Err(format!(
                    "Error processing directory entry index={} {}",
                    dir_idx, e
                ));
            }

            dir_idx += 1;
        }

        Ok(record)
    }

    /// Unpack a single control field / data field and append to the
    /// record in progress.
    ///
    /// # References
    ///
    /// * <https://www.loc.gov/marc/bibliographic/bddirectory.html>
    fn process_directory_entry(
        &mut self,
        rec_bytes: &[u8],      // full record as bytes
        rec_byte_count: usize, // full size of record
        dir_entry: &DirectoryEntry,
    ) -> Result<(), String> {
        if (dir_entry.field_end_idx) >= rec_byte_count {
            return Err(format!(
                "Field length exceeds length of record for tag={}",
                dir_entry.tag
            ));
        }

        // Extract the bytes for this directory entry from the directory.
        let field_bytes = &rec_bytes[dir_entry.field_start_idx..dir_entry.field_end_idx];

        // Turn said bytes into a string
        let field_str = match std::str::from_utf8(field_bytes) {
            Ok(s) => s,
            Err(e) => {
                return Err(format!(
                    "Field data is not UTF-8 compatible: {:?} {}",
                    field_bytes, e
                ));
            }
        };

        if dir_entry.tag.as_str() < "010" {
            let content = if !field_str.is_empty() { field_str } else { "" };

            let cf = Controlfield::new_unchecked(&dir_entry.tag, content);
            self.control_fields_mut().push(cf);
            return Ok(());
        }

        // 3-bytes for tag
        // 1 byte for indicator 1
        // 1 byte for indicator 2
        let mut field = Field::new_unchecked(&dir_entry.tag);

        let (Some(ind1), Some(ind2)) = (field_str.get(..1), field_str.get(1..2)) else {
            return Err(format!(
                "Data field has no single-byte indicators: tag={}",
                dir_entry.tag
            ));
        };
        field.set_ind1(ind1)?;
        field.set_ind2(ind2)?;

        // Split the remainder on the subfield separator and
        // build Field's from them.
        let field_parts: Vec<&str> = field_str.split(SUBFIELD_SEPARATOR).collect();

        for part in &field_parts[1..] {
            // skip the initial SUBFIELD_SEPARATOR
            let mut chars = part.chars();
            let Some(code) = chars.next() else {
                // Separators with nothing between them, or at the end:
                // no subfield.
                continue;
            };
            // Kept as found, multibyte or not.
            let sf = Subfield::new_unchecked(code, chars.as_str());
            field.subfields_mut().push(sf);
        }

        self.fields_mut().push(field);

        Ok(())
    }

    /// Generates the binary form of a MARC record as a vector of bytes.
    ///
    /// Err if the record holds a value the binary format has no room
    /// for: a leader that is not 24 bytes, a tag that is not 3, or an
    /// indicator or subfield code that is not 1.  The constructors and
    /// setters refuse such values, but parsers keep them.
    ///
    /// # Examples
    /// ```
    /// use marctk::Record;
    /// let mut my_record = Record::new();
    /// my_record
    ///     .add_data_field("245")
    ///     .unwrap()
    ///     .add_subfield("a", "My favorite book")
    ///     .unwrap();
    /// assert_eq!(
    ///     my_record.to_binary().unwrap(),
    ///     "00059       00037       245002100000\x1E  \x1FaMy favorite book\x1E\x1D".as_bytes()
    /// );
    ///
    /// let parsed = Record::from_xml(
    ///     r#"<record><datafield tag="245"><subfield code="ab">Two-byte code</subfield></datafield></record>"#
    /// ).next().unwrap().unwrap();
    /// assert!(parsed.to_binary().is_err());
    /// ```
    pub fn to_binary(&self) -> Result<Vec<u8>, String> {
        self.check_byte_counts()?;

        let mut bytes: Vec<u8> = Vec::new();

        bytes.append(&mut self.leader().as_bytes().to_vec());

        // Directory
        let num_dirs = self.build_directory(&mut bytes);

        // End-of-field after Directory
        bytes.push(END_OF_FIELD);

        self.add_data_fields(&mut bytes);

        // End-of-record after all data fields are added
        bytes.push(END_OF_RECORD);

        // Make sure the size and data offset for the leader match.
        self.sync_leader(num_dirs, &mut bytes)?;

        Ok(bytes)
    }

    /// Compile the directory entries for the control fields and data fields.
    ///
    /// # References
    ///
    /// * <https://www.loc.gov/marc/bibliographic/bddirectory.html>
    fn build_directory(&self, bytes: &mut Vec<u8>) -> usize {
        let mut num_dirs = 0;
        let mut prev_end_idx = 0;

        for field in self.control_fields() {
            num_dirs += 1;

            let mut field_len = field.content().len();

            field_len += 1; // end of field terminator

            // Our directory entry as a string.
            let s = format!(
                "{}{:0w1$}{:0w2$}",
                field.tag(),
                field_len,
                prev_end_idx, // our starting point
                w1 = DATA_LENGTH_SIZE,
                w2 = DATA_OFFSET_SIZE
            );

            bytes.append(&mut s.as_bytes().to_vec());

            prev_end_idx += field_len;
        }

        for field in self.fields() {
            num_dirs += 1;

            let mut field_len = 3; // ind1 + ind2 + field terminator
            for sf in field.subfields() {
                field_len += 2; // sf code + separator
                field_len += sf.content().len();
            }

            // Our directory entry as a string.
            let s = format!(
                "{}{:0w1$}{:0w2$}",
                field.tag(),
                field_len,
                prev_end_idx, // our starting point
                w1 = DATA_LENGTH_SIZE,
                w2 = DATA_OFFSET_SIZE
            );

            bytes.append(&mut s.as_bytes().to_vec());

            prev_end_idx += field_len;
        }

        num_dirs
    }

    /// Appends the binary forms of the control fields and data fields.
    fn add_data_fields(&self, bytes: &mut Vec<u8>) {
        // Now append the actual data
        for field in self.control_fields() {
            bytes.append(&mut field.content().as_bytes().to_vec());
            bytes.push(END_OF_FIELD);
        }

        for field in self.fields() {
            let s = format!("{}{}", field.ind1(), field.ind2());
            bytes.append(&mut s.as_bytes().to_vec());

            for sf in field.subfields() {
                let s = format!("{}{}{}", SUBFIELD_SEPARATOR, sf.code(), sf.content());
                bytes.append(&mut s.as_bytes().to_vec());
            }

            bytes.push(END_OF_FIELD);
        }
    }

    /// Sync the byte count and data offset values in the leader to
    /// match the record just created.
    fn sync_leader(&self, num_dirs: usize, bytes: &mut [u8]) -> Result<(), String> {
        let blen = bytes.len();

        if blen > MAX_RECORD_BYTES {
            return Err(format!(
                "MARC byte count {blen} too large for binary encoding"
            ));
        }

        let size_str = format!("{:0w$}", blen, w = RECORD_SIZE_ENTRY);
        let size_bytes = size_str.as_bytes();

        bytes[0..RECORD_SIZE_ENTRY].copy_from_slice(size_bytes);

        // Set the start index of the body of the record
        let data_start_idx = LEADER_SIZE + (num_dirs * DIRECTORY_ENTRY_LEN) + 1; // end-of-field
        let data_start_str = format!("{:0w$}", data_start_idx, w = DATA_OFFSET_SIZE);

        let dstart = DATA_OFFSET_START;
        let dend = dstart + DATA_OFFSET_SIZE;

        bytes[dstart..dend].copy_from_slice(data_start_str.as_bytes());

        Ok(())
    }
}

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

    /// A binary record of `fields`, each a tag and its data without the
    /// field terminator, with the leader's lengths to match.
    fn binary(fields: &[(&str, &str)]) -> Vec<u8> {
        let (mut directory, mut data) = (String::new(), String::new());
        for (tag, body) in fields {
            let body = format!("{body}\x1E");
            directory += &format!("{tag}{:04}{:05}", body.len(), data.len());
            data += &body;
        }
        let base = LEADER_SIZE + directory.len() + 1;
        let total = base + data.len() + 1;
        format!("{total:05}nam a22{base:05}   4500{directory}\x1E{data}\x1D").into_bytes()
    }

    /// `bytes` with `with` in place from byte `at`.
    fn patched(mut bytes: Vec<u8>, at: usize, with: &str) -> Vec<u8> {
        bytes[at..at + with.len()].copy_from_slice(with.as_bytes());
        bytes
    }

    fn subfields(record: &Record) -> Vec<(&str, &str)> {
        record.fields()[0]
            .subfields()
            .iter()
            .map(|sf| (sf.code(), sf.content()))
            .collect()
    }

    #[test]
    fn test_reads_fields() {
        let record =
            Record::from_binary(&binary(&[("001", "id1"), ("245", "10\x1FaOne\x1Fb")])).unwrap();
        assert_eq!(record.control_fields()[0].content(), "id1");
        let field = &record.fields()[0];
        assert_eq!((field.ind1(), field.ind2()), ("1", "0"));
        assert_eq!(subfields(&record), [("a", "One"), ("b", "")]);
    }

    #[test]
    fn test_reads_a_three_byte_tag_that_is_not_ascii() {
        let record = Record::from_binary(&binary(&[("2\u{e9}", "10\x1FaOne")])).unwrap();
        assert_eq!(record.fields()[0].tag(), "2\u{e9}");
    }

    #[test]
    fn test_empty_subfields_are_skipped() {
        let record = Record::from_binary(&binary(&[("245", "10\x1F\x1FaOne\x1F")])).unwrap();
        assert_eq!(subfields(&record), [("a", "One")]);
    }

    #[test]
    fn test_malformed_data_fields_are_errors() {
        // No indicators, one, or a character spanning both.
        for body in ["", "1", "\u{e9}0\x1Fax"] {
            assert!(
                Record::from_binary(&binary(&[("245", body)])).is_err(),
                "{body:?}"
            );
        }
    }

    #[test]
    fn test_keeps_values_as_found() {
        let record =
            Record::from_binary(&binary(&[(" 01", "id"), ("245", "10\x1F\u{e9}x")])).unwrap();
        assert_eq!(record.control_fields()[0].tag(), " 01");
        assert_eq!(subfields(&record), [("\u{e9}", "x")]);
        // A two-byte code has no room in binary.
        assert!(record.to_binary().is_err());
    }

    #[test]
    fn test_to_binary_needs_binary_byte_counts() {
        let parse = |xml: &str| Record::from_xml(xml).next().unwrap().unwrap();
        let cases = [
            ("<leader>short</leader>", "Leader"),
            (
                r#"<controlfield tag="1">x</controlfield>"#,
                "Control field tag",
            ),
            (r#"<datafield tag="24"/>"#, "Field tag"),
            (r#"<datafield tag="245" ind1="10"/>"#, "Field 245 indicator"),
            (
                r#"<datafield tag="245"><subfield code="">x</subfield></datafield>"#,
                "Field 245 subfield code",
            ),
        ];
        for (xml, problem) in cases {
            let record = parse(&format!("<record>{xml}</record>"));
            let err = record.to_binary().unwrap_err();
            assert!(err.starts_with(problem), "{xml}: {err}");
        }
        // An empty indicator reads as blank, which binary holds.
        let record = parse(r#"<record><datafield tag="245" ind1="" ind2=""/></record>"#);
        assert!(record.to_binary().is_ok());
    }

    #[test]
    fn test_malformed_leaders_and_directories_are_errors() {
        let record = binary(&[("245", "10\x1FaOne")]);
        // The data offset: none, inside the leader, past the record.
        for offset in ["00000", "00024", "99999"] {
            let bytes = patched(record.clone(), DATA_OFFSET_START, offset);
            assert!(Record::from_binary(&bytes).is_err(), "{offset}");
        }
        // A zero field length.
        let bytes = patched(record.clone(), LEADER_SIZE + 3, "0000");
        assert!(Record::from_binary(&bytes).is_err());
        // A character straddling the end of the tag.
        let bytes = patched(record.clone(), LEADER_SIZE + 2, "\u{e9}");
        assert!(Record::from_binary(&bytes).is_err());
        // An entry past the directory.
        assert!(DirectoryEntry::new(1, 37, "245001300000".as_bytes()).is_err());
    }
}