Skip to main content

Metadata

Struct Metadata 

Source
pub struct Metadata { /* private fields */ }
Expand description

A complete SigMF metadata document (.sigmf-meta).

Holds the global object, the captures and annotations arrays, and any unrecognized top-level keys. When parsed with Metadata::from_slice (or from_reader / from_path) the exact input bytes are retained and exposed through Metadata::original_bytes; any mutation through this type’s methods discards them.

§Examples

use sigmf::capture::Capture;
use sigmf::global::{Datatype, Global};
use sigmf::meta::Metadata;

let global = Global::new("1.2.6", "cf32_le".parse::<Datatype>()?);
let mut metadata = Metadata::new(global, Vec::new(), vec![Capture::new(0)]);
metadata.set_sample_rate(1_000_000.0);

let bytes = metadata.to_vec()?;
let parsed = Metadata::from_slice(&bytes)?;
assert_eq!(parsed.get_sample_rate(), Some(1_000_000.0));
assert_eq!(parsed.captures().len(), 1);

Implementations§

Source§

impl Metadata

Source

pub fn global_extension<T: SigmfExtension>(&self) -> Result<T, SigmfError>

Reads extension T from the fields of the global object.

Only the keys listed in SigmfExtension::FIELDS are considered; absent keys are simply omitted before deserialization.

§Errors

Returns SigmfError::InvalidMetadata if T’s scope is not ExtensionScope::Global or the fields do not deserialize into T.

Source

pub fn set_global_extension<T: SigmfExtension>( &mut self, extension: &T, ) -> Result<(), SigmfError>

Writes extension T into the global object.

All of T’s declared FIELDS are first removed, then the serialized fields are inserted, so fields omitted by serialization (e.g. None with skip_serializing_if) are cleared. core:extensions is not modified.

§Errors

Returns SigmfError::InvalidMetadata if T’s scope is not ExtensionScope::Global, extension does not serialize to a JSON object, or it serializes a key not listed in FIELDS; returns SigmfError::Serde if serialization fails. The metadata is unchanged on error.

Source

pub fn remove_global_extension<T: SigmfExtension>( &mut self, ) -> Result<(), SigmfError>

Removes all of extension T’s declared fields from the global object.

core:extensions is not modified.

§Errors

Returns SigmfError::InvalidMetadata if T’s scope is not ExtensionScope::Global.

Source§

impl Metadata

Source

pub fn new( global: Global, annotations: Vec<Annotation>, captures: Vec<Capture>, ) -> Self

Creates a metadata document from its global object and its annotations and captures arrays.

The document has no top-level extension fields and no retained original bytes. No validation is performed; see Metadata::validate.

§Examples
use sigmf::capture::Capture;
use sigmf::global::{Datatype, Global};
use sigmf::meta::Metadata;

let global = Global::new("1.2.6", "ri16_le".parse::<Datatype>()?);
let metadata = Metadata::new(global, Vec::new(), vec![Capture::new(0)]);
assert_eq!(metadata.get_version(), "1.2.6");
assert!(metadata.annotations().is_empty());
Source

pub fn from_slice(bytes: &[u8]) -> Result<Self, SigmfError>

Parses a metadata document from JSON bytes.

Before deserializing, the input is checked for duplicate object keys and for the basic shape required by SigMF: a global object with string core:version and core:datatype, captures and annotations arrays whose entries are objects with a non-negative integer core:sample_start, and no explicit null for optional core fields. Unknown keys are preserved. The input bytes are retained and available via Metadata::original_bytes.

This does not run full semantic validation; see Metadata::validate.

§Errors
§Examples
use sigmf::meta::Metadata;

let json = br#"{
    "global": {"core:version": "1.2.6", "core:datatype": "cf32_le"},
    "captures": [{"core:sample_start": 0, "core:frequency": 915e6}],
    "annotations": []
}"#;
let metadata = Metadata::from_slice(json)?;
assert_eq!(metadata.get_datatype().to_string(), "cf32_le");
assert_eq!(metadata.captures()[0].frequency, Some(915e6));
assert_eq!(metadata.original_bytes(), Some(&json[..]));

assert!(Metadata::from_slice(br#"{"global": {}}"#).is_err());
Source

pub fn to_vec(&self) -> Result<Vec<u8>, SigmfError>

Serializes the document as compact JSON.

Optional fields that are unset are omitted, and extension fields are written back alongside the core fields. The output is freshly serialized and is not guaranteed to match Metadata::original_bytes.

§Errors

Returns crate::SigmfError::Serde if serialization fails.

Source

pub fn to_vec_pretty(&self) -> Result<Vec<u8>, SigmfError>

Serializes the document as pretty-printed (indented) JSON.

§Errors

Returns crate::SigmfError::Serde if serialization fails.

Source

pub fn write_to( &self, writer: impl Write, policy: ValidationPolicy, ) -> Result<String, SigmfError>

Validates the document under policy, then writes its compact JSON serialization to writer.

Returns the SHA-512 digest (lowercase hex) of the exact bytes written, suitable for a collection’s core:streams hash entry. Validation warnings do not prevent writing.

§Errors
Source

pub fn save_new( &self, path: impl AsRef<Path>, policy: ValidationPolicy, ) -> Result<String, SigmfError>

Validates the document under policy and atomically writes it to a new file at path.

The JSON is written to a temporary sibling file, synced, and then published under path without overwriting an existing file. Returns the SHA-512 digest (lowercase hex) of the bytes written.

§Errors
Source

pub fn replace_atomic( &self, path: impl AsRef<Path>, policy: ValidationPolicy, ) -> Result<String, SigmfError>

Validates the document under policy and atomically writes it to path, replacing any existing file.

The JSON is written to a temporary sibling file, synced, and renamed over path, so readers observe either the old or the new contents. Returns the SHA-512 digest (lowercase hex) of the bytes written.

§Errors
Source

pub fn from_reader(reader: impl Read) -> Result<Self, SigmfError>

Reads and parses a metadata document from reader.

At most 1 MB plus one byte is read; the bytes are then parsed with Metadata::from_slice.

§Errors
Source

pub fn from_path(path: impl AsRef<Path>) -> Result<Self, SigmfError>

Opens the .sigmf-meta file at path and parses it with Metadata::from_reader.

§Errors

Returns crate::SigmfError::Io if the file cannot be opened, or any error returned by Metadata::from_reader.

Source

pub fn original_bytes(&self) -> Option<&[u8]>

Returns the exact bytes this document was parsed from, if it was parsed and has not been modified since.

Returns None for documents built with Metadata::new and after calling a mutating method on Metadata (setters, insert_*, or add_*).

Source

pub fn original_digest(&self) -> Result<Option<String>, SigmfError>

Returns the SHA-512 digest (lowercase hex) of Metadata::original_bytes, or None if no original bytes are retained.

This is the hash a collection’s core:streams entry should record for an unmodified, previously parsed metadata file.

§Errors

Returns a crate::SigmfError if hashing fails (currently infallible).

Source

pub fn hash(&self) -> Result<String, SigmfError>

Returns the SHA-512 digest (lowercase hex) of the document’s compact serialization, as produced by Metadata::to_vec.

This may differ from Metadata::original_digest even for an unmodified document, because re-serialization does not preserve the original formatting.

§Errors

Returns crate::SigmfError::Serde if serialization fails.

Source

pub fn global(&self) -> &Global

Returns the global object.

Source

pub fn captures(&self) -> &[Capture]

Returns the captures array in document order.

Source

pub fn annotations(&self) -> &[Annotation]

Returns the annotations array in document order.

Source

pub fn extra_fields(&self) -> &Map<String, Value>

Returns the unrecognized top-level keys (anything other than global, captures, and annotations).

Source

pub fn capture_at(&self, sample_index: Integer) -> Option<&Capture>

Returns the capture segment that contains sample_index.

This is the capture with the greatest core:sample_start that is less than or equal to sample_index, regardless of the order of the captures array. Returns None if every capture starts after sample_index or there are no captures. If several captures share that start, the last one in document order is returned.

Source

pub fn annotations_intersecting_samples( &self, start: Integer, sample_count: Integer, ) -> Result<Vec<&Annotation>, SigmfError>

Returns the annotations whose sample range overlaps the half-open range [start, start + sample_count).

An annotation’s range is [core:sample_start, core:sample_start + core:sample_count). Annotations without core:sample_count, or with a count of zero, never match. An empty query range returns no annotations. Results are in document order.

§Errors

Returns crate::SigmfError::InvalidRange if start + sample_count overflows, or if a candidate annotation’s end overflows.

Source

pub fn annotations_intersecting_frequency( &self, lower: Number, upper: Number, ) -> Result<Vec<&Annotation>, SigmfError>

Returns the annotations whose frequency range overlaps the closed interval [lower, upper] (in Hz).

Only annotations that set both core:freq_lower_edge and core:freq_upper_edge are considered; touching edges count as an overlap. Results are in document order.

§Errors

Returns crate::SigmfError::InvalidRange if either bound is not finite or if lower > upper.

Source

pub fn diff(&self, other: &Self) -> Result<Vec<MetadataChange>, SigmfError>

Computes the leaf-level differences between this document and other.

Both documents are serialized to JSON and compared recursively. Objects are compared key by key and arrays index by index, so inserting an element shifts every later index. Each reported change carries an RFC 6901 JSON Pointer; the result is empty when the serializations are equal.

§Errors

Returns crate::SigmfError::Serde if either document fails to serialize.

Source

pub fn insert_extra( &mut self, key: impl Into<String>, value: Value, ) -> Result<Option<Value>, SigmfError>

Inserts or replaces a top-level extension key.

Returns the previous value under key, if any, and clears the retained original bytes. The key is not checked against declared extensions.

§Errors

Returns crate::SigmfError::InvalidMetadata if key is global, captures, or annotations.

Source

pub fn insert_global_extra( &mut self, key: impl Into<String>, value: Value, ) -> Result<Option<Value>, SigmfError>

Inserts or replaces an extension key in the global object.

Returns the previous value under key, if any. Delegates to crate::global::Global::insert_extra. The retained original bytes are cleared even if the insertion is rejected.

§Errors

Returns crate::SigmfError::InvalidMetadata if key names a core global field (for example core:version).

Source

pub fn edit(&mut self) -> MetadataEdit<'_>

Starts a transactional edit of this document.

Changes are made to a draft copy; they are applied to self only when MetadataEdit::commit succeeds, and discarded if the MetadataEdit is dropped.

Source

pub fn set_version(&mut self, version: String)

Sets the global core:version field: the SigMF specification version string.

Clears the retained original bytes.

Source

pub fn set_datatype(&mut self, datatype: Datatype)

Sets the global core:datatype field: the sample format of the dataset.

Clears the retained original bytes.

Source

pub fn set_sample_rate(&mut self, sample_rate: Number)

Sets the global core:sample_rate field: the sample rate in samples per second.

Clears the retained original bytes.

Source

pub fn set_author(&mut self, author: String)

Sets the global core:author field: the author of the recording.

Clears the retained original bytes.

Source

pub fn set_collection(&mut self, collection_str: String)

Sets the global core:collection field: the base name of the SigMF collection this recording belongs to.

Clears the retained original bytes.

Source

pub fn set_data_doi(&mut self, data_doi: String)

Sets the global core:data_doi field: the DOI of the dataset file.

Clears the retained original bytes.

Source

pub fn set_description(&mut self, description: String)

Sets the global core:description field: the free-text description of the recording.

Clears the retained original bytes.

Source

pub fn set_hw(&mut self, hw: String)

Sets the global core:hw field: the description of the recording hardware.

Clears the retained original bytes.

Source

pub fn set_license(&mut self, license: String)

Sets the global core:license field: the URL of the license governing the recording.

Clears the retained original bytes.

Source

pub fn set_metadata_only(&mut self, metadata_only: bool)

Sets the global core:metadata_only field: whether the recording intentionally has no dataset file.

Clears the retained original bytes.

Source

pub fn set_meta_doi(&mut self, meta_doi: String)

Sets the global core:meta_doi field: the DOI of the metadata file.

Clears the retained original bytes.

Source

pub fn set_num_channels(&mut self, num_channels: Integer)

Sets the global core:num_channels field: the number of interleaved channels in the dataset.

Clears the retained original bytes.

Source

pub fn set_offset(&mut self, offset: Integer)

Sets the global core:offset field: the index offset of the first sample in the dataset.

Clears the retained original bytes.

Source

pub fn set_recorder(&mut self, recorder: String)

Sets the global core:recorder field: the name of the software that made the recording.

Clears the retained original bytes.

Source

pub fn set_sha512(&mut self, hash: String)

Sets the global core:sha512 field: the SHA-512 digest of the dataset file.

Clears the retained original bytes.

Source

pub fn set_geolocation(&mut self, geolocation: GeoJson)

Sets the global core:geolocation field: the GeoJSON location of the recording.

Clears the retained original bytes.

Source

pub fn set_extensions(&mut self, extensions: Vec<ExtensionDeclaration>)

Sets the global core:extensions field: the list of extension namespaces used by the recording.

Clears the retained original bytes.

Source

pub fn set_dataset(&mut self, dataset: String)

Sets the global core:dataset field: the file name of a non-conforming dataset.

Clears the retained original bytes.

Source

pub fn set_trailing_bytes(&mut self, trailing_bytes: Integer)

Sets the global core:trailing_bytes field: the number of non-sample bytes at the end of the dataset file.

Clears the retained original bytes.

Source

pub fn add_annotation(&mut self, annotation: Annotation)

Appends an entry to the annotations array.

No ordering is enforced. Clears the retained original bytes.

Source

pub fn add_capture(&mut self, capture: Capture)

Appends an entry to the captures array.

No ordering is enforced. Clears the retained original bytes.

Source

pub fn get_version(&self) -> String

Returns the global core:version field: the SigMF specification version string.

Source

pub fn get_datatype(&self) -> Datatype

Returns the global core:datatype field: the sample format of the dataset.

Source

pub fn get_sample_rate(&self) -> Option<Number>

Returns the global core:sample_rate field: the sample rate in samples per second, if set.

Source

pub fn get_author(&self) -> Option<String>

Returns the global core:author field: the author of the recording, if set.

Source

pub fn get_collection(&self) -> Option<String>

Returns the global core:collection field: the base name of the SigMF collection this recording belongs to, if set.

Source

pub fn get_data_doi(&self) -> Option<String>

Returns the global core:data_doi field: the DOI of the dataset file, if set.

Source

pub fn get_description(&self) -> Option<String>

Returns the global core:description field: the free-text description of the recording, if set.

Source

pub fn get_hw(&self) -> Option<String>

Returns the global core:hw field: the description of the recording hardware, if set.

Source

pub fn get_license(&self) -> Option<String>

Returns the global core:license field: the URL of the license governing the recording, if set.

Source

pub fn get_metadata_only(&self) -> Option<bool>

Returns the global core:metadata_only field: whether the recording intentionally has no dataset file, if set.

Source

pub fn get_meta_doi(&self) -> Option<String>

Returns the global core:meta_doi field: the DOI of the metadata file, if set.

Source

pub fn get_num_channels(&self) -> Option<Integer>

Returns the global core:num_channels field: the number of interleaved channels in the dataset, if set.

Source

pub fn get_offset(&self) -> Option<Integer>

Returns the global core:offset field: the index offset of the first sample in the dataset, if set.

Source

pub fn get_recorder(&self) -> Option<String>

Returns the global core:recorder field: the name of the software that made the recording, if set.

Source

pub fn get_sha512(&self) -> Option<String>

Returns the global core:sha512 field: the SHA-512 digest of the dataset file, if set.

Source

pub fn get_geolocation(&self) -> Option<GeoJson>

Returns the global core:geolocation field: the GeoJSON location of the recording, if set.

Source

pub fn get_extensions(&self) -> Option<Vec<ExtensionDeclaration>>

Returns the global core:extensions field: the list of extension namespaces used by the recording, if set.

Source

pub fn get_dataset(&self) -> Option<String>

Returns the global core:dataset field: the file name of a non-conforming dataset, if set.

Source

pub fn get_trailing_bytes(&self) -> Option<Integer>

Returns the global core:trailing_bytes field: the number of non-sample bytes at the end of the dataset file, if set.

Source

pub fn get_annotations(&self) -> Vec<Annotation>

Returns a clone of the annotations array.

Prefer Metadata::annotations to borrow without cloning.

Source

pub fn get_captures(&self) -> Vec<Capture>

Returns a clone of the captures array.

Prefer Metadata::captures to borrow without cloning.

Source§

impl Metadata

Source

pub fn validate(&self, policy: ValidationPolicy) -> ValidationReport

Validates this metadata against SigMF rules using policy.

Extensions declared in core:extensions are reported as unverified because no ExtensionRegistry is supplied; use validate_with_registry to verify them. See the module documentation for the full list of checks.

§Example
use sigmf::datatype::Datatype;
use sigmf::global::Global;
use sigmf::meta::Metadata;
use sigmf::validation::{Severity, ValidationPolicy, ValidationStatus};
use std::str::FromStr;

// An older version is tolerated under the interoperability policy...
let metadata = Metadata::new(
    Global::new("1.0.0", Datatype::from_str("ri16_le")?),
    Vec::new(),
    Vec::new(),
);
let report = metadata.validate(ValidationPolicy::Interoperability);
assert_eq!(report.status, ValidationStatus::NotChecked);
assert_eq!(report.issues[0].severity, Severity::Warning);

// ...but rejected under the strict policy.
let report = metadata.validate(ValidationPolicy::StrictSupportedVersion);
assert_eq!(report.status, ValidationStatus::Failed);
assert!(!report.is_valid());
Source

pub fn validate_with_registry( &self, policy: ValidationPolicy, registry: &ExtensionRegistry, ) -> ValidationReport

Validates this metadata, using registry to verify declared extensions.

In addition to the checks performed by validate, extensions declared in core:extensions whose name and version are registered are treated as verified, and their fields in the global, capture, and annotation objects are checked for the correct ExtensionScope (an error) and for being declared by the extension (a warning).

Trait Implementations§

Source§

impl Clone for Metadata

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Metadata

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de> Deserialize<'de> for Metadata

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Serialize for Metadata

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more