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
//! Resting place for [FullSyncZeroCopy]

use crate::ogre_std::{
    ogre_queues::{
        full_sync::full_sync_move::FullSyncMove,
        meta_publisher::{MetaPublisher,MovePublisher},
        meta_subscriber::{MetaSubscriber,MoveSubscriber},
        meta_container::{MetaContainer, MoveContainer},
    },
    ogre_alloc::{
        OgreAllocator,
    },
};
use std::{
    num::NonZeroU32,
    marker::PhantomData,
    sync::Arc,
    fmt::Debug,
};


/// Basis for multiple producer / multiple consumer queues using a quick-and-dirty (but fast)
/// full synchronization through an atomic flag, with a clever & experimentally tuned efficient locking mechanism.
///
/// This queue implements the "zero-copy patterns" through [ZeroCopyPublisher] & [ZeroCopySubscriber] and
/// is a good fit for payloads > 1k.
///
/// For thinner payloads, [FullSyncMove] should be a better fit, as it doesn't require a secondary container to
/// hold the objects.
pub struct FullSyncZeroCopy<SlotType:          Debug + Send + Sync,
                            OgreAllocatorType: OgreAllocator<SlotType>,
                            const BUFFER_SIZE: usize> {

    pub(crate) allocator: Arc<OgreAllocatorType>,
               queue:     FullSyncMove<u32, BUFFER_SIZE>,
               _phantom:  PhantomData<SlotType>

}


impl<'a, SlotType:          'a + Debug + Send + Sync,
         OgreAllocatorType: OgreAllocator<SlotType>,
         const BUFFER_SIZE: usize>
MetaContainer<'a, SlotType> for
FullSyncZeroCopy<SlotType, OgreAllocatorType, BUFFER_SIZE> {

    fn new() -> Self {
        Self {
            allocator: Arc::new(OgreAllocatorType::new()),
            queue:     FullSyncMove::new(),
            _phantom:  PhantomData::default(),
        }
    }
}


impl<'a, SlotType:          'a + Debug + Send + Sync,
         OgreAllocatorType: OgreAllocator<SlotType>,
         const BUFFER_SIZE: usize>
MetaPublisher<'a, SlotType> for
FullSyncZeroCopy<SlotType, OgreAllocatorType, BUFFER_SIZE> {

    #[inline(always)]
    fn publish<F: FnOnce(&mut SlotType)>(&self, setter: F) -> Option<NonZeroU32> {
        match self.leak_slot() {
            Some( (slot_ref, slot_id) ) => {
                setter(slot_ref);
                self.publish_leaked_id(slot_id)
            },
            None => None,
        }
    }

    #[inline(always)]
    fn publish_movable(&self, item: SlotType) -> Option<NonZeroU32> {
        match self.leak_slot() {
            Some( (slot_ref, slot_id) ) => {
                *slot_ref = item;
                self.publish_leaked_id(slot_id)
            }
            None => None,
        }
    }

    #[inline(always)]
    fn leak_slot(&self) -> Option<(/*ref:*/ &mut SlotType, /*id: */u32)> {
        self.allocator.alloc_ref()
    }

    #[inline(always)]
    fn publish_leaked_ref(&'a self, slot: &'a SlotType) -> Option<NonZeroU32> {
        self.publish_leaked_id(self.allocator.id_from_ref(slot))
    }

    #[inline(always)]
    fn publish_leaked_id(&'a self, slot_id: u32) -> Option<NonZeroU32> {
        self.queue.publish_movable(slot_id)
    }

    #[inline(always)]
    fn unleak_slot_ref(&'a self, slot: &'a mut SlotType) {
        self.allocator.dealloc_ref(slot);
    }

    #[inline(always)]
    fn unleak_slot_id(&'a self, slot_id: u32) {
        self.allocator.dealloc_id(slot_id);
    }

    #[inline(always)]
    fn available_elements_count(&self) -> usize {
        self.queue.available_elements_count()
    }

    #[inline(always)]
    fn max_size(&self) -> usize {
        BUFFER_SIZE
    }

    fn debug_info(&self) -> String {
        todo!()
    }
}


impl<'a, SlotType:          'a + Debug + Sync + Send,
         OgreAllocatorType: OgreAllocator<SlotType>,
         const BUFFER_SIZE: usize>
MetaSubscriber<'a, SlotType> for
FullSyncZeroCopy<SlotType, OgreAllocatorType, BUFFER_SIZE> {

    #[inline(always)]
    fn consume<GetterReturnType: 'a,
               GetterFn:                   FnOnce(&SlotType) -> GetterReturnType,
               ReportEmptyFn:              Fn() -> bool,
               ReportLenAfterDequeueingFn: FnOnce(i32)>
              (&self,
               getter_fn:                      GetterFn,
               report_empty_fn:                ReportEmptyFn,
               report_len_after_dequeueing_fn: ReportLenAfterDequeueingFn)
              -> Option<GetterReturnType> {

        match self.consume_leaking() {
            Some( (slot_ref, slot_id) ) => {
                let len_after_dequeueing = self.queue.available_elements_count() as i32;
                let ret_val = getter_fn(slot_ref);
                self.release_leaked_id(slot_id);
                report_len_after_dequeueing_fn(len_after_dequeueing);
                Some(ret_val)
            },
            None => {
                report_empty_fn();
                None
            },
        }
    }

    #[inline(always)]
    fn consume_leaking(&'a self) -> Option<(/*ref:*/ &'a SlotType, /*id: */u32)> {
        match self.queue.consume_movable() {
            Some(slot_id) => Some( (self.allocator.ref_from_id(slot_id), slot_id) ),
            None => None,
        }
    }

    #[inline(always)]
    fn release_leaked_ref(&'a self, slot: &'a SlotType) {
        let mutable_slot = unsafe { &mut *(&*(slot as *const SlotType as *const std::cell::UnsafeCell<SlotType>)).get() };
        self.allocator.dealloc_ref(mutable_slot);
    }

    #[inline(always)]
    fn release_leaked_id(&'a self, slot_id: u32) {
        self.allocator.dealloc_id(slot_id);
    }

    #[inline(always)]
    fn remaining_elements_count(&self) -> usize {
        self.available_elements_count()
    }


    #[inline(always)]
    unsafe fn peek_remaining(&self) -> Vec<&SlotType> {
        self.queue.peek_remaining().iter()
            .flat_map(|&slice| slice)
            .map(|slot_id| self.allocator.ref_from_id(*slot_id) as &SlotType)
            .collect()
    }
}



#[cfg(any(test,doc))]
mod tests {
    //! Unit tests for [full_sync_zero_copy](super) module

    //use super::*;

}