DMSCFrameHeader

Struct DMSCFrameHeader 

Source
pub struct DMSCFrameHeader {
    pub magic: u32,
    pub frame_type: u8,
    pub version: u8,
    pub flags: u16,
    pub payload_length: u32,
    pub sequence_number: u32,
    pub timestamp: u64,
    pub checksum: u32,
}
Expand description

Protocol frame header structure containing metadata for frame processing.

The frame header provides essential protocol metadata required for proper frame handling, transmission, and verification. It follows a fixed 32-byte format designed for efficient parsing and minimal overhead while maintaining comprehensive protocol information. All fields use big-endian byte ordering for consistent network transmission.

§Header Field Layout

OffsetSizeFieldDescription
04magicProtocol magic number (0x444D5350)
41frame_typeFrame type identifier (0x01-0x06)
51versionProtocol version (0x01)
62flagsProtocol flags for special handling
84payload_lengthLength of frame payload in bytes
124sequence_numberFrame sequence number for ordering
168timestampUnix timestamp of frame creation
244checksumCRC32 checksum for integrity verification

§Byte Ordering

All multi-byte fields use big-endian (network byte order) encoding to ensure consistent interpretation across different architectures and platforms. When serializing or deserializing, use the provided to_bytes() and from_bytes() methods to ensure proper byte ordering.

§Magic Number Validation

The magic number 0x444D5350 decodes to ASCII “DMSP” (DMSC Protocol) and serves as a quick validation that incoming data represents a valid DMSC frame. Receiving a frame with an invalid magic number indicates either protocol mismatch or data corruption.

§Python Bindings

When compiled with the pyo3 feature, this struct provides Python bindings:

from dmsc import DMSCFrameHeader

# Create new header for a data frame
header = DMSCFrameHeader.new(
    frame_type=DMSCFrameHeader.FrameType.Data,
    payload_length=1024,
    sequence_number=42
)

# Serialize to bytes for transmission
header_bytes = header.to_bytes()

# Access header fields
print(f"Frame type: {header.frame_type}")
print(f"Payload length: {header.payload_length}")
print(f"Sequence: {header.sequence_number}")
print(f"Timestamp: {header.timestamp}")

§Examples

Creating a new frame header:

use dmsc::protocol::frames::{DMSCFrameHeader, DMSCFrameType};

let header = DMSCFrameHeader::new(
    DMSCFrameType::Data,
    1024,           // payload length
    42              // sequence number
).expect("Failed to create frame header");

assert_eq!(header.magic, DMSCFrameHeader::MAGIC);
assert_eq!(header.version, DMSCFrameHeader::VERSION);
assert_eq!(header.frame_type, DMSCFrameType::Data as u8);

Serializing and deserializing headers:

use dmsc::protocol::frames::{DMSCFrameHeader, DMSCFrameType};

let header = DMSCFrameHeader::new(
    DMSCFrameType::Control,
    256,
    100
).expect("Failed to create header");

let bytes = header.to_bytes();
assert_eq!(bytes.len(), 32);

let reconstructed = DMSCFrameHeader::from_bytes(&bytes)
    .expect("Failed to parse header");

assert_eq!(header.magic, reconstructed.magic);
assert_eq!(header.frame_type, reconstructed.frame_type);
assert_eq!(header.sequence_number, reconstructed.sequence_number);

Verifying frame integrity:

use dmsc::protocol::frames::{DMSCFrameHeader, DMSCFrameType};

let header = DMSCFrameHeader::new(
    DMSCFrameType::Data,
    512,
    200
).expect("Failed to create header");

let payload = b"This is the frame payload data";

let is_valid = header.verify_checksum(payload);
assert!(is_valid);

// Modify payload and verify again
let modified_payload = b"This payload has been modified!";
let is_valid_modified = header.verify_checksum(modified_payload);
assert!(!is_valid_modified);

Fields§

§magic: u32

Frame magic number identifying the DMSC protocol (4 bytes).

The magic number is a 32-bit constant that uniquely identifies DMSC protocol frames. It serves as a quick validation mechanism to detect non-DMSC data or protocol version mismatches. The value 0x444D5350 corresponds to the ASCII encoding of “DMSP” (DMSC Protocol).

§Magic Number Details

  • Value: 0x444D5350
  • ASCII: “DMSP”
  • Purpose: Protocol identification
  • Validation: Must match exactly on all received frames

§Usage

The magic number is the first field in the frame header and should be validated immediately upon receiving frame data. A mismatch indicates either incorrect data or a protocol version incompatibility.

§frame_type: u8

Frame type identifier determining frame processing (1 byte).

The frame type specifies how the frame payload should be interpreted and processed. This 8-bit field identifies one of six possible frame types defined in the DMSCFrameType enumeration.

§version: u8

Protocol version for compatibility checking (1 byte).

The version field enables protocol evolution while maintaining backward compatibility. The current version is 0x01. Protocol implementations should reject frames with unsupported versions.

§flags: u16

Protocol flags for special frame handling (2 bytes).

Flags provide additional processing instructions for frames. Common flags include compression, priority, and streaming indicators.

§Flag Definitions

  • Bit 0: Compressed - Payload is compressed
  • Bit 1: Priority - High priority frame
  • Bit 2: Streaming - Part of streaming transfer
  • Bit 3: Fragmented - Part of fragmented message
  • Bits 4-15: Reserved for future use
§payload_length: u32

Length of the frame payload in bytes (4 bytes).

This field specifies the exact number of bytes in the frame payload. It enables proper memory allocation and bounds checking during frame processing. The maximum payload length is 4GB.

§sequence_number: u32

Frame sequence number for ordering and reliability (4 bytes).

Sequence numbers enable in-order delivery, duplicate detection, and loss detection for protocol frames. Each frame in a connection uses a monotonically increasing sequence number with wraparound at 2^32.

§Sequence Number Semantics

  • Initialization: Sequence numbers start at 0 for new connections
  • Increment: Each frame increments the sequence number by 1
  • Wraparound: Sequence numbers wrap from 0xFFFFFFFF to 0
  • Ordering: Receivers use sequence numbers to order frames
§timestamp: u64

Unix timestamp of frame creation in seconds (8 bytes).

The timestamp records when the frame was created, enabling temporal validation, replay detection, and latency measurements. Timestamps use seconds since Unix epoch (1970-01-01 00:00:00 UTC).

§Timestamp Considerations

  • Precision: Second-level precision (not milliseconds)
  • Clock Sync: Requires loosely synchronized clocks
  • Replay Protection: Used in conjunction with nonces
  • Age Limits: Frames older than timeout are rejected
§checksum: u32

CRC32 checksum for frame integrity verification (4 bytes).

The checksum covers all header fields (except checksum itself) and the complete frame payload. It enables detection of transmission errors and data corruption. Uses the CRC32 algorithm with polynomial 0x04C11DB7 (IEEE 802.3).

§Checksum Calculation

The checksum is computed over the concatenation of all header fields (excluding the checksum field) followed by the frame payload. This provides comprehensive protection against single-bit errors and many burst errors.

§Limitations

CRC32 provides error detection but not error correction. It can detect all single-bit errors, most double-bit errors, and many burst errors up to 32 bits in length. It does not provide cryptographic integrity.

Implementations§

Source§

impl DMSCFrameHeader

Source

pub const MAGIC: u32 = 0x444D5350

Frame magic number constant for protocol identification.

This 32-bit constant uniquely identifies DMSC protocol frames. The value 0x444D5350 corresponds to the ASCII encoding of “DMSP” (DMSC Protocol). This magic number is placed at the beginning of every frame header and is validated upon frame receipt to confirm protocol compatibility.

§Magic Number Details
  • Hex Value: 0x444D5350
  • ASCII Representation: “DMSP”
  • Purpose: Quick protocol identification
  • Validation: Must match on all received frames
§Usage in Frame Processing

When receiving frame data, the magic number should be validated first before attempting to parse other header fields. A mismatch indicates:

  1. The received data is not a DMSC frame
  2. Data corruption may have occurred
  3. The remote endpoint may be using a different protocol
Source

pub const VERSION: u8 = 0x01

Current protocol version identifier.

This version number enables protocol evolution while maintaining backward compatibility. The current version is 0x01. Future protocol enhancements may increment this version while maintaining support for earlier versions.

§Version Semantics
  • Major Version Changes: May introduce incompatible changes
  • Minor Version Changes: Backward-compatible enhancements
  • Current Value: 0x01 (initial protocol version)
§Version Negotiation

During connection establishment, endpoints should negotiate a compatible protocol version. Frames with unsupported versions should be rejected with an appropriate error response.

Source

pub fn new( frame_type: DMSCFrameType, payload_length: u32, sequence_number: u32, ) -> DMSCResult<Self>

Create a new frame header

Source

pub fn calculate_checksum(&self, payload: &[u8]) -> u32

Calculate CRC32 checksum for the header and payload

Source

pub fn verify_checksum(&self, payload: &[u8]) -> bool

Verify the checksum

Source

pub fn to_bytes(&self) -> Vec<u8>

Serialize header to bytes

Source

pub fn from_bytes(bytes: &[u8]) -> DMSCResult<Self>

Deserialize header from bytes

Trait Implementations§

Source§

impl Clone for DMSCFrameHeader

Source§

fn clone(&self) -> DMSCFrameHeader

Returns a duplicate of the value. Read more
1.0.0 · Source§

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

Performs copy-assignment from source. Read more
Source§

impl Debug for DMSCFrameHeader

Source§

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

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

impl<'de> Deserialize<'de> for DMSCFrameHeader

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<'py> IntoPyObject<'py> for DMSCFrameHeader

Source§

type Target = DMSCFrameHeader

The Python output type
Source§

type Output = Bound<'py, <DMSCFrameHeader as IntoPyObject<'py>>::Target>

The smart pointer type to use. Read more
Source§

type Error = PyErr

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

fn into_pyobject( self, py: Python<'py>, ) -> Result<<Self as IntoPyObject<'_>>::Output, <Self as IntoPyObject<'_>>::Error>

Performs the conversion.
Source§

impl PyClass for DMSCFrameHeader

Source§

type Frozen = False

Whether the pyclass is frozen. Read more
Source§

impl PyClassImpl for DMSCFrameHeader

Source§

const IS_BASETYPE: bool = false

#[pyclass(subclass)]
Source§

const IS_SUBCLASS: bool = false

#[pyclass(extends=…)]
Source§

const IS_MAPPING: bool = false

#[pyclass(mapping)]
Source§

const IS_SEQUENCE: bool = false

#[pyclass(sequence)]
Source§

const IS_IMMUTABLE_TYPE: bool = false

#[pyclass(immutable_type)]
Source§

const RAW_DOC: &'static CStr = c"Protocol frame header structure containing metadata for frame processing.\n\nThe frame header provides essential protocol metadata required for proper\nframe handling, transmission, and verification. It follows a fixed 32-byte\nformat designed for efficient parsing and minimal overhead while maintaining\ncomprehensive protocol information. All fields use big-endian byte ordering\nfor consistent network transmission.\n\n## Header Field Layout\n\n| Offset | Size | Field | Description |\n|--------|------|----------------|------------------------------------------|\n| 0 | 4 | magic | Protocol magic number (0x444D5350) |\n| 4 | 1 | frame_type | Frame type identifier (0x01-0x06) |\n| 5 | 1 | version | Protocol version (0x01) |\n| 6 | 2 | flags | Protocol flags for special handling |\n| 8 | 4 | payload_length | Length of frame payload in bytes |\n| 12 | 4 | sequence_number| Frame sequence number for ordering |\n| 16 | 8 | timestamp | Unix timestamp of frame creation |\n| 24 | 4 | checksum | CRC32 checksum for integrity verification|\n\n## Byte Ordering\n\nAll multi-byte fields use big-endian (network byte order) encoding to ensure\nconsistent interpretation across different architectures and platforms.\nWhen serializing or deserializing, use the provided `to_bytes()` and\n`from_bytes()` methods to ensure proper byte ordering.\n\n## Magic Number Validation\n\nThe magic number `0x444D5350` decodes to ASCII \"DMSP\" (DMSC Protocol) and\nserves as a quick validation that incoming data represents a valid DMSC\nframe. Receiving a frame with an invalid magic number indicates either\nprotocol mismatch or data corruption.\n\n## Python Bindings\n\nWhen compiled with the `pyo3` feature, this struct provides Python bindings:\n```python\nfrom dmsc import DMSCFrameHeader\n\n# Create new header for a data frame\nheader = DMSCFrameHeader.new(\n frame_type=DMSCFrameHeader.FrameType.Data,\n payload_length=1024,\n sequence_number=42\n)\n\n# Serialize to bytes for transmission\nheader_bytes = header.to_bytes()\n\n# Access header fields\nprint(f\"Frame type: {header.frame_type}\")\nprint(f\"Payload length: {header.payload_length}\")\nprint(f\"Sequence: {header.sequence_number}\")\nprint(f\"Timestamp: {header.timestamp}\")\n```\n\n# Examples\n\nCreating a new frame header:\n```rust,ignore\nuse dmsc::protocol::frames::{DMSCFrameHeader, DMSCFrameType};\n\nlet header = DMSCFrameHeader::new(\n DMSCFrameType::Data,\n 1024, // payload length\n 42 // sequence number\n).expect(\"Failed to create frame header\");\n\nassert_eq!(header.magic, DMSCFrameHeader::MAGIC);\nassert_eq!(header.version, DMSCFrameHeader::VERSION);\nassert_eq!(header.frame_type, DMSCFrameType::Data as u8);\n```\n\nSerializing and deserializing headers:\n```rust,ignore\nuse dmsc::protocol::frames::{DMSCFrameHeader, DMSCFrameType};\n\nlet header = DMSCFrameHeader::new(\n DMSCFrameType::Control,\n 256,\n 100\n).expect(\"Failed to create header\");\n\nlet bytes = header.to_bytes();\nassert_eq!(bytes.len(), 32);\n\nlet reconstructed = DMSCFrameHeader::from_bytes(&bytes)\n .expect(\"Failed to parse header\");\n\nassert_eq!(header.magic, reconstructed.magic);\nassert_eq!(header.frame_type, reconstructed.frame_type);\nassert_eq!(header.sequence_number, reconstructed.sequence_number);\n```\n\nVerifying frame integrity:\n```rust,ignore\nuse dmsc::protocol::frames::{DMSCFrameHeader, DMSCFrameType};\n\nlet header = DMSCFrameHeader::new(\n DMSCFrameType::Data,\n 512,\n 200\n).expect(\"Failed to create header\");\n\nlet payload = b\"This is the frame payload data\";\n\nlet is_valid = header.verify_checksum(payload);\nassert!(is_valid);\n\n// Modify payload and verify again\nlet modified_payload = b\"This payload has been modified!\";\nlet is_valid_modified = header.verify_checksum(modified_payload);\nassert!(!is_valid_modified);\n```\x00"

Docstring for the class provided on the struct or enum. Read more
Source§

const DOC: &'static CStr

Fully rendered class doc, including the text_signature if a constructor is defined. Read more
Source§

type BaseType = PyAny

Base class
Source§

type ThreadChecker = SendablePyClass<DMSCFrameHeader>

This handles following two situations: Read more
Source§

type PyClassMutability = <<PyAny as PyClassBaseType>::PyClassMutability as PyClassMutability>::MutableChild

Immutable or mutable
Source§

type Dict = PyClassDummySlot

Specify this class has #[pyclass(dict)] or not.
Source§

type WeakRef = PyClassDummySlot

Specify this class has #[pyclass(weakref)] or not.
Source§

type BaseNativeType = PyAny

The closest native ancestor. This is PyAny by default, and when you declare #[pyclass(extends=PyDict)], it’s PyDict.
Source§

fn items_iter() -> PyClassItemsIter

Source§

fn lazy_type_object() -> &'static LazyTypeObject<Self>

§

fn dict_offset() -> Option<isize>

§

fn weaklist_offset() -> Option<isize>

Source§

impl PyTypeInfo for DMSCFrameHeader

Source§

const NAME: &'static str = "DMSCFrameHeader"

Class name.
Source§

const MODULE: Option<&'static str> = ::core::option::Option::None

Module name, if any.
Source§

fn type_object_raw(py: Python<'_>) -> *mut PyTypeObject

Returns the PyTypeObject instance for this type.
§

fn type_object(py: Python<'_>) -> Bound<'_, PyType>

Returns the safe abstraction over the type object.
§

fn is_type_of(object: &Bound<'_, PyAny>) -> bool

Checks if object is an instance of this type or a subclass of this type.
§

fn is_exact_type_of(object: &Bound<'_, PyAny>) -> bool

Checks if object is an instance of this type.
Source§

impl Serialize for DMSCFrameHeader

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
Source§

impl DerefToPyAny for DMSCFrameHeader

Source§

impl ExtractPyClassWithClone for DMSCFrameHeader

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
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

§

fn implicit( self, class: Class, constructed: bool, tag: u32, ) -> TaggedParser<'a, Implicit, Self, E>

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<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> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<'a, 'py, T> FromPyObject<'a, 'py> for T
where T: PyClass + Clone + ExtractPyClassWithClone,

§

type Error = PyClassGuardError<'a, 'py>

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

fn extract( obj: Borrowed<'a, 'py, PyAny>, ) -> Result<T, <T as FromPyObject<'a, 'py>>::Error>

Extracts Self from the bound smart pointer obj. Read more
§

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

§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
§

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

§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
§

impl<T> Instrument for T

§

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

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

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
§

impl<'py, T> IntoPyObjectExt<'py> for T
where T: IntoPyObject<'py>,

§

fn into_bound_py_any(self, py: Python<'py>) -> Result<Bound<'py, PyAny>, PyErr>

Converts self into an owned Python object, dropping type information.
§

fn into_py_any(self, py: Python<'py>) -> Result<Py<PyAny>, PyErr>

Converts self into an owned Python object, dropping type information and unbinding it from the 'py lifetime.
§

fn into_pyobject_or_pyerr(self, py: Python<'py>) -> Result<Self::Output, PyErr>

Converts self into a Python object. Read more
Source§

impl<T> IntoRequest<T> for T

Source§

fn into_request(self) -> Request<T>

Wrap the input message T in a tonic::Request
Source§

impl<T> IntoRequest<T> for T

Source§

fn into_request(self) -> Request<T>

Wrap the input message T in a tonic::Request
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

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

Initializes a with the given initializer. Read more
§

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

Dereferences the given pointer. Read more
§

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

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

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

impl<T> PyErrArguments for T
where T: for<'py> IntoPyObject<'py> + Send + Sync,

§

fn arguments(self, py: Python<'_>) -> Py<PyAny>

Arguments for exception
§

impl<T> PyTypeCheck for T
where T: PyTypeInfo,

§

const NAME: &'static str = T::NAME

👎Deprecated since 0.27.0: Use ::classinfo_object() instead and format the type name at runtime. Note that using built-in cast features is often better than manual PyTypeCheck usage.
Name of self. This is used in error messages, for example.
§

fn type_check(object: &Bound<'_, PyAny>) -> bool

Checks if object is an instance of Self, which may include a subtype. Read more
§

fn classinfo_object(py: Python<'_>) -> Bound<'_, PyAny>

Returns the expected type as a possible argument for the isinstance and issubclass function. Read more
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 = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

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
§

fn with_current_subscriber(self) -> WithDispatch<Self>

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

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

§

impl<'py, T> FromPyObjectOwned<'py> for T
where T: for<'a> FromPyObject<'a, 'py>,

§

impl<T> Ungil for T
where T: Send,