Skip to content

Commit

Permalink
Add padding bytes to the end of DATA submessage to align to 4 bytes.
Browse files Browse the repository at this point in the history
  • Loading branch information
jhelovuo committed Aug 1, 2024
1 parent 11bdd19 commit 077e8e5
Show file tree
Hide file tree
Showing 6 changed files with 32 additions and 34 deletions.
31 changes: 11 additions & 20 deletions examples/hello_world_publisher/main.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,14 @@
//! Re-implementation of helloworld / publisher example in CycloneDDS
//!
use std::time::{Duration};
use log::error;
use std::time::Duration;

use log::error;
use rustdds::{
DomainParticipantBuilder, Keyed, QosPolicyBuilder,
policy::Reliability, DataWriterStatus, DomainParticipantBuilder, Keyed, QosPolicyBuilder,
StatusEvented, TopicKind,
DataWriterStatus,
};
use rustdds::policy::Reliability;

use serde::{Deserialize, Serialize};

use smol::Timer;
use futures::{FutureExt, TryFutureExt, StreamExt};
use futures::{FutureExt, StreamExt, TryFutureExt};

#[derive(Serialize, Deserialize, Clone, Debug)]
struct HelloWorldData {
Expand All @@ -28,26 +23,23 @@ impl Keyed for HelloWorldData {
}
}


fn main() {
let domain_participant = DomainParticipantBuilder::new(0)
.build()
.unwrap_or_else(|e| panic!("DomainParticipant construction failed: {e:?}"));

let qos = QosPolicyBuilder::new()
.reliability(
Reliability::Reliable {
max_blocking_time: rustdds::Duration::from_secs(1),
})
.reliability(Reliability::Reliable {
max_blocking_time: rustdds::Duration::from_secs(1),
})
.build();


let topic = domain_participant
.create_topic(
// We can internally call the Rust type "HelloWorldData" whatever we want,
// but these strings must match whatever our counterparts expect
// to see over RTPS.
"HelloWorldData_Msg".to_string(), // topic name
"HelloWorldData_Msg".to_string(), // topic name
"HelloWorldData::Msg".to_string(), // type name
&qos,
TopicKind::WithKey,
Expand All @@ -60,8 +52,8 @@ fn main() {
.unwrap();

let hello_message = HelloWorldData {
user_id: 123,
message: "Hello, World!11".to_string(),
user_id: 42,
message: "Hello, Rust!".to_string(),
};

// set up async executor to run concurrent tasks
Expand Down Expand Up @@ -95,7 +87,7 @@ fn main() {
println!("Matched with hello subscriber");
write_trigger_sender.send(()).await.unwrap();
}
_ =>
_ =>
println!("DataWriter event: {e:?}"),
}
}
Expand All @@ -105,4 +97,3 @@ fn main() {
println!("Bye, World!");
});
}

23 changes: 16 additions & 7 deletions src/messages/submessages/data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use enumflags2::BitFlags;

use crate::{
messages::submessages::{elements::parameter_list::ParameterList, submessages::*},
serialization::{padding_needed_for_alignment_4, round_up_to_4},
structure::{guid::EntityId, sequence_number::SequenceNumber},
};
// use log::debug;
Expand Down Expand Up @@ -125,6 +126,9 @@ impl Data {
None
};

// Serialized data is the rest of the submessage. It may contain some
// alignment padding, but at least a CDR decoder should be able to cope with
// that.
let serialized_payload = if expect_data {
Some(buffer.clone().split_off(cursor.position() as usize))
} else {
Expand All @@ -145,13 +149,15 @@ impl Data {
// "octetsToNextHeader" field in RTPS spec v2.5 Section "9.4.5.1 Submessage
// Header".
pub fn len_serialized(&self) -> usize {
2 + // extraFlags
2 + // octetsToInlineSos
4 + // readerId
4 + // writerId
8 + // writerSN
self.inline_qos.as_ref().map(|q| q.len_serialized() ).unwrap_or(0) + // QoS ParameterList
self.serialized_payload.as_ref().map(|q| q.len()).unwrap_or(0)
round_up_to_4(
2 + // extraFlags
2 + // octetsToInlineSos
4 + // readerId
4 + // writerId
8 + // writerSN
self.inline_qos.as_ref().map(|q| q.len_serialized() ).unwrap_or(0) + // QoS ParameterList
self.serialized_payload.as_ref().map(|q| q.len()).unwrap_or(0),
)
}

#[cfg(test)]
Expand Down Expand Up @@ -198,6 +204,9 @@ impl<C: Context> Writable<C> for Data {

if let Some(serialized_payload) = self.serialized_payload.as_ref() {
writer.write_bytes(serialized_payload)?;
for _ in 0..padding_needed_for_alignment_4(serialized_payload.len()) {
writer.write_u8(0)?;
}
}

Ok(())
Expand Down
5 changes: 2 additions & 3 deletions src/messages/submessages/elements/parameter.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use speedy::{Context, Readable, Reader, Writable, Writer};
use bit_vec::BitVec;

use crate::structure::parameter_id::ParameterId;
use crate::serialization::round_up_to_4;
use crate::{serialization::round_up_to_4, structure::parameter_id::ParameterId};

#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Parameter {
Expand Down Expand Up @@ -69,7 +68,7 @@ impl Parameter {
round_up_to_4(
2 + // parameter_id
2 + // length field
self.value.len() // payload
self.value.len(), // payload
)
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/network/udp_listener.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ use crate::{
network::util::{
get_local_multicast_ip_addrs, get_local_multicast_locators, get_local_unicast_locators,
},
structure::locator::Locator,
serialization::padding_needed_for_alignment_4,
structure::locator::Locator,
};

const MAX_MESSAGE_SIZE: usize = 64 * 1024; // This is max we can get from UDP.
Expand Down
2 changes: 1 addition & 1 deletion src/security/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,11 @@ use crate::{
security,
security::config::ConfigError,
serialization::{
padding_needed_for_alignment_4,
pl_cdr_adapters::{
PlCdrDeserialize, PlCdrDeserializeError, PlCdrSerialize, PlCdrSerializeError,
},
speedy_pl_cdr_helpers::*,
padding_needed_for_alignment_4,
},
structure::{guid::GuidPrefix, parameter_id::ParameterId},
Keyed, QosPolicies, RepresentationIdentifier, GUID,
Expand Down
3 changes: 1 addition & 2 deletions src/serialization.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ pub use cdr_adapters::{
};
pub use representation_identifier::RepresentationIdentifier;


// Compute how much padding bytes are needed to
// get the next multiple of 4
pub fn padding_needed_for_alignment_4(unaligned_length: usize) -> usize {
Expand All @@ -29,4 +28,4 @@ pub fn padding_needed_for_alignment_4(unaligned_length: usize) -> usize {

pub fn round_up_to_4(unaligned_length: usize) -> usize {
unaligned_length + padding_needed_for_alignment_4(unaligned_length)
}
}

0 comments on commit 077e8e5

Please sign in to comment.