roman-numerals-rs

Crates.ioroman-numerals-rs
lib.rsroman-numerals-rs
version1.0.0
sourcesrc
created_at2024-11-10 00:57:02.752105
updated_at2024-11-10 00:57:02.752105
descriptionManipulate well-formed Roman numerals
homepage
repositoryhttps://github.com/AA-Turner/roman-numerals/
max_upload_size
id1442464
size25,235
Adam Turner (AA-Turner)

documentation

README

roman-numerals

A library for manipulating well-formed Roman numerals.

Integers between 1 and 3,999 (inclusive) are supported. Numbers beyond this range will return an OutOfRangeError.

The classical system of roman numerals requires that the same character may not appear more than thrice consecutively, meaning that 'MMMCMXCIX' (3,999) is the largest well-formed Roman numeral. The smallest is 'I' (1), as there is no symbol for zero in Roman numerals.

Both upper- and lower-case formatting of roman numerals are supported, and likewise for parsing strings, although the entire string must be of the same case. Numerals that do not adhere to the classical form are rejected with an InvalidRomanNumeralError.

Example usage

Create a roman numeral

use roman_numerals_rs::RomanNumeral;

let num = RomanNumeral::new(16)?;
assert_eq!(num.to_string(), "XVI");

let num: RomanNumeral = "XVI".parse()?;
assert_eq!(num.as_u16(), 16);

let num: RomanNumeral = 3_999.try_into().unwrap();
println!("{}", num);  // MMMCMXCIX

Convert a roman numeral to a string

use roman_numerals_rs::RomanNumeral;

let num = RomanNumeral::new(16)?;
assert_eq!(num.to_string(), "XVI");
assert_eq!(num.to_uppercase(), "XVI");
assert_eq!(num.to_lowercase(), "xvi");
assert_eq!(format!("{:X}", num), "XVI");
assert_eq!(format!("{:x}", num), "xvi");

Extract the decimal value of a roman numeral

use roman_numerals_rs::RomanNumeral;

let num = RomanNumeral::new(42)?;
assert_eq!(num.as_u16(), 42);

Invalid input

use core::str::FromStr;
use roman_numerals_rs::{RomanNumeral, InvalidRomanNumeralError, OutOfRangeError};

let res = RomanNumeral::from_str("Spam!");
assert!(matches!(res.unwrap_err(), InvalidRomanNumeralError));

let res = "CLL".parse::<RomanNumeral>();
assert!(matches!(res.unwrap_err(), InvalidRomanNumeralError));

let res = RomanNumeral::new(0);
assert!(matches!(res.unwrap_err(), OutOfRangeError));

let res = RomanNumeral::new(4_000);
assert!(matches!(res.unwrap_err(), OutOfRangeError));

Licence

This project is placed in the public domain or under the terms of the 'Zero Clause BSD licence', whichever is more permissive.

Commit count: 3

cargo fmt