use fhir_types::r4::count::Count;
use fhir_types::r4::primitives::Code;
use fhir_types::r4::primitives::Decimal;
use fhir_types::r4::primitives::Integer;
use fhir_types::r4::primitives::PositiveInt;
use fhir_types::r4::primitives::UnsignedInt;
use fhir_types::r4::primitives::Uri;
use fhir_types::r4::quantity::Quantity;
use openehr_rm::v1_2::data_types::quantity::dv_count::DvCount;
use crate::engine::lens::Fallback;
use crate::engine::lens::Lens;
use crate::engine::lens::LensError;
use crate::engine::lens::code_phrase::text_of;
use crate::engine::lens::number::decimal_text;
use crate::engine::lens::number::narrow;
use crate::engine::lens::number::point;
use crate::engine::lens::number::whole;
use crate::engine::lens::quantity::UCUM;
use crate::model::ast::keyword::Direction;
pub const INTEGER_CELL: &str = "DV_COUNT against integer";
pub const UNSIGNED_INT_CELL: &str = "DV_COUNT against unsignedInt";
pub const POSITIVE_INT_CELL: &str = "DV_COUNT against positiveInt";
pub const QUANTITY_CELL: &str = "DV_COUNT against Quantity";
pub const COUNT_CELL: &str = "DV_COUNT against Count";
pub const UNITY: &str = "1";
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct CountLens;
impl Lens<DvCount, Integer> for CountLens {
fn cell(&self) -> &'static str {
INTEGER_CELL
}
fn get(&self, source: &DvCount) -> Result<Integer, LensError> {
point(source.magnitude_status.as_deref(), INTEGER_CELL)?;
narrow(source.magnitude, INTEGER_CELL, "DV_COUNT.magnitude").map(Integer::from)
}
fn put(&self, view: &Integer, existing: Option<&DvCount>) -> Result<DvCount, LensError> {
let value = view.value.ok_or(LensError::Missing {
cell: INTEGER_CELL,
attribute: "DV_COUNT.magnitude",
direction: Direction::FhirToOpenehr,
})?;
Ok(counted(i64::from(value), existing))
}
fn fallbacks(&self, _view: &Integer) -> Vec<Fallback> {
Vec::new()
}
}
impl Lens<DvCount, Quantity> for CountLens {
fn cell(&self) -> &'static str {
QUANTITY_CELL
}
fn get(&self, source: &DvCount) -> Result<Quantity, LensError> {
point(source.magnitude_status.as_deref(), QUANTITY_CELL)?;
Ok(Quantity {
value: Some(Decimal::from(source.magnitude.to_string().as_str())),
..Quantity::default()
})
}
fn put(&self, view: &Quantity, existing: Option<&DvCount>) -> Result<DvCount, LensError> {
unbounded(view.comparator.as_ref(), QUANTITY_CELL)?;
let text = decimal_text(view.value.as_ref(), QUANTITY_CELL, "DV_COUNT.magnitude")?;
Ok(counted(
whole(text, QUANTITY_CELL, "Quantity.value")?,
existing,
))
}
fn fallbacks(&self, _view: &Quantity) -> Vec<Fallback> {
Vec::new()
}
}
impl Lens<DvCount, Count> for CountLens {
fn cell(&self) -> &'static str {
COUNT_CELL
}
fn get(&self, source: &DvCount) -> Result<Count, LensError> {
point(source.magnitude_status.as_deref(), COUNT_CELL)?;
Ok(Count {
value: Some(Decimal::from(source.magnitude.to_string().as_str())),
system: Some(Uri::from(UCUM)),
code: Some(Code::from(UNITY)),
..Count::default()
})
}
fn put(&self, view: &Count, existing: Option<&DvCount>) -> Result<DvCount, LensError> {
unbounded(view.comparator.as_ref(), COUNT_CELL)?;
let code = text_of(view.code.as_ref().map(|code| &code.value));
if let Some(other) = code.filter(|&code| code != UNITY) {
return Err(LensError::Shape {
cell: COUNT_CELL,
attribute: "Count.code",
found: String::from(other),
reason: "R4 cnt-3 fixes the code of a Count at 1",
direction: Direction::FhirToOpenehr,
});
}
let text = decimal_text(view.value.as_ref(), COUNT_CELL, "DV_COUNT.magnitude")?;
Ok(counted(whole(text, COUNT_CELL, "Count.value")?, existing))
}
fn fallbacks(&self, _view: &Count) -> Vec<Fallback> {
Vec::new()
}
}
impl Lens<DvCount, UnsignedInt> for CountLens {
fn cell(&self) -> &'static str {
UNSIGNED_INT_CELL
}
fn get(&self, source: &DvCount) -> Result<UnsignedInt, LensError> {
point(source.magnitude_status.as_deref(), UNSIGNED_INT_CELL)?;
restricted(
source.magnitude,
0,
UNSIGNED_INT_CELL,
"a FHIR unsignedInt is an integer from 0",
)
.map(UnsignedInt::from)
}
fn put(&self, view: &UnsignedInt, existing: Option<&DvCount>) -> Result<DvCount, LensError> {
let value = view.value.ok_or(LensError::Missing {
cell: UNSIGNED_INT_CELL,
attribute: "DV_COUNT.magnitude",
direction: Direction::FhirToOpenehr,
})?;
Ok(counted(i64::from(value), existing))
}
fn fallbacks(&self, _view: &UnsignedInt) -> Vec<Fallback> {
Vec::new()
}
}
impl Lens<DvCount, PositiveInt> for CountLens {
fn cell(&self) -> &'static str {
POSITIVE_INT_CELL
}
fn get(&self, source: &DvCount) -> Result<PositiveInt, LensError> {
point(source.magnitude_status.as_deref(), POSITIVE_INT_CELL)?;
restricted(
source.magnitude,
1,
POSITIVE_INT_CELL,
"a FHIR positiveInt is an integer from 1",
)
.map(PositiveInt::from)
}
fn put(&self, view: &PositiveInt, existing: Option<&DvCount>) -> Result<DvCount, LensError> {
let value = view.value.ok_or(LensError::Missing {
cell: POSITIVE_INT_CELL,
attribute: "DV_COUNT.magnitude",
direction: Direction::FhirToOpenehr,
})?;
Ok(counted(i64::from(value), existing))
}
fn fallbacks(&self, _view: &PositiveInt) -> Vec<Fallback> {
Vec::new()
}
}
fn restricted(
magnitude: i64,
least: u32,
cell: &'static str,
reason: &'static str,
) -> Result<u32, LensError> {
let integer = narrow(magnitude, cell, "DV_COUNT.magnitude")?;
u32::try_from(integer)
.ok()
.filter(|value| *value >= least)
.ok_or_else(|| LensError::Shape {
cell,
attribute: "DV_COUNT.magnitude",
found: magnitude.to_string(),
reason,
direction: Direction::OpenehrToFhir,
})
}
fn unbounded(comparator: Option<&Code>, cell: &'static str) -> Result<(), LensError> {
match text_of(comparator.map(|code| &code.value)) {
Some(found) => Err(LensError::Shape {
cell,
attribute: "Quantity.comparator",
found: String::from(found),
reason: "DV_COUNT.adoc gives comparator no openEHR row",
direction: Direction::FhirToOpenehr,
}),
None => Ok(()),
}
}
fn counted(magnitude: i64, existing: Option<&DvCount>) -> DvCount {
DvCount {
normal_status: existing.and_then(|held| held.normal_status.clone()),
normal_range: existing.and_then(|held| held.normal_range.clone()),
other_reference_ranges: existing.and_then(|held| held.other_reference_ranges.clone()),
magnitude_status: existing.and_then(|held| held.magnitude_status.clone()),
accuracy: existing.and_then(|held| held.accuracy),
accuracy_is_percent: existing.and_then(|held| held.accuracy_is_percent),
magnitude,
}
}
#[cfg(test)]
mod tests {
use super::CountLens;
use crate::engine::lens::Lens;
use crate::engine::lens::LensError;
use crate::engine::lens::quantity::UCUM;
use fhir_types::r4::count::Count;
use fhir_types::r4::primitives::Code;
use fhir_types::r4::primitives::Decimal;
use fhir_types::r4::primitives::Integer;
use fhir_types::r4::primitives::PositiveInt;
use fhir_types::r4::primitives::UnsignedInt;
use fhir_types::r4::quantity::Quantity;
use openehr_rm::v1_2::data_types::quantity::dv_count::DvCount;
use proptest::option;
use proptest::prop_compose;
use proptest::prop_oneof;
use proptest::proptest;
use proptest::strategy::Just;
fn count(magnitude: i64) -> DvCount {
DvCount {
normal_status: None,
normal_range: None,
other_reference_ranges: None,
magnitude_status: None,
accuracy: None,
accuracy_is_percent: None,
magnitude,
}
}
prop_compose! {
fn counted()(
magnitude in i64::from(i32::MIN)..=i64::from(i32::MAX),
magnitude_status in prop_oneof![Just(None), Just(Some(String::from("=")))],
accuracy in option::of(0i32..10),
) -> DvCount {
DvCount { magnitude_status, accuracy: accuracy.map(f64::from), ..count(magnitude) }
}
}
proptest! {
#[test]
fn integer_get_put(source in counted()) {
let view: Integer = CountLens.get(&source).expect("the count travels");
let back = CountLens.put(&view, Some(&source)).expect("the view is complete");
assert_eq!(back, source, "GetPut failed for {source:?}");
}
#[test]
fn integer_put_get(value in proptest::num::i32::ANY) {
let view = Integer::from(value);
let back: DvCount = CountLens.put(&view, None).expect("the view is complete");
let again: Integer = CountLens.get(&back).expect("the count travels");
assert_eq!(again, view, "PutGet failed for {view:?}");
}
#[test]
fn unsigned_int_get_put(magnitude in 0..=i64::from(i32::MAX)) {
let source = count(magnitude);
let view: UnsignedInt = CountLens.get(&source).expect("the count travels");
let back = CountLens.put(&view, Some(&source)).expect("the view is complete");
assert_eq!(back, source, "GetPut failed for {source:?}");
}
#[test]
fn unsigned_int_put_get(value in 0..=i32::MAX.unsigned_abs()) {
let view = UnsignedInt::from(value);
let back: DvCount = CountLens.put(&view, None).expect("the view is complete");
let again: UnsignedInt = CountLens.get(&back).expect("the count travels");
assert_eq!(again, view, "PutGet failed for {view:?}");
}
#[test]
fn positive_int_get_put(magnitude in 1..=i64::from(i32::MAX)) {
let source = count(magnitude);
let view: PositiveInt = CountLens.get(&source).expect("the count travels");
let back = CountLens.put(&view, Some(&source)).expect("the view is complete");
assert_eq!(back, source, "GetPut failed for {source:?}");
}
#[test]
fn positive_int_put_get(value in 1..=i32::MAX.unsigned_abs()) {
let view = PositiveInt::from(value);
let back: DvCount = CountLens.put(&view, None).expect("the view is complete");
let again: PositiveInt = CountLens.get(&back).expect("the count travels");
assert_eq!(again, view, "PutGet failed for {view:?}");
}
#[test]
fn quantity_get_put(source in counted()) {
let view: Quantity = CountLens.get(&source).expect("the count travels");
let back = CountLens.put(&view, Some(&source)).expect("the view is complete");
assert_eq!(back, source, "GetPut failed for {source:?}");
}
#[test]
fn quantity_put_get(source in counted()) {
let view: Quantity = CountLens.get(&source).expect("the count travels");
let back: DvCount = CountLens.put(&view, None).expect("the view is complete");
let again: Quantity = CountLens.get(&back).expect("the count travels");
assert_eq!(again, view, "PutGet failed for {view:?}");
}
#[test]
fn count_get_put(source in counted()) {
let view: Count = CountLens.get(&source).expect("the count travels");
let back = CountLens.put(&view, Some(&source)).expect("the view is complete");
assert_eq!(back, source, "GetPut failed for {source:?}");
}
#[test]
fn count_put_get(source in counted()) {
let view: Count = CountLens.get(&source).expect("the count travels");
let back: DvCount = CountLens.put(&view, None).expect("the view is complete");
let again: Count = CountLens.get(&back).expect("the count travels");
assert_eq!(again, view, "PutGet failed for {view:?}");
}
}
#[test]
fn a_count_writes_the_code_one_in_ucum() {
let view: Count = CountLens.get(&count(4)).expect("the count travels");
assert_eq!(
(
view.value.and_then(|value| value.value),
view.code.and_then(|code| code.value),
view.system.and_then(|system| system.value),
),
(
Some(String::from("4")),
Some(String::from("1")),
Some(String::from(UCUM)),
)
);
}
#[test]
fn a_count_outside_the_fhir_integer_range_is_refused() {
let error = Lens::<DvCount, Integer>::get(&CountLens, &count(i64::from(i32::MAX) + 1))
.expect_err("a FHIR integer is 32-bit");
assert!(
matches!(error, LensError::Shape { attribute, .. } if attribute == "DV_COUNT.magnitude"),
"the refusal names the magnitude: {error}"
);
}
#[test]
fn a_negative_count_is_no_unsigned_int() {
let error = Lens::<DvCount, UnsignedInt>::get(&CountLens, &count(-1))
.expect_err("an unsignedInt is from 0");
assert!(
matches!(error, LensError::Shape { attribute, ref found, .. } if attribute == "DV_COUNT.magnitude" && found == "-1"),
"the refusal names the magnitude: {error}"
);
}
#[test]
fn a_zero_count_is_an_unsigned_int_and_no_positive_int() {
let zero: UnsignedInt = CountLens.get(&count(0)).expect("0 is an unsignedInt");
assert_eq!(zero.value, Some(0));
let error = Lens::<DvCount, PositiveInt>::get(&CountLens, &count(0))
.expect_err("a positiveInt is from 1");
assert!(
matches!(error, LensError::Shape { attribute, ref found, .. } if attribute == "DV_COUNT.magnitude" && found == "0"),
"the refusal names the magnitude: {error}"
);
}
#[test]
fn a_count_beyond_the_fhir_integer_range_is_no_unsigned_int() {
let error = Lens::<DvCount, UnsignedInt>::get(&CountLens, &count(i64::from(i32::MAX) + 1))
.expect_err("an unsignedInt ends at 2,147,483,647");
assert!(matches!(error, LensError::Shape { .. }), "{error}");
}
#[test]
fn a_fractional_quantity_is_no_count() {
let view = Quantity {
value: Some(Decimal::from("2.5")),
..Quantity::default()
};
let error = CountLens.put(&view, None).expect_err("a count is whole");
assert!(
matches!(error, LensError::Shape { attribute, .. } if attribute == "Quantity.value"),
"the refusal names the value: {error}"
);
}
#[test]
fn a_count_coded_otherwise_is_refused() {
let view = Count {
value: Some(Decimal::from("2")),
code: Some(Code::from("mg")),
..Count::default()
};
let error = CountLens
.put(&view, None)
.expect_err("cnt-3 fixes the code");
assert!(
matches!(error, LensError::Shape { attribute, .. } if attribute == "Count.code"),
"the refusal names the code: {error}"
);
}
#[test]
fn a_comparator_going_in_is_refused() {
let view = Quantity {
value: Some(Decimal::from("2")),
comparator: Some(Code::from("<")),
..Quantity::default()
};
assert!(CountLens.put(&view, None).is_err());
let count = Count {
value: Some(Decimal::from("2")),
comparator: Some(Code::from(">=")),
..Count::default()
};
assert!(CountLens.put(&count, None).is_err());
}
#[test]
fn a_bounded_count_has_no_comparator_to_carry_it() {
let source = DvCount {
magnitude_status: Some(String::from("<")),
..count(4)
};
assert!(Lens::<DvCount, Integer>::get(&CountLens, &source).is_err());
assert!(Lens::<DvCount, Quantity>::get(&CountLens, &source).is_err());
assert!(Lens::<DvCount, Count>::get(&CountLens, &source).is_err());
}
}