Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Move SubfieldCode into primitives module #822

Merged
merged 1 commit into from
Sep 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 11 additions & 11 deletions pica-record/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,23 @@
//! select).

pub use error::PicaError;
pub use subfield::{SubfieldCode, SubfieldValue, SubfieldValueRef};
pub use primitives::SubfieldCode;

/// Parsers recognizing low-level primitives (e.g. subfield codes).
#[rustfmt::skip]
pub mod parser_v2 {
pub use super::subfield::parse_subfield_code;
pub mod parser {
pub use super::primitives::parse_subfield_code;
// TODO

pub use super::subfield::parse_subfield_value_ref;
pub use super::occurrence::parse_occurrence_digits;
pub use super::tag::parse_tag;
}

mod primitives;

pub use subfield::{SubfieldValue, SubfieldValueRef};

// -----{ TODO }-----------------------------------------

mod error;
Expand All @@ -51,11 +59,3 @@ pub use occurrence::{Occurrence, OccurrenceRef};
pub use record::{ByteRecord, Record, RecordRef, StringRecord};
pub use subfield::{Subfield, SubfieldRef};
pub use tag::{Tag, TagRef};

/// Parsers recognizing low-level primitives (e.g. subfield codes).
#[rustfmt::skip]
pub mod parser {
pub use super::occurrence::parse_occurrence_digits;
pub use super::subfield::parse_subfield_code;
pub use super::tag::parse_tag;
}
173 changes: 173 additions & 0 deletions pica-record/src/primitives/code.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
use std::fmt::{self, Display};

use crate::PicaError;

/// A PICA+ subfield code.
///
/// This type represents a PICA+ subfield code, which is a ASCII
/// alpha-numeric chracter.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
pub struct SubfieldCode(char);

impl SubfieldCode {
/// Creates a new subfield code.
///
/// # Error
///
/// This functions fails if the given code is not an ASCII
/// alpha-numeric character.
///
/// # Example
///
/// ```rust
/// use pica_record::SubfieldCode;
///
/// let code = SubfieldCode::new('a')?;
/// assert_eq!(code, 'a');
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn new(code: char) -> Result<Self, PicaError> {
if !code.is_ascii_alphanumeric() {
return Err(PicaError::InvalidSubfieldCode(code));
}

Ok(Self(code))
}

/// Creates a subfied code without checking for validity.
///
/// # Safety
///
/// The caller *must* ensure that the given subfield code is valid.
///
/// # Example
///
/// ```rust
/// use pica_record::SubfieldCode;
///
/// let code = SubfieldCode::from_unchecked('a');
/// assert_eq!(code, 'a');
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn from_unchecked<T: Into<char>>(code: T) -> Self {
Self(code.into())
}

/// Returns the subfield code as a byte (`u8`).
///
/// # Example
///
/// ```rust
/// use pica_record::SubfieldCode;
///
/// let code = SubfieldCode::new('a')?;
/// assert_eq!(code.as_byte(), b'a');
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
pub fn as_byte(&self) -> u8 {
self.0 as u8
}
}

impl Display for SubfieldCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}

impl PartialEq<char> for SubfieldCode {
fn eq(&self, code: &char) -> bool {
self.0 == *code
}
}

impl PartialEq<char> for &SubfieldCode {
fn eq(&self, code: &char) -> bool {
self.0 == *code
}
}

impl TryFrom<char> for SubfieldCode {
type Error = PicaError;

fn try_from(code: char) -> Result<Self, Self::Error> {
Self::new(code)
}
}

#[cfg(feature = "arbitrary")]
impl quickcheck::Arbitrary for SubfieldCode {
fn arbitrary(g: &mut quickcheck::Gen) -> Self {
let code = (1..)
.map(|_| char::arbitrary(g))
.find(char::is_ascii_alphanumeric)
.unwrap();

Self(code)
}
}

#[cfg(test)]
mod tests {
use quickcheck_macros::quickcheck;

use super::*;

#[quickcheck]
fn test_subfield_code_new(input: char) {
let result = SubfieldCode::new(input);

if input.is_ascii_alphanumeric() {
assert_eq!(result.unwrap(), SubfieldCode(input));
} else {
assert_eq!(
result.unwrap_err(),
PicaError::InvalidSubfieldCode(input)
);
}
}

#[test]
fn test_subfield_code_from_unchecked() {
for c in '0'..='z' {
if c.is_ascii_alphanumeric() {
assert_eq!(
SubfieldCode::from_unchecked(c),
SubfieldCode(c)
);
}
}
}

#[test]
fn test_subfield_code_as_byte() {
for c in '0'..='z' {
if c.is_ascii_alphanumeric() {
let code = SubfieldCode::new(c).unwrap();
assert_eq!(code.as_byte(), c as u8);
}
}
}

#[test]
fn test_subfield_code_try_from_char() {
for c in '0'..='z' {
if c.is_ascii_alphanumeric() {
assert_eq!(
SubfieldCode::try_from(c).unwrap(),
SubfieldCode(c)
);
} else {
assert_eq!(
SubfieldCode::try_from(c).unwrap_err(),
PicaError::InvalidSubfieldCode(c)
);
}
}
}
}
5 changes: 5 additions & 0 deletions pica-record/src/primitives/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
pub use code::SubfieldCode;
pub use parse::parse_subfield_code;

mod code;
mod parse;
30 changes: 30 additions & 0 deletions pica-record/src/primitives/parse.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
use winnow::prelude::*;
use winnow::token::one_of;

use crate::SubfieldCode;

/// Parse a PICA+ subfield code.
pub fn parse_subfield_code(i: &mut &[u8]) -> PResult<SubfieldCode> {
one_of((b'0'..=b'9', b'a'..=b'z', b'A'..=b'Z'))
.map(SubfieldCode::from_unchecked)
.parse_next(i)
}

#[cfg(test)]
mod tests {
use quickcheck_macros::quickcheck;

use super::*;

#[quickcheck]
fn test_parse_arbitrary_subfield_code(code: u8) {
if code.is_ascii_alphanumeric() {
assert_eq!(
parse_subfield_code.parse(&[code]).unwrap(),
SubfieldCode::from_unchecked(char::from(code))
);
} else {
assert!(parse_subfield_code.parse(&[code]).is_err());
}
}
}
Loading