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
//! Models a MARC record with associated components.
const TAG_SIZE: usize = 3;
const LEADER_SIZE: usize = 24;
const CODE_SIZE: usize = 1;
const DEFAULT_LEADER: &str = "                        ";
const DEFAULT_INDICATOR: &str = " ";

/// Verifies the provided string is composed of 'len' number of bytes.
fn check_byte_count(s: &str, len: usize) -> Result<(), String> {
    let byte_len = s.bytes().len();
    if byte_len != len {
        return Err(format!(
            "Invalid byte count for string s={s} wanted={len} found={byte_len}"
        ));
    }
    Ok(())
}

/// MARC Control Field whose tag value is < "010"
#[derive(Debug, Clone, PartialEq)]
pub struct Controlfield {
    tag: String,
    content: String,
}

impl Controlfield {
    /// Create a Controlfield with the provided tag and content.
    ///
    /// * `tag` - Must have the correct byte count.
    ///
    /// # Examples
    ///
    /// ```
    /// let control_field = marc::Controlfield::new("008", "12345").unwrap();
    /// assert_eq!(control_field.tag(), "008");
    /// ```
    /// ```
    /// let control_field = marc::Controlfield::new("010", "12345");
    ///
    /// assert_eq!(control_field.is_err(), true);
    /// assert_eq!(control_field.unwrap_err(), "Invalid Controlfield tag: 010");
    /// ```
    pub fn new(tag: impl Into<String>, content: impl Into<String>) -> Result<Self, String> {
        let tag = tag.into();
        check_byte_count(&tag, TAG_SIZE)?;

        if tag.as_str() < "000" || tag.as_str() > "009" {
            return Err(format!("Invalid Controlfield tag: {tag}"));
        }

        Ok(Controlfield {
            tag,
            content: content.into(),
        })
    }

    /// Get the tag
    ///
    /// # Examples
    ///
    /// ```
    /// use marc::Controlfield;
    ///
    /// let control_field = Controlfield::new("008", "12345").unwrap();
    /// assert_eq!(control_field.tag(), "008");
    /// ```
    pub fn tag(&self) -> &str {
        &self.tag
    }

    /// Get the content
    ///
    /// # Examples
    ///
    /// ```
    /// use marc::Controlfield;
    ///
    /// let control_field = Controlfield::new("008", "12345").unwrap();
    /// assert_eq!(control_field.content(), "12345");
    /// ```
    pub fn content(&self) -> &str {
        &self.content
    }

    /// Set the Controlfield content.
    ///
    /// # Examples
    ///
    /// ```
    /// use marc::Controlfield;
    ///
    /// let mut control_field = Controlfield::new("008", "12345").unwrap();
    /// control_field.set_content("6789");
    /// assert_eq!(control_field.content(), "6789");
    /// ```
    pub fn set_content(&mut self, content: impl Into<String>) {
        self.content = content.into();
    }
}

/// A single subfield code + value pair
#[derive(Debug, Clone, PartialEq)]
pub struct Subfield {
    code: String,
    content: String,
}

impl Subfield {
    /// Create a Subfield with the provided code and content.
    ///
    /// * `code` - Must have the correct byte count.
    ///
    /// # Examples
    ///
    /// ```
    /// use marc::Subfield;
    /// let subfield: Subfield = match Subfield::new("a", "Στη σκιά της πεταλούδας") {
    ///   Ok(sf) => sf,
    ///   Err(e) => panic!("Subfield::new() failed with: {}", e),
    /// };
    /// assert_eq!(subfield.content(), "Στη σκιά της πεταλούδας");
    /// ```
    ///
    /// ```should_panic
    /// use marc::Subfield;
    /// Subfield::new("🦋", "Στη σκιά της πεταλούδας").unwrap();
    /// ```
    ///
    pub fn new(code: impl Into<String>, content: impl Into<String>) -> Result<Self, String> {
        let code = code.into();
        check_byte_count(&code, CODE_SIZE)?;
        Ok(Subfield {
            code,
            content: content.into(),
        })
    }
    /// Get the Subfield content.
    pub fn content(&self) -> &str {
        &self.content
    }
    /// Set the Subfield content.
    ///
    /// # Examples
    ///
    /// ```
    /// use marc::Subfield;
    /// let mut subfield: Subfield = Subfield::new("a", "potato").unwrap();
    /// subfield.set_content("cheese");
    /// assert_eq!(subfield.content(), "cheese");
    /// ```
    ///
    pub fn set_content(&mut self, content: impl Into<String>) {
        self.content = content.into();
    }
    /// Get the Subfield code.
    ///
    /// # Examples
    ///
    /// ```
    /// use marc::Subfield;
    /// let subfield: Subfield = Subfield::new("a", "potato").unwrap();
    /// assert_eq!(subfield.code(), "a");
    /// ```
    ///
    pub fn code(&self) -> &str {
        &self.code
    }
    /// Set the Subfield code.
    ///
    /// # Examples
    ///
    /// ```
    /// use marc::Subfield;
    /// let mut subfield: Subfield = Subfield::new("a", "potato").unwrap();
    /// subfield.set_code("q");
    /// assert_eq!(subfield.code(), "q");
    /// ```
    ///
    /// ```should_panic
    /// use marc::Subfield;
    /// let mut subfield: Subfield = Subfield::new("a", "potato").unwrap();
    /// subfield.set_code("🥔").unwrap();
    /// ```
    ///
    pub fn set_code(&mut self, code: impl Into<String>) -> Result<(), String> {
        let code: String = code.into();
        check_byte_count(&code, CODE_SIZE)?;
        self.code = code;
        Ok(())
    }
}

/// A MARC Data Field with tag, indicators, and subfields.
#[derive(Debug, Clone, PartialEq)]
pub struct Field {
    tag: String,
    ind1: Option<String>,
    ind2: Option<String>,
    subfields: Vec<Subfield>,
}

impl Field {
    /// Create a Field with the provided tag.
    ///
    /// * `tag` - Must have the correct byte count.
    ///
    /// # Examples
    ///
    /// ```
    /// use marc::record::Field;
    ///
    /// let field: Field = match Field::new("245") {
    ///   Ok(f) => f,
    ///   Err(e) => panic!("Field::new() failed with: {}", e),
    /// };
    /// assert_eq!(field.tag(), "245");
    /// assert_eq!(field.ind1(), " ");
    /// assert_eq!(field.ind2(), " ");
    /// assert_eq!(field.subfields().len(), 0);
    /// ```
    ///
    pub fn new(tag: impl Into<String>) -> Result<Self, String> {
        let tag = tag.into();
        check_byte_count(&tag, TAG_SIZE)?;

        if tag.as_str() < "010" || tag.as_str() > "999" {
            // Of note, OCLC sometimes creates MARC records with data
            // fields using the tag "DAT".  For our purposes, the only
            // thing that really matters is the byte count (checked
            // above), so just warn for unexpected tags.
            eprintln!("Unexpected tag for data field: '{tag}'");
        }

        Ok(Field {
            tag,
            ind1: None,
            ind2: None,
            subfields: Vec::new(),
        })
    }
    /// Get the tag
    pub fn tag(&self) -> &str {
        &self.tag
    }
    /// Get the value of indicator-1, defaulting to DEFAULT_INDICATOR.
    pub fn ind1(&self) -> &str {
        self.ind1.as_deref().unwrap_or(DEFAULT_INDICATOR)
    }
    /// Get the value of indicator-2, defaulting to DEFAULT_INDICATOR.
    pub fn ind2(&self) -> &str {
        self.ind2.as_deref().unwrap_or(DEFAULT_INDICATOR)
    }
    /// Get the full list of subfields
    pub fn subfields(&self) -> &Vec<Subfield> {
        &self.subfields
    }
    /// Get a mutable list of subfields.
    pub fn subfields_mut(&mut self) -> &mut Vec<Subfield> {
        &mut self.subfields
    }

    /// Set the indicator-1 value.
    ///
    /// * `ind` - Must have the correct byte count.
    pub fn set_ind1(&mut self, ind: impl Into<String>) -> Result<(), String> {
        let ind = ind.into();
        check_byte_count(&ind, CODE_SIZE)?;
        self.ind1 = Some(ind);
        Ok(())
    }

    /// Set the indicator-2 value.
    ///
    /// * `ind` - Must have the correct byte count.
    pub fn set_ind2(&mut self, ind: impl Into<String>) -> Result<(), String> {
        let ind = ind.into();
        check_byte_count(&ind, CODE_SIZE)?;
        self.ind2 = Some(ind);
        Ok(())
    }

    /// Get a list of subfields with the provided code.
    pub fn get_subfields(&self, code: &str) -> Vec<&Subfield> {
        self.subfields.iter().filter(|f| f.code() == code).collect()
    }

    pub fn first_subfield(&self, code: &str) -> Option<&Subfield> {
        self.subfields.iter().find(|f| f.code() == code)
    }

    pub fn has_subfield(&self, code: &str) -> bool {
        self.subfields.iter().any(|f| f.code() == code)
    }

    /// Get a mutable list of subfields with the provided code.
    pub fn get_subfields_mut(&mut self, code: &str) -> Vec<&mut Subfield> {
        self.subfields
            .iter_mut()
            .filter(|f| f.code() == code)
            .collect()
    }

    /// Adds a new Subfield to this field using the provided code and content.
    ///
    /// * `code` - Must have the correct byte count.
    pub fn add_subfield(
        &mut self,
        code: impl Into<String>,
        content: impl Into<String>,
    ) -> Result<(), String> {
        self.subfields.push(Subfield::new(code, content)?);
        Ok(())
    }

    /// Remove the first subfield with the specified code.
    pub fn remove_first_subfield(&mut self, code: &str) -> Option<Subfield> {
        if let Some(index) = self.subfields.iter().position(|s| s.code.eq(code)) {
            return Some(self.subfields.remove(index));
        }

        None
    }

    /// Remove all subfields with the specified code and returns
    /// the count of removed subfields.
    ///
    /// # Examples
    ///
    /// ```
    /// use marc::record::Field;
    /// let mut field = Field::new("505").unwrap();
    /// let _ = field.add_subfield("t", "Chapter 1 /");
    /// let _ = field.add_subfield("r", "Cool author --");
    /// let _ = field.add_subfield("t", "Chapter 2.");
    /// assert_eq!(field.subfields().len(), 3);
    ///
    /// assert_eq!(field.remove_subfields("t"), 2);
    ///
    /// assert_eq!(field.subfields().len(), 1);
    /// ```
    pub fn remove_subfields(&mut self, code: &str) -> usize {
        let mut removed = 0;

        while let Some(index) = self.subfields.iter().position(|s| s.code.eq(code)) {
            self.subfields.remove(index);
            removed += 1;
        }

        removed
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct Record {
    leader: String,
    control_fields: Vec<Controlfield>,
    fields: Vec<Field>,
}

/// A MARC record with leader, control fields, and data fields.
impl Default for Record {
    fn default() -> Self {
        Self::new()
    }
}

impl Record {
    /// Create a new Record with a default leader and no content.
    pub fn new() -> Self {
        Record {
            leader: DEFAULT_LEADER.to_string(),
            control_fields: Vec::new(),
            fields: Vec::new(),
        }
    }

    /// Get the leader as a string.
    pub fn leader(&self) -> &str {
        &self.leader
    }

    /// Apply a leader value.
    ///
    /// Returns Err if the value is not composed of the correct number
    /// of bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// use marc::record::Record;
    /// let mut record = Record::default();
    /// assert!(record.set_leader("too short").is_err());
    /// assert!(record.set_leader("just right              ").is_ok());
    /// ```
    pub fn set_leader(&mut self, leader: impl Into<String>) -> Result<(), String> {
        let leader = leader.into();
        check_byte_count(&leader, LEADER_SIZE)?;
        self.leader = leader;
        Ok(())
    }

    /// Apply a leader value from a set of bytes
    ///
    /// Returns Err if the value is not composed of the correct number
    /// of bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// use marc::record::Record;
    /// let mut record = Record::default();
    /// assert!(record.set_leader_bytes("too short".as_bytes()).is_err());
    /// assert!(record.set_leader_bytes("just right              ".as_bytes()).is_ok());
    /// ```
    pub fn set_leader_bytes(&mut self, bytes: &[u8]) -> Result<(), String> {
        let s = std::str::from_utf8(bytes)
            .map_err(|e| format!("Leader is not a valid UTF-8 string: {e} bytes={bytes:?}"))?;
        self.set_leader(s)
    }

    /// Get the full list of control fields.
    pub fn control_fields(&self) -> &Vec<Controlfield> {
        &self.control_fields
    }
    /// Get the full list of control fields, mutable.
    pub fn control_fields_mut(&mut self) -> &mut Vec<Controlfield> {
        &mut self.control_fields
    }
    /// Get the full list of fields.
    pub fn fields(&self) -> &Vec<Field> {
        &self.fields
    }
    /// Get the full list of fields, mutable.
    pub fn fields_mut(&mut self) -> &mut Vec<Field> {
        &mut self.fields
    }

    /// Return a list of control fields with the provided tag.
    pub fn get_control_fields(&self, tag: &str) -> Vec<&Controlfield> {
        self.control_fields
            .iter()
            .filter(|f| f.tag() == tag)
            .collect()
    }

    /// Return a list of fields with the provided tag.
    pub fn get_fields(&self, tag: &str) -> Vec<&Field> {
        self.fields.iter().filter(|f| f.tag() == tag).collect()
    }

    /// Return a mutable list of fields with the provided tag.
    pub fn get_fields_mut(&mut self, tag: &str) -> Vec<&mut Field> {
        self.fields.iter_mut().filter(|f| f.tag() == tag).collect()
    }

    /// Add a new control field with the provided tag and content and
    /// insert it in tag order.
    ///
    /// Controlfields are those with tag 001 .. 009
    ///
    /// Err if the tag is invalid.
    ///
    /// # Examples
    ///
    /// ```
    /// use marc::record::Record;
    /// let mut record = Record::default();
    /// assert!(record.add_control_field("011", "foo").is_err());
    /// assert!(record.add_control_field("002", "bar").is_ok());
    /// assert!(record.add_control_field("001", "bar").is_ok());
    ///
    /// // should be sorted by tag.
    /// assert_eq!(record.control_fields()[0].tag(), "001");
    /// ```
    pub fn add_control_field(&mut self, tag: &str, content: &str) -> Result<(), String> {
        if tag >= "010" || tag <= "000" {
            return Err(format!("Invalid control field tag: '{tag}'"));
        }
        self.insert_control_field(Controlfield::new(tag, content)?);
        Ok(())
    }

    pub fn insert_control_field(&mut self, field: Controlfield) {
        match self
            .control_fields()
            .iter()
            .position(|f| f.tag() > field.tag())
        {
            Some(idx) => self.control_fields_mut().insert(idx, field),
            None => self.control_fields_mut().push(field),
        }
    }

    /// Insert a data field in tag order
    pub fn insert_field(&mut self, field: Field) -> usize {
        match self.fields().iter().position(|f| f.tag() > field.tag()) {
            Some(idx) => {
                self.fields_mut().insert(idx, field);
                idx
            }
            None => {
                self.fields_mut().push(field);
                0
            }
        }
    }

    /// Create a new Field with the provided tag, insert it into the
    /// record in tag order, then return a mut ref to the new field.
    ///
    /// # Examples
    ///
    /// ```
    /// use marc::record::Record;
    /// let mut record = Record::default();
    /// assert!(record.add_data_field("245").is_ok());
    /// assert!(record.add_data_field("240").is_ok());
    /// assert!(record.add_data_field("1234").is_err());
    ///
    /// assert_eq!(record.fields()[0].tag(), "240");
    /// ```
    pub fn add_data_field(&mut self, tag: impl Into<String>) -> Result<&mut Field, String> {
        let pos = self.insert_field(Field::new(tag)?);
        Ok(self.fields_mut().get_mut(pos).unwrap())
    }

    /// Returns a list of values for the specified tag and subfield.
    ///
    /// # Examples
    ///
    /// ```
    /// use marc::record::Record;
    /// let mut record = Record::default();
    /// let field = record.add_data_field("650").expect("added field");
    /// field.add_subfield("a", "foo");
    /// field.add_subfield("a", "bar");
    ///
    /// let field = record.add_data_field("650").expect("added field");
    /// field.add_subfield("a", "baz");
    ///
    /// let values = record.get_values("650", "a");
    ///
    /// assert_eq!(values.len(), 3);
    /// assert_eq!(values[1], "bar");
    /// ```
    pub fn get_values(&self, tag: &str, sfcode: &str) -> Vec<&str> {
        let mut vec = Vec::new();
        for field in self.get_fields(tag) {
            for sf in field.get_subfields(sfcode) {
                vec.push(sf.content.as_str());
            }
        }
        vec
    }

    /// Remove all occurrences of control fields with the provided tag.
    pub fn remove_control_fields(&mut self, tag: &str) {
        loop {
            if let Some(pos) = self.control_fields.iter().position(|f| f.tag() == tag) {
                self.control_fields.remove(pos);
            } else {
                // No more fields to remove.
                return;
            }
        }
    }

    /// Remove all occurrences of fields with the provided tag.
    pub fn remove_fields(&mut self, tag: &str) {
        loop {
            if let Some(pos) = self.fields.iter().position(|f| f.tag() == tag) {
                self.fields.remove(pos);
            } else {
                // No more fields to remove.
                return;
            }
        }
    }
}