iceoryx2 0.9.0

iceoryx2: Lock-Free Zero-Copy Interprocess Communication
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
// Copyright (c) 2023 - 2024 Contributors to the Eclipse Foundation
//
// See the NOTICE file(s) distributed with this work for additional
// information regarding copyright ownership.
//
// This program and the accompanying materials are made available under the
// terms of the Apache Software License 2.0 which is available at
// https://www.apache.org/licenses/LICENSE-2.0, or the MIT license
// which is available at https://opensource.org/licenses/MIT.
//
// SPDX-License-Identifier: Apache-2.0 OR MIT

//! # Examples
//!
//! ## Typed API
//!
//! ```
//! use iceoryx2::prelude::*;
//!
//! # fn main() -> Result<(), Box<dyn core::error::Error>> {
//! let node = NodeBuilder::new().create::<ipc::Service>()?;
//! let service = node.service_builder(&"My/Funk/ServiceName".try_into()?)
//!     .publish_subscribe::<u64>()
//!     .open_or_create()?;
//!
//! let publisher = service
//!     .publisher_builder()
//!     // defines how many samples can be loaned in parallel
//!     .max_loaned_samples(5)
//!     // defines behavior when subscriber queue is full in an non-overflowing service
//!     .backpressure_strategy(BackpressureStrategy::DiscardData)
//!     .create()?;
//!
//! // loan some initialized memory and send it
//! // the payload type must implement the [`core::default::Default`] trait in order to be able to use this API
//! let mut sample = publisher.loan()?;
//! *sample.payload_mut() = 1337;
//! sample.send()?;
//!
//! // loan some uninitialized memory and send it
//! let sample = publisher.loan_uninit()?;
//! let sample = sample.write_payload(1337);
//! sample.send()?;
//!
//! // loan some uninitialized memory and send it (with direct access of [`core::mem::MaybeUninit<Payload>`])
//! let mut sample = publisher.loan_uninit()?;
//! sample.payload_mut().write(1337);
//! let sample = unsafe { sample.assume_init() };
//! sample.send()?;
//!
//! // send a copy of the value
//! publisher.send_copy(313)?;
//!
//! # Ok(())
//! # }
//! ```
//!
//! ## Slice API
//!
//! ```
//! use iceoryx2::prelude::*;
//!
//! # fn main() -> Result<(), Box<dyn core::error::Error>> {
//! let node = NodeBuilder::new().create::<ipc::Service>()?;
//! let service = node.service_builder(&"My/Funk/ServiceName".try_into()?)
//!     .publish_subscribe::<[usize]>()
//!     .open_or_create()?;
//!
//! let publisher = service
//!     .publisher_builder()
//!     // defines the maximum length of a slice
//!     .initial_max_slice_len(128)
//!     // defines how many samples can be loaned in parallel
//!     .max_loaned_samples(5)
//!     // defines behavior when subscriber queue is full in an non-overflowing service
//!     .backpressure_strategy(BackpressureStrategy::DiscardData)
//!     .create()?;
//!
//! // loan some initialized memory and send it
//! // the payload type must implement the [`core::default::Default`] trait in order to be able to use this API
//! // we acquire a slice of length 12
//! let mut sample = publisher.loan_slice(12)?;
//! sample.payload_mut()[5] = 1337;
//! sample.send()?;
//!
//! // loan uninitialized slice of length 60 and send it
//! let sample = publisher.loan_slice_uninit(60)?;
//! // initialize the n element of the slice with the value n * 123
//! let sample = sample.write_from_fn(|n| n * 123 );
//! sample.send()?;
//!
//! // loan some uninitialized memory and send it (with direct access of [`core::mem::MaybeUninit<Payload>`])
//! let mut sample = publisher.loan_slice_uninit(42)?;
//! for element in sample.payload_mut() {
//!     element.write(1337);
//! }
//! let sample = unsafe { sample.assume_init() };
//! sample.send()?;
//!
//! # Ok(())
//! # }
//! ```

use core::any::TypeId;
use core::fmt::Debug;
use core::ptr::NonNull;
use core::{marker::PhantomData, mem::MaybeUninit};

use alloc::vec::Vec;

use iceoryx2_bb_concurrency::atomic::Ordering;
use iceoryx2_bb_concurrency::atomic::{AtomicBool, AtomicUsize};
use iceoryx2_bb_concurrency::cell::UnsafeCell;
use iceoryx2_bb_container::queue::Queue;
use iceoryx2_bb_elementary::CallbackProgression;
use iceoryx2_bb_elementary::cyclic_tagger::CyclicTagger;
use iceoryx2_bb_elementary_traits::non_null::NonNullCompat;
use iceoryx2_bb_elementary_traits::testing::abandonable::Abandonable;
use iceoryx2_bb_elementary_traits::zero_copy_send::ZeroCopySend;
use iceoryx2_bb_lock_free::mpmc::container::{ContainerHandle, ContainerState};
use iceoryx2_bb_posix::unique_system_id::UniqueSystemId;
use iceoryx2_cal::arc_sync_policy::ArcSyncPolicy;
use iceoryx2_cal::dynamic_storage::DynamicStorage;
use iceoryx2_cal::shm_allocator::{AllocationStrategy, PointerOffset};
use iceoryx2_cal::zero_copy_connection::{
    CHANNEL_STATE_OPEN, ChannelId, ZeroCopyCreationError, ZeroCopyPortDetails, ZeroCopySender,
};
use iceoryx2_log::{fail, warn};

use crate::port::details::sender::*;
use crate::port::update_connections::{ConnectionFailure, UpdateConnections};
use crate::prelude::BackpressureStrategy;
use crate::raw_sample::RawSampleMut;
use crate::sample_mut::SampleMut;
use crate::sample_mut_uninit::SampleMutUninit;
use crate::service::builder::{CustomHeaderMarker, CustomPayloadMarker};
use crate::service::dynamic_config::publish_subscribe::{PublisherDetails, SubscriberDetails};
use crate::service::header::publish_subscribe::Header;
use crate::service::naming_scheme::data_segment_name;
use crate::service::port_factory::publisher::{LocalPublisherConfig, PortFactoryPublisher};
use crate::service::static_config::message_type_details::TypeVariant;
use crate::service::{self};

use super::details::data_segment::{DataSegment, DataSegmentType};
use super::details::segment_state::SegmentState;
use super::{LoanError, SendError};
use crate::identifiers::UniquePublisherId;

/// Defines a failure that can occur when a [`Publisher`] is created with
/// [`crate::service::port_factory::publisher::PortFactoryPublisher`].
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub enum PublisherCreateError {
    /// The maximum amount of [`Publisher`]s that can connect to a
    /// [`Service`](crate::service::Service) is
    /// defined in [`crate::config::Config`]. When this is exceeded no more [`Publisher`]s
    /// can be created for a specific [`Service`](crate::service::Service).
    ExceedsMaxSupportedPublishers,
    /// The datasegment in which the payload of the [`Publisher`] is stored, could not be created.
    UnableToCreateDataSegment,
    /// Caused by a failure when instantiating a [`ArcSyncPolicy`] defined in the
    /// [`Service`](crate::service::Service) as `ArcThreadSafetyPolicy`.
    FailedToDeployThreadsafetyPolicy,
    /// The tracking port tag, required for cleanup, could not be created.
    UnableToCreatePortTag,
}

impl core::fmt::Display for PublisherCreateError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "PublisherCreateError::{self:?}")
    }
}

impl core::error::Error for PublisherCreateError {}

#[derive(Debug, Clone, Copy)]
struct OffsetAndSize {
    offset: u64,
    size: usize,
}

#[derive(Debug)]
pub(crate) struct PublisherSharedState<Service: service::Service> {
    config: LocalPublisherConfig,
    pub(crate) sender: Sender<Service>,
    subscriber_list_state: UnsafeCell<ContainerState<SubscriberDetails>>,
    history: Option<UnsafeCell<Queue<OffsetAndSize>>>,
    is_active: AtomicBool,
    // IMPORTANT!
    // Fields of a rust struct are dropped in declaration order. Since this tag is our marker that the
    // port exists and might require cleanup after a crash, the tag must be defined as last member of
    // the struct.
    // Otherwise the process might crash during cleanup, has already removed the tag but other resources
    // are still existing. This would make a cleanup from another process impossible.
    port_tag: Service::StaticStorage,
}

impl<Service: service::Service> Abandonable for PublisherSharedState<Service> {
    unsafe fn abandon_in_place(mut this: NonNull<Self>) {
        let this = unsafe { this.as_mut() };
        unsafe { Sender::<Service>::abandon_in_place(NonNull::iox2_from_mut(&mut this.sender)) }
        unsafe {
            Service::StaticStorage::abandon_in_place(NonNull::iox2_from_mut(&mut this.port_tag))
        }
    }
}

impl<Service: service::Service> PublisherSharedState<Service> {
    fn add_sample_to_history(&self, offset: PointerOffset, sample_size: usize) {
        match &self.history {
            None => (),
            Some(history) => {
                let history = unsafe { &mut *history.get() };
                self.sender.borrow_sample(offset);
                match history.push_with_overflow(OffsetAndSize {
                    offset: offset.as_value(),
                    size: sample_size,
                }) {
                    None => (),
                    Some(old) => self
                        .sender
                        .release_sample(PointerOffset::from_value(old.offset)),
                }
            }
        }
    }

    fn force_update_connections(&self) -> Result<(), ZeroCopyCreationError> {
        let mut result = Ok(());
        self.sender.start_update_connection_cycle();
        unsafe {
            (*self.subscriber_list_state.get()).for_each(|index, port| {
                let inner_result = self.sender.update_connection(
                    index,
                    ReceiverDetails {
                        port_id: port.subscriber_id.value(),
                        buffer_size: port.buffer_size,
                    },
                    |connection| self.deliver_sample_history(connection),
                );

                if result.is_ok() {
                    result = inner_result;
                }

                CallbackProgression::Continue
            })
        };

        self.sender.finish_update_connection_cycle();

        result
    }

    fn update_connections(&self) -> Result<(), ConnectionFailure> {
        if unsafe {
            self.sender
                .service_state
                .dynamic_storage()
                .get()
                .publish_subscribe()
                .subscribers
                .update_state(&mut *self.subscriber_list_state.get())
        } {
            fail!(from self, when self.force_update_connections(),
                "Connections were updated only partially since at least one connection to a Subscriber port failed.");
        }

        Ok(())
    }

    fn deliver_sample_history(&self, connection: &Connection<Service>) {
        match &self.history {
            None => (),
            Some(history) => {
                let history = unsafe { &mut *history.get() };
                let buffer_size = connection.sender.buffer_size();
                let history_start = history.len().saturating_sub(buffer_size);

                for i in history_start..history.len() {
                    let old_sample = unsafe { history.get_unchecked(i) };
                    self.sender.retrieve_returned_samples();

                    let offset = PointerOffset::from_value(old_sample.offset);
                    match connection
                        .sender
                        .try_send(offset, old_sample.size, ChannelId::new(0))
                    {
                        Ok(overflow) => {
                            self.sender.borrow_sample(offset);

                            if let Some(old) = overflow {
                                self.sender.release_sample(old);
                            }
                        }
                        Err(e) => {
                            warn!(from self, "Failed to deliver history to new subscriber via {:?} due to {:?}", connection, e);
                        }
                    }
                }
            }
        }
    }

    pub(crate) fn send_sample(
        &self,
        offset: PointerOffset,
        sample_size: usize,
    ) -> Result<usize, SendError> {
        let msg = "Unable to send sample";
        if !self.is_active.load(Ordering::Relaxed) {
            fail!(from self, with SendError::ConnectionBrokenSinceSenderNoLongerExists,
                "{} since the corresponding publisher is already disconnected.", msg);
        }

        fail!(from self, when self.update_connections(),
            "{} since the connections could not be updated.", msg);

        self.add_sample_to_history(offset, sample_size);
        self.sender
            .deliver_offset(offset, sample_size, ChannelId::new(0))
    }
}

/// Sending endpoint of a publish-subscriber based communication.
#[derive(Debug)]
pub struct Publisher<
    Service: service::Service,
    Payload: Debug + ZeroCopySend + ?Sized + 'static,
    UserHeader: Debug + ZeroCopySend,
> {
    pub(crate) publisher_shared_state:
        Service::ArcThreadSafetyPolicy<PublisherSharedState<Service>>,
    dynamic_publisher_handle: Option<ContainerHandle>,
    _payload: PhantomData<Payload>,
    _user_header: PhantomData<UserHeader>,
}

unsafe impl<
    Service: service::Service,
    Payload: Debug + ZeroCopySend + ?Sized,
    UserHeader: Debug + ZeroCopySend,
> Send for Publisher<Service, Payload, UserHeader>
where
    Service::ArcThreadSafetyPolicy<PublisherSharedState<Service>>: Send + Sync,
{
}

unsafe impl<
    Service: service::Service,
    Payload: Debug + ZeroCopySend + ?Sized,
    UserHeader: Debug + ZeroCopySend,
> Sync for Publisher<Service, Payload, UserHeader>
where
    Service::ArcThreadSafetyPolicy<PublisherSharedState<Service>>: Send + Sync,
{
}

impl<
    Service: service::Service,
    Payload: Debug + ZeroCopySend + ?Sized,
    UserHeader: Debug + ZeroCopySend,
> Abandonable for Publisher<Service, Payload, UserHeader>
{
    unsafe fn abandon_in_place(mut this: NonNull<Self>) {
        let this = unsafe { this.as_mut() };
        unsafe {
            Service::ArcThreadSafetyPolicy::abandon_in_place(NonNull::iox2_from_mut(
                &mut this.publisher_shared_state,
            ))
        };
    }
}

impl<
    Service: service::Service,
    Payload: Debug + ZeroCopySend + ?Sized,
    UserHeader: Debug + ZeroCopySend,
> Drop for Publisher<Service, Payload, UserHeader>
{
    fn drop(&mut self) {
        let shared_state = self.publisher_shared_state.lock();
        shared_state.is_active.store(false, Ordering::Relaxed);
        if let Some(handle) = self.dynamic_publisher_handle {
            shared_state
                .sender
                .service_state
                .dynamic_storage()
                .get()
                .publish_subscribe()
                .release_publisher_handle(handle)
        }
    }
}

impl<
    Service: service::Service,
    Payload: Debug + ZeroCopySend + ?Sized,
    UserHeader: Debug + ZeroCopySend,
> Publisher<Service, Payload, UserHeader>
{
    pub(crate) fn new(
        publisher_factory: PortFactoryPublisher<Service, Payload, UserHeader>,
    ) -> Result<Self, PublisherCreateError> {
        let msg = "Unable to create Publisher port";
        let origin = "Publisher::new()";
        let port_id = UniquePublisherId::new();
        let config = &publisher_factory.config;
        let service = &publisher_factory.factory.service;
        // !MUST! be the first thing that is created when a new port is instantiated otherwise the
        // port resources might leak if this process is killed in between.
        let port_tag = match service
            .shared_node()
            .create_port_tag(origin, msg, port_id.0.value())
        {
            Ok(port_tag) => port_tag,
            Err(e) => {
                fail!(from origin, with PublisherCreateError::UnableToCreatePortTag,
                        "{msg} since the port tag, that is required for cleanup, could not be created. [{e:?}]");
            }
        };

        let static_config = publisher_factory
            .factory
            .service
            .static_config()
            .publish_subscribe();
        let subscriber_list = &service
            .dynamic_storage()
            .get()
            .publish_subscribe()
            .subscribers;

        let number_of_samples = unsafe {
            service
                .static_config()
                .messaging_pattern
                .publish_subscribe()
        }
        .required_amount_of_samples_per_data_segment(config.max_loaned_samples);

        let number_of_samples = publisher_factory
            .preallocate_number_of_samples_override
            .call(number_of_samples);

        let data_segment_type =
            DataSegmentType::new_from_allocation_strategy(config.allocation_strategy);

        let sample_layout = static_config
            .message_type_details
            .sample_layout(config.initial_max_slice_len);

        let max_slice_len = config.initial_max_slice_len;
        let max_number_of_segments =
            DataSegment::<Service>::max_number_of_segments(data_segment_type);
        let publisher_details = PublisherDetails {
            data_segment_type,
            publisher_id: port_id,
            number_of_samples,
            max_slice_len,
            node_id: *service.shared_node().id(),
            max_number_of_segments,
        };
        let global_config = service.shared_node().config();

        let segment_name = data_segment_name(publisher_details.publisher_id.value());
        let data_segment = match data_segment_type {
            DataSegmentType::Static => DataSegment::create_static_segment(
                &segment_name,
                sample_layout,
                global_config,
                number_of_samples,
            ),
            DataSegmentType::Dynamic => DataSegment::create_dynamic_segment(
                &segment_name,
                sample_layout,
                global_config,
                number_of_samples,
                config.allocation_strategy,
            ),
        };

        let data_segment = fail!(from origin,
                when data_segment,
                with PublisherCreateError::UnableToCreateDataSegment,
                "{} since the data segment could not be acquired.", msg);

        let publisher_shared_state =
            <Service as service::Service>::ArcThreadSafetyPolicy::new(PublisherSharedState {
                port_tag,
                is_active: AtomicBool::new(true),
                sender: Sender {
                    data_segment,
                    segment_states: {
                        let mut v: Vec<SegmentState> =
                            Vec::with_capacity(max_number_of_segments as usize);
                        for _ in 0..max_number_of_segments {
                            v.push(SegmentState::new(number_of_samples))
                        }
                        v
                    },
                    connections: (0..subscriber_list.capacity())
                        .map(|_| UnsafeCell::new(None))
                        .collect(),
                    sender_port_id: port_id.value(),
                    shared_node: service.shared_node().clone(),
                    receiver_max_buffer_size: static_config.subscriber_max_buffer_size,
                    receiver_max_borrowed_samples: static_config.subscriber_max_borrowed_samples,
                    enable_safe_overflow: static_config.enable_safe_overflow,
                    number_of_samples,
                    max_number_of_segments,
                    degradation_handler: publisher_factory.degradation_handler,
                    backpressure_handler: publisher_factory.backpressure_handler,
                    service_state: service.clone(),
                    tagger: CyclicTagger::new(),
                    loan_counter: AtomicUsize::new(0),
                    sender_max_borrowed_samples: config.max_loaned_samples,
                    backpressure_strategy: config.backpressure_strategy,
                    message_type_details: static_config.message_type_details,
                    number_of_channels: 1,
                    initial_channel_state: CHANNEL_STATE_OPEN,
                },
                config: *config,
                subscriber_list_state: UnsafeCell::new(unsafe { subscriber_list.get_state() }),
                history: match static_config.history_size == 0 {
                    true => None,
                    false => Some(UnsafeCell::new(Queue::new(static_config.history_size))),
                },
            });

        let publisher_shared_state = match publisher_shared_state {
            Ok(v) => v,
            Err(e) => {
                fail!(from origin,
                            with PublisherCreateError::FailedToDeployThreadsafetyPolicy,
                            "{msg} since the threadsafety policy could not be instantiated ({e:?}).");
            }
        };

        let mut new_self = Self {
            publisher_shared_state,
            dynamic_publisher_handle: None,
            _payload: PhantomData,
            _user_header: PhantomData,
        };

        if let Err(e) = new_self
            .publisher_shared_state
            .lock()
            .force_update_connections()
        {
            warn!(from new_self,
                "The new Publisher port is unable to connect to every Subscriber port, caused by {:?}.", e);
        }

        core::sync::atomic::compiler_fence(Ordering::SeqCst);

        // !MUST! be the last task otherwise a publisher is added to the dynamic config without the
        // creation of all required resources
        let dynamic_publisher_handle = match service
            .dynamic_storage()
            .get()
            .publish_subscribe()
            .add_publisher_id(publisher_details)
        {
            Some(unique_index) => unique_index,
            None => {
                fail!(from origin, with PublisherCreateError::ExceedsMaxSupportedPublishers,
                            "{} since it would exceed the maximum supported amount of publishers of {}.",
                            msg, service.static_config().publish_subscribe().max_publishers);
            }
        };

        new_self.dynamic_publisher_handle = Some(dynamic_publisher_handle);

        Ok(new_self)
    }

    /// Returns the [`UniquePublisherId`] of the [`Publisher`]
    pub fn id(&self) -> UniquePublisherId {
        UniquePublisherId(UniqueSystemId::from(
            self.publisher_shared_state.lock().sender.sender_port_id,
        ))
    }

    /// Returns the strategy the [`Publisher`] follows when a [`SampleMut`] cannot be delivered
    /// since the [`Subscriber`](crate::port::subscriber::Subscriber)s buffer is full.
    pub fn backpressure_strategy(&self) -> BackpressureStrategy {
        self.publisher_shared_state
            .lock()
            .sender
            .backpressure_strategy
    }
}

////////////////////////
// BEGIN: typed API
////////////////////////
impl<
    Service: service::Service,
    Payload: Debug + ZeroCopySend + Sized,
    UserHeader: Default + Debug + ZeroCopySend,
> Publisher<Service, Payload, UserHeader>
{
    /// Copies the input `value` into a [`crate::sample_mut::SampleMut`] and delivers it.
    /// On success it returns the number of [`crate::port::subscriber::Subscriber`]s that received
    /// the data, otherwise a [`SendError`] describing the failure.
    ///
    /// # Example
    ///
    /// ```
    /// use iceoryx2::prelude::*;
    /// # fn main() -> Result<(), Box<dyn core::error::Error>> {
    /// # let node = NodeBuilder::new().create::<ipc::Service>()?;
    /// #
    /// # let service = node.service_builder(&"My/Funk/ServiceName".try_into()?)
    /// #     .publish_subscribe::<u64>()
    /// #     .open_or_create()?;
    /// #
    /// # let publisher = service.publisher_builder()
    /// #                        .create()?;
    ///
    /// publisher.send_copy(1234)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn send_copy(&self, value: Payload) -> Result<usize, SendError> {
        let msg = "Unable to send copy of payload";
        let sample = fail!(from self, when self.loan_uninit(),
                                    "{} since the loan of a sample failed.", msg);

        sample.write_payload(value).send()
    }

    /// Loans/allocates a [`SampleMutUninit`] from the underlying data segment of the [`Publisher`].
    /// The user has to initialize the payload before it can be sent.
    ///
    /// On failure it returns [`LoanError`] describing the failure.
    ///
    /// # Example
    ///
    /// ```
    /// use iceoryx2::prelude::*;
    /// # fn main() -> Result<(), Box<dyn core::error::Error>> {
    /// # let node = NodeBuilder::new().create::<ipc::Service>()?;
    /// #
    /// # let service = node.service_builder(&"My/Funk/ServiceName".try_into()?)
    /// #     .publish_subscribe::<u64>()
    /// #     .open_or_create()?;
    /// #
    /// # let publisher = service.publisher_builder()
    /// #                        .create()?;
    ///
    /// let sample = publisher.loan_uninit()?;
    /// let sample = sample.write_payload(42); // alternatively `sample.payload_mut()` can be use to access the `MaybeUninit<Payload>`
    ///
    /// sample.send()?;
    ///
    /// # Ok(())
    /// # }
    /// ```
    pub fn loan_uninit(
        &self,
    ) -> Result<SampleMutUninit<Service, MaybeUninit<Payload>, UserHeader>, LoanError> {
        let shared_state = self.publisher_shared_state.lock();
        let chunk = shared_state
            .sender
            .allocate(shared_state.sender.sample_layout(1))?;
        let node_id = shared_state.sender.service_state.shared_node().id();
        let header_ptr = chunk.header as *mut Header;
        let user_header_ptr: *mut UserHeader = chunk.user_header.cast();
        unsafe { header_ptr.write(Header::new(*node_id, self.id(), 1)) };
        unsafe { user_header_ptr.write(UserHeader::default()) };

        let sample = unsafe {
            RawSampleMut::new_unchecked(header_ptr, user_header_ptr, chunk.payload.cast())
        };
        Ok(
            SampleMutUninit::<Service, MaybeUninit<Payload>, UserHeader>::new(
                &self.publisher_shared_state,
                sample,
                chunk.offset,
                chunk.size,
            ),
        )
    }
}

impl<
    Service: service::Service,
    Payload: Default + Debug + ZeroCopySend + Sized,
    UserHeader: Default + Debug + ZeroCopySend,
> Publisher<Service, Payload, UserHeader>
{
    /// Loans/allocates a [`crate::sample_mut::SampleMut`] from the underlying data segment of the [`Publisher`]
    /// and initialize it with the default value. This can be a performance hit and [`Publisher::loan_uninit`]
    /// can be used to loan a [`core::mem::MaybeUninit<Payload>`].
    ///
    /// On failure it returns [`LoanError`] describing the failure.
    ///
    /// # Example
    ///
    /// ```
    /// use iceoryx2::prelude::*;
    /// # fn main() -> Result<(), Box<dyn core::error::Error>> {
    /// # let node = NodeBuilder::new().create::<ipc::Service>()?;
    /// #
    /// # let service = node.service_builder(&"My/Funk/ServiceName".try_into()?)
    /// #     .publish_subscribe::<u64>()
    /// #     .open_or_create()?;
    /// #
    /// # let publisher = service.publisher_builder().create()?;
    ///
    /// let mut sample = publisher.loan()?;
    /// *sample.payload_mut() = 42;
    ///
    /// sample.send()?;
    ///
    /// # Ok(())
    /// # }
    /// ```
    pub fn loan(&self) -> Result<SampleMut<Service, Payload, UserHeader>, LoanError> {
        Ok(self.loan_uninit()?.write_payload(Payload::default()))
    }
}
////////////////////////
// END: typed API
////////////////////////

////////////////////////
// BEGIN: sliced API
////////////////////////
impl<
    Service: service::Service,
    Payload: Default + Debug + ZeroCopySend,
    UserHeader: Default + Debug + ZeroCopySend,
> Publisher<Service, [Payload], UserHeader>
{
    /// Loans/allocates a [`crate::sample_mut::SampleMut`] from the underlying data segment of the [`Publisher`]
    /// and initializes all slice elements with the default value. This can be a performance hit
    /// and [`Publisher::loan_slice_uninit()`] can be used to loan a slice of
    /// [`core::mem::MaybeUninit<Payload>`].
    ///
    /// On failure it returns [`LoanError`] describing the failure.
    ///
    /// # Example
    ///
    /// ```
    /// use iceoryx2::prelude::*;
    /// # fn main() -> Result<(), Box<dyn core::error::Error>> {
    /// # let node = NodeBuilder::new().create::<ipc::Service>()?;
    /// #
    /// # let service = node.service_builder(&"My/Funk/ServiceName".try_into()?)
    /// #     .publish_subscribe::<[u64]>()
    /// #     .open_or_create()?;
    /// #
    /// # let publisher = service.publisher_builder()
    /// #                        .initial_max_slice_len(120)
    /// #                        .create()?;
    ///
    /// let slice_length = 5;
    /// let mut sample = publisher.loan_slice(slice_length)?;
    /// sample.payload_mut()[2] = 42;
    ///
    /// sample.send()?;
    ///
    /// # Ok(())
    /// # }
    /// ```
    pub fn loan_slice(
        &self,
        number_of_elements: usize,
    ) -> Result<SampleMut<Service, [Payload], UserHeader>, LoanError> {
        let sample = self.loan_slice_uninit(number_of_elements)?;
        Ok(sample.write_from_fn(|_| Payload::default()))
    }
}

impl<Service: service::Service, Payload: Debug + ZeroCopySend, UserHeader: Debug + ZeroCopySend>
    Publisher<Service, [Payload], UserHeader>
{
    /// Returns the maximum initial slice length configured for this [`Publisher`].
    pub fn initial_max_slice_len(&self) -> usize {
        self.publisher_shared_state
            .lock()
            .config
            .initial_max_slice_len
    }
}

impl<
    Service: service::Service,
    Payload: Debug + ZeroCopySend,
    UserHeader: Default + Debug + ZeroCopySend,
> Publisher<Service, [Payload], UserHeader>
{
    /// Loans/allocates a [`SampleMutUninit`] from the underlying data segment of the [`Publisher`].
    /// The user has to initialize the payload before it can be sent.
    ///
    /// On failure it returns [`LoanError`] describing the failure.
    ///
    /// # Example
    ///
    /// ```
    /// use iceoryx2::prelude::*;
    ///
    /// # let node = NodeBuilder::new().create::<ipc::Service>()?;
    /// #
    /// # let service = node.service_builder(&"My/Funk/ServiceName".try_into()?)
    /// #     .publish_subscribe::<[usize]>()
    /// #     .open_or_create()?;
    /// #
    /// # let publisher = service.publisher_builder()
    /// #                        .initial_max_slice_len(120)
    /// #                        .create()?;
    ///
    /// let slice_length = 5;
    /// let sample = publisher.loan_slice_uninit(slice_length)?;
    /// let sample = sample.write_from_fn(|n| n * 2); // alternatively `sample.payload_mut()` can be use to access the `[MaybeUninit<Payload>]`
    ///
    /// sample.send()?;
    /// # Ok::<_, Box<dyn core::error::Error>>(())
    /// ```
    pub fn loan_slice_uninit(
        &self,
        slice_len: usize,
    ) -> Result<SampleMutUninit<Service, [MaybeUninit<Payload>], UserHeader>, LoanError> {
        // required since Rust does not support generic specializations or negative traits
        debug_assert!(TypeId::of::<Payload>() != TypeId::of::<CustomPayloadMarker>());

        self.loan_slice_uninit_impl(slice_len, slice_len)
    }

    fn loan_slice_uninit_impl(
        &self,
        slice_len: usize,
        underlying_number_of_slice_elements: usize,
    ) -> Result<SampleMutUninit<Service, [MaybeUninit<Payload>], UserHeader>, LoanError> {
        let shared_state = self.publisher_shared_state.lock();
        let max_slice_len = shared_state.config.initial_max_slice_len;
        if shared_state.config.allocation_strategy == AllocationStrategy::Static
            && max_slice_len < slice_len
        {
            fail!(from self, with LoanError::ExceedsMaxLoanSize,
                "Unable to loan slice with {} elements since it would exceed the max supported slice length of {}.",
                slice_len, max_slice_len);
        }

        let sample_layout = shared_state.sender.sample_layout(slice_len);
        let chunk = shared_state.sender.allocate(sample_layout)?;
        let user_header_ptr: *mut UserHeader = chunk.user_header.cast();
        let header_ptr = chunk.header as *mut Header;
        let node_id = shared_state.sender.service_state.shared_node().id();
        unsafe { header_ptr.write(Header::new(*node_id, self.id(), slice_len as _)) };
        unsafe { user_header_ptr.write(UserHeader::default()) };

        let sample = unsafe {
            RawSampleMut::new_unchecked(
                header_ptr,
                user_header_ptr,
                core::ptr::slice_from_raw_parts_mut(
                    chunk.payload.cast(),
                    underlying_number_of_slice_elements,
                ),
            )
        };

        Ok(
            SampleMutUninit::<Service, [MaybeUninit<Payload>], UserHeader>::new(
                &self.publisher_shared_state,
                sample,
                chunk.offset,
                chunk.size,
            ),
        )
    }
}

impl<Service: service::Service> Publisher<Service, [CustomPayloadMarker], CustomHeaderMarker> {
    /// # Safety
    ///
    ///  * slice_len != 1 only when payload TypeVariant == Dynamic
    ///  * The number_of_elements in the [`Header`](crate::service::header::publish_subscribe::Header)
    ///     is set to `slice_len`
    ///  * The [`SampleMutUninit`] will contain `slice_len` * `MessageTypeDetails::payload.size`
    ///     elements of type [`CustomPayloadMarker`].
    #[doc(hidden)]
    pub unsafe fn loan_custom_payload(
        &self,
        slice_len: usize,
    ) -> Result<
        SampleMutUninit<Service, [MaybeUninit<CustomPayloadMarker>], CustomHeaderMarker>,
        LoanError,
    > {
        let shared_state = self.publisher_shared_state.lock();

        // TypeVariant::Dynamic == slice and only here it makes sense to loan more than one element
        debug_assert!(
            slice_len == 1 || shared_state.sender.payload_type_variant() == TypeVariant::Dynamic
        );

        self.loan_slice_uninit_impl(slice_len, shared_state.sender.payload_size() * slice_len)
    }
}
////////////////////////
// END: sliced API
////////////////////////

impl<
    Service: service::Service,
    Payload: Debug + ZeroCopySend + ?Sized,
    UserHeader: Debug + ZeroCopySend,
> UpdateConnections for Publisher<Service, Payload, UserHeader>
{
    fn update_connections(&self) -> Result<(), ConnectionFailure> {
        self.publisher_shared_state.lock().update_connections()
    }
}