Enum dicom_core::value::PrimitiveValue
source · pub enum PrimitiveValue {
Show 16 variants
Empty,
Strs(SmallVec<[String; 2]>),
Str(String),
Tags(SmallVec<[Tag; 2]>),
U8(SmallVec<[u8; 2]>),
I16(SmallVec<[i16; 2]>),
U16(SmallVec<[u16; 2]>),
I32(SmallVec<[i32; 2]>),
U32(SmallVec<[u32; 2]>),
I64(SmallVec<[i64; 2]>),
U64(SmallVec<[u64; 2]>),
F32(SmallVec<[f32; 2]>),
F64(SmallVec<[f64; 2]>),
Date(SmallVec<[DicomDate; 2]>),
DateTime(SmallVec<[DicomDateTime; 2]>),
Time(SmallVec<[DicomTime; 2]>),
}Expand description
An enum representing a primitive value from a DICOM element. The result of decoding an element’s data value may be one of the enumerated types depending on its content and value representation.
Multiple elements are contained in a smallvec vector,
conveniently aliased to the type C.
See the macro dicom_value! for a more intuitive means
of constructing these values.
Alternatively, From conversions into PrimitiveValue exist
for single element types,
including numeric types, String, and &str.
Example
let value = PrimitiveValue::from("Smith^John");
assert_eq!(value, PrimitiveValue::Str("Smith^John".to_string()));
assert_eq!(value.multiplicity(), 1);
let value = PrimitiveValue::from(512_u16);
assert_eq!(value, PrimitiveValue::U16(smallvec![512]));Variants§
Empty
No data. Usually employed for zero-length values.
Strs(SmallVec<[String; 2]>)
A sequence of strings. Used for AE, AS, PN, SH, CS, LO, UI and UC. Can also be used for IS, SS, DS, DA, DT and TM when decoding with format preservation.
Str(String)
A single string. Used for ST, LT, UT and UR, which are never multi-valued.
Tags(SmallVec<[Tag; 2]>)
A sequence of attribute tags. Used specifically for AT.
U8(SmallVec<[u8; 2]>)
The value is a sequence of unsigned 8-bit integers. Used for OB and UN.
I16(SmallVec<[i16; 2]>)
The value is a sequence of signed 16-bit integers. Used for SS.
U16(SmallVec<[u16; 2]>)
A sequence of unsigned 16-bit integers. Used for US and OW.
I32(SmallVec<[i32; 2]>)
A sequence of signed 32-bit integers. Used for SL and IS.
U32(SmallVec<[u32; 2]>)
A sequence of unsigned 32-bit integers. Used for UL and OL.
I64(SmallVec<[i64; 2]>)
A sequence of signed 64-bit integers. Used for SV.
U64(SmallVec<[u64; 2]>)
A sequence of unsigned 64-bit integers. Used for UV and OV.
F32(SmallVec<[f32; 2]>)
The value is a sequence of 32-bit floating point numbers. Used for OF and FL.
F64(SmallVec<[f64; 2]>)
The value is a sequence of 64-bit floating point numbers. Used for OD and FD, DS.
Date(SmallVec<[DicomDate; 2]>)
A sequence of dates with arbitrary precision. Used for the DA representation.
DateTime(SmallVec<[DicomDateTime; 2]>)
A sequence of date-time values with arbitrary precision. Used for the DT representation.
Time(SmallVec<[DicomTime; 2]>)
A sequence of time values with arbitrary precision. Used for the TM representation.
Implementations§
source§impl PrimitiveValue
impl PrimitiveValue
sourcepub fn multiplicity(&self) -> u32
pub fn multiplicity(&self) -> u32
Obtain the number of individual elements. This number may not match the DICOM value multiplicity in some value representations.
sourcepub fn calculate_byte_len(&self) -> usize
pub fn calculate_byte_len(&self) -> usize
Determine the length of the DICOM value in its encoded form.
In other words, this is the number of bytes that the value would need to occupy in a DICOM file, without compression and without the element header. The output is always an even number, so as to consider the mandatory trailing padding.
This method is particularly useful for presenting an estimated space occupation to the end user. However, consumers should not depend on this number for decoding or encoding values. The calculated number does not need to match the length of the original byte stream from where the value was originally decoded.
sourcepub fn to_str(&self) -> Cow<'_, str>
pub fn to_str(&self) -> Cow<'_, str>
Convert the primitive value into a string representation.
String values already encoded with the Str and Strs variants
are provided as is.
In the case of Strs, the strings are first joined together
with a backslash ('\\').
All other type variants are first converted to a string,
then joined together with a backslash.
Trailing whitespace is stripped from each string.
Note:
As the process of reading a DICOM value
may not always preserve its original nature,
it is not guaranteed that to_str() returns a string with
the exact same byte sequence as the one originally found
at the source of the value,
even for the string variants.
Therefore, this method is not reliable
for compliant DICOM serialization.
Examples
assert_eq!(
dicom_value!(Str, "Smith^John").to_str(),
"Smith^John",
);
assert_eq!(
dicom_value!(Date, DicomDate::from_y(2014)?).to_str(),
"2014",
);
assert_eq!(
dicom_value!(Str, "Smith^John\0").to_str(),
"Smith^John",
);
assert_eq!(
dicom_value!(Strs, [
"DERIVED",
"PRIMARY",
"WHOLE BODY",
"EMISSION",
])
.to_str(),
"DERIVED\\PRIMARY\\WHOLE BODY\\EMISSION",
);
Ok(())
}sourcepub fn to_raw_str(&self) -> Cow<'_, str>
pub fn to_raw_str(&self) -> Cow<'_, str>
Convert the primitive value into a raw string representation.
String values already encoded with the Str and Strs variants
are provided as is.
In the case of Strs, the strings are first joined together
with a backslash ('\\').
All other type variants are first converted to a string,
then joined together with a backslash.
This method keeps all trailing whitespace,
unlike to_str().
Note:
As the process of reading a DICOM value
may not always preserve its original nature,
it is not guaranteed that to_raw_str() returns a string with
the exact same byte sequence as the one originally found
at the source of the value,
even for the string variants.
Therefore, this method is not reliable
for compliant DICOM serialization.
Examples
assert_eq!(
dicom_value!(Str, "Smith^John\0").to_raw_str(),
"Smith^John\0",
);
assert_eq!(
dicom_value!(Date, DicomDate::from_ymd(2014, 10, 12).unwrap()).to_raw_str(),
"2014-10-12",
);
assert_eq!(
dicom_value!(Strs, [
"DERIVED",
" PRIMARY ",
"WHOLE BODY",
"EMISSION ",
])
.to_raw_str(),
"DERIVED\\ PRIMARY \\WHOLE BODY\\EMISSION ",
);sourcepub fn to_multi_str(&self) -> Cow<'_, [String]>
pub fn to_multi_str(&self) -> Cow<'_, [String]>
Convert the primitive value into a multi-string representation.
String values already encoded with the Str and Strs variants
are provided as is.
All other type variants are first converted to a string,
then collected into a vector.
Trailing whitespace is stripped from each string.
If keeping it is desired,
use to_raw_str().
Note:
As the process of reading a DICOM value
may not always preserve its original nature,
it is not guaranteed that to_multi_str() returns strings with
the exact same byte sequence as the one originally found
at the source of the value,
even for the string variants.
Therefore, this method is not reliable
for compliant DICOM serialization.
Examples
assert_eq!(
dicom_value!(Strs, [
"DERIVED",
"PRIMARY",
"WHOLE BODY ",
" EMISSION ",
])
.to_multi_str(),
&["DERIVED", "PRIMARY", "WHOLE BODY", " EMISSION"][..],
);
assert_eq!(
dicom_value!(Str, "Smith^John").to_multi_str(),
&["Smith^John"][..],
);
assert_eq!(
dicom_value!(Str, "Smith^John\0").to_multi_str(),
&["Smith^John"][..],
);
assert_eq!(
dicom_value!(Date, DicomDate::from_ym(2014, 10)?).to_multi_str(),
&["201410"][..],
);
assert_eq!(
dicom_value!(I64, [128, 256, 512]).to_multi_str(),
&["128", "256", "512"][..],
);
Ok(())
}sourcepub fn to_clean_str(&self) -> Cow<'_, str>
👎Deprecated: to_clean_str() is now deprecated in favour of using to_str() directly.
to_raw_str() replaces the old functionality of to_str() and maintains all trailing whitespace.
pub fn to_clean_str(&self) -> Cow<'_, str>
to_clean_str() is now deprecated in favour of using to_str() directly.
to_raw_str() replaces the old functionality of to_str() and maintains all trailing whitespace.Convert the primitive value into a clean string representation, removing unwanted whitespaces.
Leading whitespaces are preserved and are only removed at the end of a string
String values already encoded with the Str and Strs variants
are provided as is without the unwanted whitespaces.
In the case of Strs, the strings are first cleaned from whitespaces
and then joined together with a backslash ('\\').
All other type variants are first converted to a clean string,
then joined together with a backslash.
Note:
As the process of reading a DICOM value
may not always preserve its original nature,
it is not guaranteed that to_clean_str() returns a string with
the exact same byte sequence as the one originally found
at the source of the value,
even for the string variants.
Therefore, this method is not reliable
for compliant DICOM serialization.
Examples
assert_eq!(
dicom_value!(Str, "Smith^John ").to_clean_str(),
"Smith^John",
);
assert_eq!(
dicom_value!(Str, " Smith^John").to_clean_str(),
" Smith^John",
);
assert_eq!(
dicom_value!(Date, DicomDate::from_ymd(2014, 10, 12)?).to_clean_str(),
"2014-10-12",
);
assert_eq!(
dicom_value!(Strs, [
"DERIVED\0",
"PRIMARY",
" WHOLE BODY",
"EMISSION",
])
.to_clean_str(),
"DERIVED\\PRIMARY\\ WHOLE BODY\\EMISSION",
);
Ok(())
}sourcepub fn to_bytes(&self) -> Cow<'_, [u8]>
pub fn to_bytes(&self) -> Cow<'_, [u8]>
Retrieve this DICOM value as raw bytes.
Binary numeric values are returned with a reinterpretation of the holding vector’s occupied data block as bytes, without copying, under the platform’s native byte order.
String values already encoded with the Str and Strs variants
are provided as their respective bytes in UTF-8.
In the case of Strs, the strings are first joined together
with a backslash ('\\').
Other type variants are first converted to a string,
joined together with a backslash,
then turned into a byte vector.
For values which are inherently textual according the standard,
this is equivalent to calling as_bytes() after to_str().
Note:
As the process of reading a DICOM value
may not always preserve its original nature,
it is not guaranteed that to_bytes() returns the same byte sequence
as the one originally found at the source of the value.
Therefore, this method is not reliable
for compliant DICOM serialization.
Examples
U8 provides a straight, zero-copy slice of bytes.
assert_eq!(
PrimitiveValue::U8(smallvec![
1, 2, 5,
]).to_bytes(),
&[1, 2, 5][..],
);Other values are converted to text first.
assert_eq!(
PrimitiveValue::from("Smith^John").to_bytes(),
&b"Smith^John"[..],
);
assert_eq!(
PrimitiveValue::from(DicomDate::from_ymd(2014, 10, 12)?)
.to_bytes(),
&b"2014-10-12"[..],
);
assert_eq!(
dicom_value!(Strs, [
"DERIVED",
"PRIMARY",
"WHOLE BODY",
"EMISSION",
])
.to_bytes(),
&b"DERIVED\\PRIMARY\\WHOLE BODY\\EMISSION"[..],
);
Ok(())
}sourcepub fn to_int<T>(&self) -> Result<T, ConvertValueError>where
T: NumCast + FromStr<Err = ParseIntError>,
pub fn to_int<T>(&self) -> Result<T, ConvertValueError>where
T: NumCast + FromStr<Err = ParseIntError>,
Retrieve a single integer of type T from this value.
If the value is already represented as an integer, it is returned after a conversion to the target type. An error is returned if the integer cannot be represented by the given integer type. If the value is a string or sequence of strings, the first string is parsed to obtain an integer, potentially failing if the string does not represent a valid integer. The string is stripped of trailing whitespace before parsing, in order to account for the possible padding to even length. If the value is a sequence of U8 bytes, the bytes are individually interpreted as independent numbers. Otherwise, the operation fails.
Note that this method does not enable
the conversion of floating point numbers to integers via truncation.
If this is intentional,
retrieve a float via to_float32 or to_float64 instead,
then cast it to an integer.
Example
assert_eq!(
PrimitiveValue::I32(smallvec![
1, 2, 5,
])
.to_int::<u32>().ok(),
Some(1_u32),
);
assert_eq!(
PrimitiveValue::from("505 ").to_int::<i32>().ok(),
Some(505),
);sourcepub fn to_multi_int<T>(&self) -> Result<Vec<T>, ConvertValueError>where
T: NumCast + FromStr<Err = ParseIntError>,
pub fn to_multi_int<T>(&self) -> Result<Vec<T>, ConvertValueError>where
T: NumCast + FromStr<Err = ParseIntError>,
Retrieve a sequence of integers of type T from this value.
If the values is already represented as an integer,
it is returned after a NumCast conversion to the target type.
An error is returned if any of the integers cannot be represented
by the given integer type.
If the value is a string or sequence of strings,
each string is parsed to obtain an integer,
potentially failing if the string does not represent a valid integer.
The string is stripped of trailing whitespace before parsing,
in order to account for the possible padding to even length.
If the value is a sequence of U8 bytes,
the bytes are individually interpreted as independent numbers.
Otherwise, the operation fails.
Note that this method does not enable
the conversion of floating point numbers to integers via truncation.
If this is intentional,
retrieve a float via to_float32 or to_float64 instead,
then cast it to an integer.
Example
assert_eq!(
PrimitiveValue::I32(smallvec![
1, 2, 5,
])
.to_multi_int::<u32>().ok(),
Some(vec![1_u32, 2, 5]),
);
assert_eq!(
dicom_value!(Strs, ["5050", "23 "]).to_multi_int::<i32>().ok(),
Some(vec![5050, 23]),
);sourcepub fn to_float32(&self) -> Result<f32, ConvertValueError>
pub fn to_float32(&self) -> Result<f32, ConvertValueError>
Retrieve one single-precision floating point from this value.
If the value is already represented as a number,
it is returned after a conversion to f32.
An error is returned if the number cannot be represented
by the given number type.
If the value is a string or sequence of strings,
the first string is parsed to obtain a number,
potentially failing if the string does not represent a valid number.
The string is stripped of trailing whitespace before parsing,
in order to account for the possible padding to even length.
If the value is a sequence of U8 bytes,
the bytes are individually interpreted as independent numbers.
Otherwise, the operation fails.
Example
assert_eq!(
PrimitiveValue::F32(smallvec![
1.5, 2., 5.,
])
.to_float32().ok(),
Some(1.5_f32),
);
assert_eq!(
PrimitiveValue::from("-6.75 ").to_float32().ok(),
Some(-6.75),
);sourcepub fn to_multi_float32(&self) -> Result<Vec<f32>, ConvertValueError>
pub fn to_multi_float32(&self) -> Result<Vec<f32>, ConvertValueError>
Retrieve a sequence of single-precision floating point numbers from this value.
If the value is already represented as numbers,
they are returned after a conversion to f32.
An error is returned if any of the numbers cannot be represented
by an f32.
If the value is a string or sequence of strings,
the strings are parsed to obtain a number,
potentially failing if the string does not represent a valid number.
The string is stripped of trailing whitespace before parsing,
in order to account for the possible padding to even length.
If the value is a sequence of U8 bytes,
the bytes are individually interpreted as independent numbers.
Otherwise, the operation fails.
Example
assert_eq!(
PrimitiveValue::F32(smallvec![
1.5, 2., 5.,
])
.to_multi_float32().ok(),
Some(vec![1.5_f32, 2., 5.]),
);
assert_eq!(
PrimitiveValue::from("-6.75 ").to_multi_float32().ok(),
Some(vec![-6.75]),
);sourcepub fn to_float64(&self) -> Result<f64, ConvertValueError>
pub fn to_float64(&self) -> Result<f64, ConvertValueError>
Retrieve one double-precision floating point from this value.
If the value is already represented as a number,
it is returned after a conversion to f64.
An error is returned if the number cannot be represented
by the given number type.
If the value is a string or sequence of strings,
the first string is parsed to obtain a number,
potentially failing if the string does not represent a valid number.
If the value is a sequence of U8 bytes,
the bytes are individually interpreted as independent numbers.
Otherwise, the operation fails.
Example
assert_eq!(
PrimitiveValue::F64(smallvec![
1.5, 2., 5.,
])
.to_float64().ok(),
Some(1.5_f64),
);
assert_eq!(
PrimitiveValue::from("-6.75 ").to_float64().ok(),
Some(-6.75),
);sourcepub fn to_multi_float64(&self) -> Result<Vec<f64>, ConvertValueError>
pub fn to_multi_float64(&self) -> Result<Vec<f64>, ConvertValueError>
Retrieve a sequence of double-precision floating point numbers from this value.
If the value is already represented as numbers,
they are returned after a conversion to f64.
An error is returned if any of the numbers cannot be represented
by an f64.
If the value is a string or sequence of strings,
the strings are parsed to obtain a number,
potentially failing if the string does not represent a valid number.
The string is stripped of trailing whitespace before parsing,
in order to account for the possible padding to even length.
If the value is a sequence of U8 bytes,
the bytes are individually interpreted as independent numbers.
Otherwise, the operation fails.
Example
assert_eq!(
PrimitiveValue::F64(smallvec![
1.5, 2., 5.,
])
.to_multi_float64().ok(),
Some(vec![1.5_f64, 2., 5.]),
);
assert_eq!(
PrimitiveValue::from("-6.75 ").to_multi_float64().ok(),
Some(vec![-6.75]),
);sourcepub fn to_naive_date(&self) -> Result<NaiveDate, ConvertValueError>
pub fn to_naive_date(&self) -> Result<NaiveDate, ConvertValueError>
Retrieve a single chrono::NaiveDate from this value.
If the value is already represented as a precise DicomDate, it is converted
to a NaiveDate value. It fails for imprecise values.
If the value is a string or sequence of strings,
the first string is decoded to obtain a date, potentially failing if the
string does not represent a valid date.
If the value is a sequence of U8 bytes, the bytes are
first interpreted as an ASCII character string.
Users are advised that this method is DICOM compliant and a full date representation of YYYYMMDD is required. Otherwise, the operation fails.
Partial precision dates are handled by DicomDate, which can be retrieved
by .to_date().
Example
assert_eq!(
PrimitiveValue::Date(smallvec![
DicomDate::from_ymd(2014, 10, 12)?,
])
.to_naive_date().ok(),
Some(NaiveDate::from_ymd(2014, 10, 12)),
);
assert_eq!(
PrimitiveValue::Strs(smallvec![
"20141012".to_string(),
])
.to_naive_date().ok(),
Some(NaiveDate::from_ymd(2014, 10, 12)),
);
assert!(
PrimitiveValue::Str("201410".to_string())
.to_naive_date().is_err()
);sourcepub fn to_multi_naive_date(&self) -> Result<Vec<NaiveDate>, ConvertValueError>
pub fn to_multi_naive_date(&self) -> Result<Vec<NaiveDate>, ConvertValueError>
Retrieve the full sequence of chrono::NaiveDates from this value.
If the value is already represented as a sequence of precise DicomDate values,
it is converted. It fails for imprecise values.
If the value is a string or sequence of strings,
the strings are decoded to obtain a date, potentially failing if
any of the strings does not represent a valid date.
If the value is a sequence of U8 bytes, the bytes are
first interpreted as an ASCII character string,
then as a backslash-separated list of dates.
Users are advised that this method is DICOM compliant and a full date representation of YYYYMMDD is required. Otherwise, the operation fails.
Partial precision dates are handled by DicomDate, which can be retrieved
by .to_multi_date().
Example
assert_eq!(
PrimitiveValue::Date(smallvec![
DicomDate::from_ymd(2014, 10, 12)?,
]).to_multi_naive_date().ok(),
Some(vec![NaiveDate::from_ymd(2014, 10, 12)]),
);
assert_eq!(
PrimitiveValue::Strs(smallvec![
"20141012".to_string(),
"20200828".to_string(),
]).to_multi_naive_date().ok(),
Some(vec![
NaiveDate::from_ymd(2014, 10, 12),
NaiveDate::from_ymd(2020, 8, 28),
]),
);sourcepub fn to_date(&self) -> Result<DicomDate, ConvertValueError>
pub fn to_date(&self) -> Result<DicomDate, ConvertValueError>
Retrieve a single DicomDate from this value.
If the value is already represented as a DicomDate, it is returned.
If the value is a string or sequence of strings,
the first string is decoded to obtain a DicomDate, potentially failing if the
string does not represent a valid DicomDate.
If the value is a sequence of U8 bytes, the bytes are
first interpreted as an ASCII character string.
Unlike Rust’s chrono::NaiveDate, DicomDate allows for missing date components.
DicomDate implements AsRange trait, so specific chrono::NaiveDate values can be retrieved.
Example
use dicom_core::value::{AsRange, DicomDate};
let value = PrimitiveValue::Str("200002".into());
let date = value.to_date()?;
// it is not precise, day of month is unspecified
assert_eq!(
date.is_precise(),
false
);
assert_eq!(
date.earliest()?,
NaiveDate::from_ymd(2000,2,1)
);
assert_eq!(
date.latest()?,
NaiveDate::from_ymd(2000,2,29)
);
assert!(date.exact().is_err());
let date = PrimitiveValue::Str("20000201".into()).to_date()?;
assert_eq!(
date.is_precise(),
true
);
// .to_naive_date() works only for precise values
assert_eq!(
date.exact()?,
date.to_naive_date()?
);
sourcepub fn to_multi_date(&self) -> Result<Vec<DicomDate>, ConvertValueError>
pub fn to_multi_date(&self) -> Result<Vec<DicomDate>, ConvertValueError>
Retrieve the full sequence of DicomDates from this value.
Example
use dicom_core::value::DicomDate;
assert_eq!(
dicom_value!(Strs, ["201410", "2020", "20200101"])
.to_multi_date()?,
vec![
DicomDate::from_ym(2014, 10)?,
DicomDate::from_y(2020)?,
DicomDate::from_ymd(2020, 1, 1)?
]);
sourcepub fn to_naive_time(&self) -> Result<NaiveTime, ConvertValueError>
pub fn to_naive_time(&self) -> Result<NaiveTime, ConvertValueError>
Retrieve a single chrono::NaiveTime from this value.
If the value is represented as a precise DicomTime,
it is converted to a NaiveTime.
It fails for imprecise values,
as in, those which do not specify up to at least the seconds.
If the value is a string or sequence of strings,
the first string is decoded to obtain a time, potentially failing if the
string does not represent a valid time.
If the value is a sequence of U8 bytes, the bytes are
first interpreted as an ASCII character string.
Otherwise, the operation fails.
Users are advised that this method requires at least 1 out of 6 digits of the second fraction .F to be present. Otherwise, the operation fails.
Partial precision times are handled by DicomTime,
which can be retrieved by .to_time().
Example
assert_eq!(
PrimitiveValue::from(DicomTime::from_hms(11, 2, 45)?).to_naive_time().ok(),
Some(NaiveTime::from_hms(11, 2, 45)),
);
assert_eq!(
PrimitiveValue::from("110245.78").to_naive_time().ok(),
Some(NaiveTime::from_hms_milli(11, 2, 45, 780)),
);sourcepub fn to_multi_naive_time(&self) -> Result<Vec<NaiveTime>, ConvertValueError>
pub fn to_multi_naive_time(&self) -> Result<Vec<NaiveTime>, ConvertValueError>
Retrieve the full sequence of chrono::NaiveTimes from this value.
If the value is already represented as a sequence of precise DicomTime values,
it is converted to a sequence of NaiveTime values. It fails for imprecise values.
If the value is a string or sequence of strings,
the strings are decoded to obtain a date, potentially failing if
any of the strings does not represent a valid date.
If the value is a sequence of U8 bytes, the bytes are
first interpreted as an ASCII character string,
then as a backslash-separated list of times.
Otherwise, the operation fails.
Users are advised that this method requires at least 1 out of 6 digits of the second fraction .F to be present. Otherwise, the operation fails.
Partial precision times are handled by DicomTime,
which can be retrieved by .to_multi_time().
Example
assert_eq!(
PrimitiveValue::from(DicomTime::from_hms(22, 58, 2)?).to_multi_naive_time().ok(),
Some(vec![NaiveTime::from_hms(22, 58, 2)]),
);
assert_eq!(
PrimitiveValue::Strs(smallvec![
"225802.1".to_string(),
"225916.742388".to_string(),
]).to_multi_naive_time().ok(),
Some(vec![
NaiveTime::from_hms_micro(22, 58, 2, 100_000),
NaiveTime::from_hms_micro(22, 59, 16, 742_388),
]),
);sourcepub fn to_time(&self) -> Result<DicomTime, ConvertValueError>
pub fn to_time(&self) -> Result<DicomTime, ConvertValueError>
Retrieve a single DicomTime from this value.
If the value is already represented as a time, it is converted into DicomTime. If the value is a string or sequence of strings, the first string is decoded to obtain a DicomTime, potentially failing if the string does not represent a valid DicomTime. If the value is a sequence of U8 bytes, the bytes are first interpreted as an ASCII character string.
Unlike Rust’s chrono::NaiveTime, DicomTime allows for missing time components.
DicomTime implements AsRange trait, so specific chrono::NaiveTime values can be retrieved.
Example
use dicom_core::value::{AsRange, DicomTime};
let value = PrimitiveValue::Str("10".into());
let time = value.to_time()?;
// is not precise, minute, second and second fraction are unspecified
assert_eq!(
time.is_precise(),
false
);
assert_eq!(
time.earliest()?,
NaiveTime::from_hms(10,0,0)
);
assert_eq!(
time.latest()?,
NaiveTime::from_hms_micro(10,59,59,999_999)
);
assert!(time.exact().is_err());
let second = PrimitiveValue::Str("101259".into());
// not a precise value, fraction of second is unspecified
assert!(second.to_time()?.exact().is_err());
// .to_naive_time() yields a result, for at least second precision values
// second fraction defaults to zeros
assert_eq!(
second.to_time()?.to_naive_time()?,
NaiveTime::from_hms(10,12,59)
);
let fraction6 = PrimitiveValue::Str("101259.123456".into());
let fraction5 = PrimitiveValue::Str("101259.12345".into());
// is not precise, last digit of second fraction is unspecified
assert!(
fraction5.to_time()?.exact().is_err()
);
assert!(
fraction6.to_time()?.exact().is_ok()
);
assert_eq!(
fraction6.to_time()?.exact()?,
fraction6.to_time()?.to_naive_time()?
);
sourcepub fn to_multi_time(&self) -> Result<Vec<DicomTime>, ConvertValueError>
pub fn to_multi_time(&self) -> Result<Vec<DicomTime>, ConvertValueError>
Retrieve the full sequence of DicomTimes from this value.
If the value is already represented as a time, it is converted into DicomTime. If the value is a string or sequence of strings, the first string is decoded to obtain a DicomTime, potentially failing if the string does not represent a valid DicomTime. If the value is a sequence of U8 bytes, the bytes are first interpreted as an ASCII character string.
Unlike Rust’s chrono::NaiveTime, DicomTime allows for missing time components.
DicomTime implements AsRange trait, so specific chrono::NaiveTime values can be retrieved.
Example
use dicom_core::value::DicomTime;
assert_eq!(
PrimitiveValue::Strs(smallvec![
"2258".to_string(),
"225916.000742".to_string(),
]).to_multi_time()?,
vec![
DicomTime::from_hm(22, 58)?,
DicomTime::from_hms_micro(22, 59, 16, 742)?,
],
);
sourcepub fn to_chrono_datetime(
&self,
default_offset: FixedOffset
) -> Result<DateTime<FixedOffset>, ConvertValueError>
pub fn to_chrono_datetime(
&self,
default_offset: FixedOffset
) -> Result<DateTime<FixedOffset>, ConvertValueError>
Retrieve a single chrono::DateTime from this value.
If the value is already represented as a precise DicomDateTime,
it is converted to chrono::DateTime. Imprecise values fail.
If the value is a string or sequence of strings,
the first string is decoded to obtain a date-time,
potentially failing if the string does not represent a valid time.
If the value in its textual form does not present a time zone,
default_offset is used.
If the value is a sequence of U8 bytes, the bytes are
first interpreted as an ASCII character string.
Otherwise, the operation fails.
Users of this method are advised to retrieve the default time zone offset from the same source of the DICOM value.
Users are advised that this method requires at least 1 out of 6 digits of the second fraction .F to be present. Otherwise, the operation fails.
Partial precision date-times are handled by DicomDateTime,
which can be retrieved by .to_datetime().
Example
let default_offset = FixedOffset::east(0);
// full accuracy `DicomDateTime` can be converted
assert_eq!(
PrimitiveValue::from(
DicomDateTime::from_date_and_time(
DicomDate::from_ymd(2012, 12, 21)?,
DicomTime::from_hms_micro(9, 30, 1, 1)?,
default_offset
)?
).to_chrono_datetime(default_offset)?,
FixedOffset::east(0)
.ymd(2012, 12, 21)
.and_hms_micro(9, 30, 1, 1)
,
);
assert_eq!(
PrimitiveValue::from("20121221093001.1")
.to_chrono_datetime(default_offset).ok(),
Some(FixedOffset::east(0)
.ymd(2012, 12, 21)
.and_hms_micro(9, 30, 1, 100_000)
),
);sourcepub fn to_multi_chrono_datetime(
&self,
default_offset: FixedOffset
) -> Result<Vec<DateTime<FixedOffset>>, ConvertValueError>
pub fn to_multi_chrono_datetime(
&self,
default_offset: FixedOffset
) -> Result<Vec<DateTime<FixedOffset>>, ConvertValueError>
Retrieve the full sequence of chrono::DateTimes from this value.
If the value is already represented as a sequence of precise DicomDateTime values,
it is converted to a sequence of chrono::DateTime values. Imprecise values fail.
If the value is a string or sequence of strings,
the strings are decoded to obtain a date, potentially failing if
any of the strings does not represent a valid date.
If the value is a sequence of U8 bytes, the bytes are
first interpreted as an ASCII character string,
then as a backslash-separated list of date-times.
Otherwise, the operation fails.
Users are advised that this method requires at least 1 out of 6 digits of the second fraction .F to be present. Otherwise, the operation fails.
Partial precision date-times are handled by DicomDateTime,
which can be retrieved by .to_multi_datetime().
Example
let default_offset = FixedOffset::east(0);
// full accuracy `DicomDateTime` can be converted
assert_eq!(
PrimitiveValue::from(
DicomDateTime::from_date_and_time(
DicomDate::from_ymd(2012, 12, 21)?,
DicomTime::from_hms_micro(9, 30, 1, 123_456)?,
default_offset
)?
).to_multi_chrono_datetime(default_offset)?,
vec![FixedOffset::east(0)
.ymd(2012, 12, 21)
.and_hms_micro(9, 30, 1, 123_456)
],
);
assert_eq!(
PrimitiveValue::Strs(smallvec![
"20121221093001.123".to_string(),
"20180102100123.123456".to_string(),
]).to_multi_chrono_datetime(default_offset).ok(),
Some(vec![
FixedOffset::east(0)
.ymd(2012, 12, 21)
.and_hms_micro(9, 30, 1, 123_000),
FixedOffset::east(0)
.ymd(2018, 1, 2)
.and_hms_micro(10, 1, 23, 123_456)
]),
);sourcepub fn to_datetime(
&self,
default_offset: FixedOffset
) -> Result<DicomDateTime, ConvertValueError>
pub fn to_datetime(
&self,
default_offset: FixedOffset
) -> Result<DicomDateTime, ConvertValueError>
Retrieve a single DicomDateTime from this value.
If the value is already represented as a date-time, it is converted into DicomDateTime. If the value is a string or sequence of strings, the first string is decoded to obtain a DicomDateTime, potentially failing if the string does not represent a valid DicomDateTime. If the value is a sequence of U8 bytes, the bytes are first interpreted as an ASCII character string.
Unlike Rust’s chrono::DateTime, DicomDateTime allows for missing date or time components.
DicomDateTime implements AsRange trait, so specific chrono::DateTime values can be retrieved.
Example
use dicom_core::value::{DicomDateTime, AsRange, DateTimeRange};
let default_offset = FixedOffset::east(0);
let dt_value = PrimitiveValue::from("20121221093001.1").to_datetime(default_offset)?;
assert_eq!(
dt_value.earliest()?,
FixedOffset::east(0)
.ymd(2012, 12, 21)
.and_hms_micro(9, 30, 1, 100_000)
);
assert_eq!(
dt_value.latest()?,
FixedOffset::east(0)
.ymd(2012, 12, 21)
.and_hms_micro(9, 30, 1, 199_999)
);
let dt_value = PrimitiveValue::from("20121221093001.123456").to_datetime(default_offset)?;
// date-time has all components
assert_eq!(dt_value.is_precise(), true);
assert!(dt_value.exact().is_ok());
// .to_chrono_datetime() only works for a precise value
assert_eq!(
dt_value.to_chrono_datetime()?,
dt_value.exact()?
);
// ranges are inclusive, for a precise value, two identical values are returned
assert_eq!(
dt_value.range()?,
DateTimeRange::from_start_to_end(
FixedOffset::east(0)
.ymd(2012, 12, 21)
.and_hms_micro(9, 30, 1, 123_456),
FixedOffset::east(0)
.ymd(2012, 12, 21)
.and_hms_micro(9, 30, 1, 123_456))?
);sourcepub fn to_multi_datetime(
&self,
default_offset: FixedOffset
) -> Result<Vec<DicomDateTime>, ConvertValueError>
pub fn to_multi_datetime(
&self,
default_offset: FixedOffset
) -> Result<Vec<DicomDateTime>, ConvertValueError>
Retrieve the full sequence of DicomDateTimes from this value.
sourcepub fn to_date_range(&self) -> Result<DateRange, ConvertValueError>
pub fn to_date_range(&self) -> Result<DateRange, ConvertValueError>
Retrieve a single DateRange from this value.
If the value is already represented as a DicomDate, it is converted into DateRange - todo.
If the value is a string or sequence of strings,
the first string is decoded to obtain a DateRange, potentially failing if the
string does not represent a valid DateRange.
If the value is a sequence of U8 bytes, the bytes are
first interpreted as an ASCII character string.
Example
use chrono::{NaiveDate};
use dicom_core::value::{DateRange};
let da_range = PrimitiveValue::from("2012-201305").to_date_range()?;
assert_eq!(
da_range.start(),
Some(&NaiveDate::from_ymd(2012, 1, 1))
);
assert_eq!(
da_range.end(),
Some(&NaiveDate::from_ymd(2013, 05, 31))
);
let range_from = PrimitiveValue::from("2012-").to_date_range()?;
assert!(range_from.end().is_none());
sourcepub fn to_time_range(&self) -> Result<TimeRange, ConvertValueError>
pub fn to_time_range(&self) -> Result<TimeRange, ConvertValueError>
Retrieve a single TimeRange from this value.
If the value is already represented as a DicomTime, it is converted into TimeRange - todo.
If the value is a string or sequence of strings,
the first string is decoded to obtain a TimeRange, potentially failing if the
string does not represent a valid DateRange.
If the value is a sequence of U8 bytes, the bytes are
first interpreted as an ASCII character string.
Example
use chrono::{NaiveTime};
use dicom_core::value::{TimeRange};
let tm_range = PrimitiveValue::from("02-153000.123").to_time_range()?;
// null components default to zeros
assert_eq!(
tm_range.start(),
Some(&NaiveTime::from_hms(2, 0, 0))
);
// unspecified part of second fraction defaults to latest possible
assert_eq!(
tm_range.end(),
Some(&NaiveTime::from_hms_micro(15, 30, 0, 123_999))
);
let range_from = PrimitiveValue::from("01-").to_time_range()?;
assert!(range_from.end().is_none());
sourcepub fn to_datetime_range(
&self,
offset: FixedOffset
) -> Result<DateTimeRange, ConvertValueError>
pub fn to_datetime_range(
&self,
offset: FixedOffset
) -> Result<DateTimeRange, ConvertValueError>
Retrieve a single DateTimeRange from this value.
If the value is already represented as a DicomDateTime, it is converted into DateTimeRange.
If the value is a string or sequence of strings,
the first string is decoded to obtain a DateTimeRange, potentially failing if the
string does not represent a valid DateTimeRange.
If the value is a sequence of U8 bytes, the bytes are
first interpreted as an ASCII character string.
Example
use chrono::{DateTime, FixedOffset, TimeZone};
use dicom_core::value::{DateTimeRange};
let offset = FixedOffset::east(3600);
let dt_range = PrimitiveValue::from("19920101153020.123+0500-1993").to_datetime_range(offset)?;
// default offset override with parsed value
assert_eq!(
dt_range.start(),
Some(&FixedOffset::east(5*3600).ymd(1992, 1, 1)
.and_hms_micro(15, 30, 20, 123_000)
)
);
// null components default to latest possible
assert_eq!(
dt_range.end(),
Some(&offset.ymd(1993, 12, 31)
.and_hms_micro(23, 59, 59, 999_999)
)
);
let range_from = PrimitiveValue::from("2012-").to_datetime_range(offset)?;
assert!(range_from.end().is_none());
sourcepub fn to_person_name(&self) -> Result<PersonName<'_>, ConvertValueError>
pub fn to_person_name(&self) -> Result<PersonName<'_>, ConvertValueError>
Retrieve a single PersonName from this value.
If the value is a string or sequence of strings,
the first string is split to obtain a PersonName.
Example
use dicom_core::value::PersonName;
let value = PrimitiveValue::from("Tooms^Victor^Eugene");
// PersonName contains borrowed values
let pn = value.to_person_name()?;
assert_eq!(pn.given(), Some("Victor"));
assert_eq!(pn.middle(), Some("Eugene"));
assert!(pn.prefix().is_none());
let value2 = PrimitiveValue::from(pn);
assert_eq!(value, value2);
source§impl PrimitiveValue
impl PrimitiveValue
Per variant, strongly checked getters to DICOM values.
Conversions from one representation to another do not take place when using these methods.
sourcepub fn string(&self) -> Result<&str, CastValueError>
pub fn string(&self) -> Result<&str, CastValueError>
Get a single string value.
If it contains multiple strings, only the first one is returned.
An error is returned if the variant is not compatible.
To enable conversions of other variants to a textual representation,
see to_str() instead.
sourcepub fn strings(&self) -> Result<&[String], CastValueError>
pub fn strings(&self) -> Result<&[String], CastValueError>
Get the inner sequence of string values
if the variant is either Str or Strs.
An error is returned if the variant is not compatible.
To enable conversions of other variants to a textual representation,
see to_str() instead.
sourcepub fn tag(&self) -> Result<Tag, CastValueError>
pub fn tag(&self) -> Result<Tag, CastValueError>
Get a single value of the requested type. If it contains multiple values, only the first one is returned. An error is returned if the variant is not compatible.
Get a sequence of values of the requested type without copying. An error is returned if the variant is not compatible.
sourcepub fn date(&self) -> Result<DicomDate, CastValueError>
pub fn date(&self) -> Result<DicomDate, CastValueError>
Get a single value of the requested type. If it contains multiple values, only the first one is returned. An error is returned if the variant is not compatible.
sourcepub fn dates(&self) -> Result<&[DicomDate], CastValueError>
pub fn dates(&self) -> Result<&[DicomDate], CastValueError>
Get a sequence of values of the requested type without copying. An error is returned if the variant is not compatible.
sourcepub fn time(&self) -> Result<DicomTime, CastValueError>
pub fn time(&self) -> Result<DicomTime, CastValueError>
Get a single value of the requested type. If it contains multiple values, only the first one is returned. An error is returned if the variant is not compatible.
sourcepub fn times(&self) -> Result<&[DicomTime], CastValueError>
pub fn times(&self) -> Result<&[DicomTime], CastValueError>
Get a sequence of values of the requested type without copying. An error is returned if the variant is not compatible.
sourcepub fn datetime(&self) -> Result<DicomDateTime, CastValueError>
pub fn datetime(&self) -> Result<DicomDateTime, CastValueError>
Get a single value of the requested type. If it contains multiple values, only the first one is returned. An error is returned if the variant is not compatible.
sourcepub fn datetimes(&self) -> Result<&[DicomDateTime], CastValueError>
pub fn datetimes(&self) -> Result<&[DicomDateTime], CastValueError>
Get a sequence of values of the requested type without copying. An error is returned if the variant is not compatible.
sourcepub fn uint8(&self) -> Result<u8, CastValueError>
pub fn uint8(&self) -> Result<u8, CastValueError>
Get a single value of the requested type. If it contains multiple values, only the first one is returned. An error is returned if the variant is not compatible.
sourcepub fn uint8_slice(&self) -> Result<&[u8], CastValueError>
pub fn uint8_slice(&self) -> Result<&[u8], CastValueError>
Get a sequence of values of the requested type without copying. An error is returned if the variant is not compatible.
sourcepub fn uint16(&self) -> Result<u16, CastValueError>
pub fn uint16(&self) -> Result<u16, CastValueError>
Get a single value of the requested type. If it contains multiple values, only the first one is returned. An error is returned if the variant is not compatible.
sourcepub fn uint16_slice(&self) -> Result<&[u16], CastValueError>
pub fn uint16_slice(&self) -> Result<&[u16], CastValueError>
Get a sequence of values of the requested type without copying. An error is returned if the variant is not compatible.
sourcepub fn int16(&self) -> Result<i16, CastValueError>
pub fn int16(&self) -> Result<i16, CastValueError>
Get a single value of the requested type. If it contains multiple values, only the first one is returned. An error is returned if the variant is not compatible.
sourcepub fn int16_slice(&self) -> Result<&[i16], CastValueError>
pub fn int16_slice(&self) -> Result<&[i16], CastValueError>
Get a sequence of values of the requested type without copying. An error is returned if the variant is not compatible.
sourcepub fn uint32(&self) -> Result<u32, CastValueError>
pub fn uint32(&self) -> Result<u32, CastValueError>
Get a single value of the requested type. If it contains multiple values, only the first one is returned. An error is returned if the variant is not compatible.
sourcepub fn uint32_slice(&self) -> Result<&[u32], CastValueError>
pub fn uint32_slice(&self) -> Result<&[u32], CastValueError>
Get a sequence of values of the requested type without copying. An error is returned if the variant is not compatible.
sourcepub fn int32(&self) -> Result<i32, CastValueError>
pub fn int32(&self) -> Result<i32, CastValueError>
Get a single value of the requested type. If it contains multiple values, only the first one is returned. An error is returned if the variant is not compatible.
sourcepub fn int32_slice(&self) -> Result<&[i32], CastValueError>
pub fn int32_slice(&self) -> Result<&[i32], CastValueError>
Get a sequence of values of the requested type without copying. An error is returned if the variant is not compatible.
sourcepub fn int64(&self) -> Result<i64, CastValueError>
pub fn int64(&self) -> Result<i64, CastValueError>
Get a single value of the requested type. If it contains multiple values, only the first one is returned. An error is returned if the variant is not compatible.
sourcepub fn int64_slice(&self) -> Result<&[i64], CastValueError>
pub fn int64_slice(&self) -> Result<&[i64], CastValueError>
Get a sequence of values of the requested type without copying. An error is returned if the variant is not compatible.
sourcepub fn uint64(&self) -> Result<u64, CastValueError>
pub fn uint64(&self) -> Result<u64, CastValueError>
Get a single value of the requested type. If it contains multiple values, only the first one is returned. An error is returned if the variant is not compatible.
sourcepub fn uint64_slice(&self) -> Result<&[u64], CastValueError>
pub fn uint64_slice(&self) -> Result<&[u64], CastValueError>
Get a sequence of values of the requested type without copying. An error is returned if the variant is not compatible.
sourcepub fn float32(&self) -> Result<f32, CastValueError>
pub fn float32(&self) -> Result<f32, CastValueError>
Get a single value of the requested type. If it contains multiple values, only the first one is returned. An error is returned if the variant is not compatible.
sourcepub fn float32_slice(&self) -> Result<&[f32], CastValueError>
pub fn float32_slice(&self) -> Result<&[f32], CastValueError>
Get a sequence of values of the requested type without copying. An error is returned if the variant is not compatible.
sourcepub fn float64(&self) -> Result<f64, CastValueError>
pub fn float64(&self) -> Result<f64, CastValueError>
Get a single value of the requested type. If it contains multiple values, only the first one is returned. An error is returned if the variant is not compatible.
sourcepub fn float64_slice(&self) -> Result<&[f64], CastValueError>
pub fn float64_slice(&self) -> Result<&[f64], CastValueError>
Get a sequence of values of the requested type without copying. An error is returned if the variant is not compatible.
sourcepub fn extend_str<T>(
&mut self,
strings: impl IntoIterator<Item = T>
) -> Result<(), ModifyValueError>where
T: Into<String>,
pub fn extend_str<T>(
&mut self,
strings: impl IntoIterator<Item = T>
) -> Result<(), ModifyValueError>where
T: Into<String>,
Extend a textual value by appending more strings to an existing text or empty value.
An error is returned if the current value is not textual.
Example
use dicom_core::dicom_value;
let mut value = dicom_value!(Strs, ["Hello"]);
value.extend_str(["DICOM"])?;
assert_eq!(value.to_string(), "Hello\\DICOM");sourcepub fn extend_i32(
&mut self,
numbers: impl IntoIterator<Item = i32>
) -> Result<(), ModifyValueError>
pub fn extend_i32(
&mut self,
numbers: impl IntoIterator<Item = i32>
) -> Result<(), ModifyValueError>
Extend a value of numbers by appending 32-bit signed integers to an existing value.
The value may be empty or already contain numeric or textual values.
If the current value is textual, the numbers provided are converted to text. For the case of numeric values, the given numbers are converted to the current number type through casting.
An error is returned
if the current value is not compatible with the insertion of integers,
such as Tag or Date.
Example
use dicom_core::dicom_value;
let mut value = dicom_value!(I32, [1, 2]);
value.extend_i32([5])?;
assert_eq!(value.to_multi_int::<i32>()?, vec![1, 2, 5]);
let mut value = dicom_value!(Strs, ["City"]);
value.extend_i32([17])?;
assert_eq!(value.to_string(), "City\\17");sourcepub fn extend_u32(
&mut self,
numbers: impl IntoIterator<Item = u32>
) -> Result<(), ModifyValueError>
pub fn extend_u32(
&mut self,
numbers: impl IntoIterator<Item = u32>
) -> Result<(), ModifyValueError>
Extend a value of numbers by appending 32-bit unsigned integers to an existing value.
The value may be empty or already contain numeric or textual values.
If the current value is textual, the numbers provided are converted to text. For the case of numeric values, the given numbers are converted to the current number type through casting.
An error is returned
if the current value is not compatible with the insertion of integers,
such as Tag or Date.
Example
use dicom_core::dicom_value;
let mut value = dicom_value!(U32, [1, 2]);
value.extend_u32([5])?;
assert_eq!(value.to_multi_int::<u32>()?, vec![1, 2, 5]);
let mut value = dicom_value!(Strs, ["City"]);
value.extend_u32([17])?;
assert_eq!(value.to_string(), "City\\17");Trait Implementations§
source§impl Clone for PrimitiveValue
impl Clone for PrimitiveValue
source§fn clone(&self) -> PrimitiveValue
fn clone(&self) -> PrimitiveValue
1.0.0 · source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read moresource§impl Debug for PrimitiveValue
impl Debug for PrimitiveValue
source§impl DicomValueType for PrimitiveValue
impl DicomValueType for PrimitiveValue
source§fn value_type(&self) -> ValueType
fn value_type(&self) -> ValueType
source§fn cardinality(&self) -> usize
fn cardinality(&self) -> usize
source§impl Display for PrimitiveValue
impl Display for PrimitiveValue
The output of this method is equivalent to calling the method to_str