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
//! Bibliographic helper utilities for MARC records.
//!
//! This module provides utilities for validating and parsing common
//! bibliographic identifiers and data found in MARC records.
/// ISBN (International Standard Book Number) validator and parser
#[derive(Debug)]
pub struct IsbnValidator;
impl IsbnValidator {
/// Validate an ISBN-10 checksum
///
/// ISBN-10 uses a weighted checksum where digits are multiplied by 10-9 and mod 11.
/// The check digit can be 0-9 or 'X' (representing 10).
///
/// # Examples
///
/// ```
/// use mrrc::IsbnValidator;
///
/// // Valid ISBN-10
/// assert!(IsbnValidator::validate_isbn10("0306406152"));
/// // Invalid ISBN-10
/// assert!(!IsbnValidator::validate_isbn10("0306406153"));
/// ```
#[must_use]
pub fn validate_isbn10(isbn: &str) -> bool {
let clean = isbn.replace(['-', ' '], "");
if clean.len() != 10 {
return false;
}
let mut sum = 0;
for (i, ch) in clean.chars().enumerate() {
let digit = if i == 9 && ch == 'X' {
10
} else if let Some(d) = ch.to_digit(10) {
d
} else {
return false;
};
sum += digit * (10 - u32::try_from(i).unwrap_or(0));
}
sum % 11 == 0
}
/// Validate an ISBN-13 checksum
///
/// ISBN-13 uses a weighted checksum where odd positions are multiplied by 1
/// and even positions by 3, summed mod 10.
///
/// # Examples
///
/// ```
/// use mrrc::IsbnValidator;
///
/// // Valid ISBN-13
/// assert!(IsbnValidator::validate_isbn13("9780306406157"));
/// // Invalid ISBN-13
/// assert!(!IsbnValidator::validate_isbn13("9780306406158"));
/// ```
#[must_use]
pub fn validate_isbn13(isbn: &str) -> bool {
let clean = isbn.replace(['-', ' '], "");
if clean.len() != 13 {
return false;
}
// Must start with 978 or 979
if !clean.starts_with("978") && !clean.starts_with("979") {
return false;
}
let mut sum = 0;
for (i, ch) in clean.chars().enumerate() {
if let Some(digit) = ch.to_digit(10) {
let weight = if i % 2 == 0 { 1 } else { 3 };
sum += digit * weight;
} else {
return false;
}
}
(10 - (sum % 10)) % 10 == 0
}
/// Validate an ISBN (auto-detect ISBN-10 or ISBN-13)
///
/// # Examples
///
/// ```
/// use mrrc::IsbnValidator;
///
/// assert!(IsbnValidator::validate("0306406152")); // ISBN-10
/// assert!(IsbnValidator::validate("9780306406157")); // ISBN-13
/// ```
#[must_use]
pub fn validate(isbn: &str) -> bool {
let clean = isbn.replace(['-', ' '], "");
match clean.len() {
10 => Self::validate_isbn10(&clean),
13 => Self::validate_isbn13(&clean),
_ => false,
}
}
/// Extract the ISBN without dashes or spaces
///
/// # Examples
///
/// ```
/// use mrrc::IsbnValidator;
///
/// assert_eq!(IsbnValidator::normalize("978-0-306-40615-7"), "9780306406157");
/// assert_eq!(IsbnValidator::normalize("0-306-40615-2"), "0306406152");
/// ```
#[must_use]
pub fn normalize(isbn: &str) -> String {
isbn.replace(['-', ' '], "")
}
}
/// Publication information parser
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PublicationInfo {
/// Place of publication (field 260, subfield 'a')
pub place: Option<String>,
/// Publisher (field 260, subfield 'b')
pub publisher: Option<String>,
/// Publication date (field 260, subfield 'c')
pub date: Option<String>,
}
impl PublicationInfo {
/// Create a new `PublicationInfo`
#[must_use]
pub fn new(place: Option<String>, publisher: Option<String>, date: Option<String>) -> Self {
PublicationInfo {
place,
publisher,
date,
}
}
/// Extract publication year from the date field
///
/// Attempts to parse a 4-digit year from the publication date.
/// Looks for the first sequence of 4 digits.
///
/// # Examples
///
/// ```
/// use mrrc::PublicationInfo;
///
/// let info = PublicationInfo::new(None, None, Some("New York : Springer, 2015.".to_string()));
/// assert_eq!(info.publication_year(), Some(2015));
///
/// let info = PublicationInfo::new(None, None, Some("[s.l. : s.n.], 1999".to_string()));
/// assert_eq!(info.publication_year(), Some(1999));
/// ```
#[must_use]
pub fn publication_year(&self) -> Option<u32> {
if let Some(date_str) = &self.date {
// Look for first 4-digit sequence
let mut digits = String::new();
for ch in date_str.chars() {
if ch.is_ascii_digit() {
digits.push(ch);
if digits.len() == 4 {
return digits.parse().ok();
}
} else if !digits.is_empty() {
// Reset if we hit a non-digit after collecting some
digits.clear();
}
}
// Try one more time if we never hit 4 digits
if digits.is_empty() {
None
} else {
while digits.len() < 4 {
digits.push('0');
}
digits.parse().ok()
}
} else {
None
}
}
/// Format publication info as a complete statement
///
/// # Examples
///
/// ```
/// use mrrc::PublicationInfo;
///
/// let info = PublicationInfo::new(
/// Some("London".to_string()),
/// Some("Routledge".to_string()),
/// Some("2020".to_string()),
/// );
/// assert_eq!(
/// info.format_statement(),
/// "London : Routledge, 2020"
/// );
/// ```
#[must_use]
pub fn format_statement(&self) -> String {
let mut parts = Vec::new();
if let Some(place) = &self.place {
if !place.is_empty() {
parts.push(place.clone());
}
}
if let Some(publisher) = &self.publisher {
if !publisher.is_empty() {
parts.push(publisher.clone());
}
}
let base = if parts.is_empty() {
String::new()
} else {
parts.join(" : ")
};
if let Some(date) = &self.date {
if date.is_empty() {
base
} else if base.is_empty() {
date.clone()
} else {
format!("{base}, {date}")
}
} else {
base
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_validate_isbn10_valid() {
assert!(IsbnValidator::validate_isbn10("0306406152"));
assert!(IsbnValidator::validate_isbn10("043942089X"));
}
#[test]
fn test_validate_isbn10_invalid() {
assert!(!IsbnValidator::validate_isbn10("0306406153"));
assert!(!IsbnValidator::validate_isbn10("123"));
assert!(!IsbnValidator::validate_isbn10("abcd123456"));
}
#[test]
fn test_validate_isbn10_with_dashes() {
assert!(IsbnValidator::validate_isbn10("0-306-40615-2"));
assert!(IsbnValidator::validate_isbn10("0-439-42089-X"));
}
#[test]
fn test_validate_isbn13_valid() {
assert!(IsbnValidator::validate_isbn13("9780306406157"));
assert!(IsbnValidator::validate_isbn13("9780201379624")); // Valid ISBN-13
}
#[test]
fn test_validate_isbn13_invalid() {
assert!(!IsbnValidator::validate_isbn13("9780306406158"));
assert!(!IsbnValidator::validate_isbn13("1234567890123"));
assert!(!IsbnValidator::validate_isbn13("123"));
}
#[test]
fn test_validate_isbn13_with_dashes() {
assert!(IsbnValidator::validate_isbn13("978-0-306-40615-7"));
}
#[test]
fn test_validate_auto_detect() {
assert!(IsbnValidator::validate("0306406152")); // ISBN-10
assert!(IsbnValidator::validate("9780306406157")); // ISBN-13
assert!(!IsbnValidator::validate("123"));
}
#[test]
fn test_normalize() {
assert_eq!(
IsbnValidator::normalize("978-0-306-40615-7"),
"9780306406157"
);
assert_eq!(IsbnValidator::normalize("0-306-40615-2"), "0306406152");
assert_eq!(
IsbnValidator::normalize("978 0 306 40615 7"),
"9780306406157"
);
}
#[test]
fn test_publication_year_extraction() {
let info = PublicationInfo::new(None, None, Some("2020".to_string()));
assert_eq!(info.publication_year(), Some(2020));
let info = PublicationInfo::new(None, None, Some("New York : Springer, 2015.".to_string()));
assert_eq!(info.publication_year(), Some(2015));
let info = PublicationInfo::new(None, None, Some("[s.l. : s.n.], 1999".to_string()));
assert_eq!(info.publication_year(), Some(1999));
let info = PublicationInfo::new(None, None, None);
assert_eq!(info.publication_year(), None);
}
#[test]
fn test_format_statement_complete() {
let info = PublicationInfo::new(
Some("London".to_string()),
Some("Routledge".to_string()),
Some("2020".to_string()),
);
assert_eq!(info.format_statement(), "London : Routledge, 2020");
}
#[test]
fn test_format_statement_partial() {
let info =
PublicationInfo::new(Some("New York".to_string()), None, Some("1995".to_string()));
assert_eq!(info.format_statement(), "New York, 1995");
}
#[test]
fn test_format_statement_empty() {
let info = PublicationInfo::new(None, None, None);
assert_eq!(info.format_statement(), "");
}
}