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
// Copyright (c) 2023 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

//! Provides the [`NamedSemaphore`] and the [`UnnamedSemaphore`]. Both can be used in an
//! inter-process context to signal events between processes.

use std::sync::atomic::{AtomicBool, AtomicI64, Ordering};
use std::{cell::UnsafeCell, fmt::Debug};

pub use crate::unmovable_ipc_handle::IpcCapable;
use crate::unmovable_ipc_handle::{internal::*, IpcHandleState};
use iceoryx2_bb_container::semantic_string::*;
use iceoryx2_bb_elementary::enum_gen;
use iceoryx2_bb_log::{debug, fail, fatal_panic};
use iceoryx2_bb_system_types::file_name::FileName;
use iceoryx2_bb_system_types::file_path::*;
use iceoryx2_bb_system_types::path::*;
use iceoryx2_pal_posix::posix::errno::Errno;
use iceoryx2_pal_posix::posix::Struct;
use iceoryx2_pal_posix::*;

use crate::{
    adaptive_wait::*,
    clock::{AsTimespec, Time, TimeError},
    config::MAX_INITIAL_SEMAPHORE_VALUE,
    handle_errno,
    system_configuration::*,
};
use std::time::Duration;

pub use crate::clock::ClockType;
pub use crate::creation_mode::CreationMode;
pub use crate::permission::Permission;

enum_gen! { NamedSemaphoreCreationError
  entry:
    InsufficientPermissions,
    InitialValueTooLarge,
    PerProcessFileHandleLimitReached,
    SystemWideFileHandleLimitReached,
    AlreadyExists,
    MaxFilePathLengthExceeded,
    Interrupt,
    NotSupportForGivenName,
    DoesNotExist,
    NoSpaceLeft,
    UnknownError(i32)
}

#[derive(Debug, Clone, Copy, Eq, Hash, PartialEq)]
pub enum UnnamedSemaphoreCreationError {
    InitialValueTooLarge,
    ExceedsMaximumNumberOfSemaphores,
    InsufficientPermissions,
    HandleAlreadyInitialized,
    UnknownError(i32),
}

#[derive(Debug, Clone, Copy, Eq, Hash, PartialEq)]
pub enum SemaphorePostError {
    Overflow,
    UnknownError(i32),
}

#[derive(Debug, Clone, Copy, Eq, Hash, PartialEq)]
pub enum SemaphoreWaitError {
    NotSupported,
    DeadlockConditionDetected,
    Interrupt,
    UnknownError(i32),
}

#[derive(Debug, Clone, Copy, Eq, Hash, PartialEq)]
pub enum UnnamedSemaphoreOpenIpcHandleError {
    IsNotInterProcessCapable,
    Uninitialized,
}

enum_gen! {
    SemaphoreTimedWaitError
  entry:
    WaitingTimeExceedsSystemLimits
  mapping:
    SemaphoreWaitError,
    AdaptiveWaitError,
    TimeError
}

enum_gen! {
    /// The SemaphoreError enum is a generalization when one doesn't require the fine-grained error
    /// handling enums. One can forward SemaphoreError as more generic return value when a method
    /// returns a Semaphore***Error.
    /// On a higher level it is again convertable to [`crate::Error`].
    SemaphoreError
  generalization:
    FailedToCreate <= NamedSemaphoreCreationError; UnnamedSemaphoreCreationError,
    FailedToPost <= SemaphorePostError,
    FailedToWait <= SemaphoreWaitError; SemaphoreTimedWaitError
}

#[derive(PartialEq, Eq)]
enum UnlinkMode {
    IgnoreNonExistingSemaphore,
    FailWhenSemaphoreDoesNotExist,
}

#[derive(PartialEq, Eq)]
enum InitMode {
    Create,
    Open,
    TryOpen,
}

mod internal {
    use super::*;

    #[doc(hidden)]
    pub trait SemaphoreHandle {
        fn handle(&self) -> *mut posix::sem_t;
        fn get_clock_type(&self) -> ClockType;
    }
}

/// Defines the interface of a [`NamedSemaphore`] and an [`UnnamedSemaphore`].
pub trait SemaphoreInterface: internal::SemaphoreHandle + Debug {
    /// Increments the semaphore by one. If the semaphore already holds the maximum supported value
    /// another post call will lead to [`SemaphorePostError::Overflow`].
    fn post(&self) -> Result<(), SemaphorePostError> {
        if unsafe { posix::sem_post(self.handle()) } == 0 {
            return Ok(());
        }

        let msg = "Unable to post semaphore";
        handle_errno!(SemaphorePostError, from self,
            fatal Errno::EINVAL => ("This should never happen! {} since an invalid handle was provided.", msg),
            Errno::EOVERFLOW => (Overflow, "{} since the operation would cause an overflow.", msg),
            v => (UnknownError(v as i32), "{} since an unknown error occurred ({}).", msg, v)
        );
    }

    /// Decrements the semaphore by one. If the semaphore is zero it waits until a
    /// [`SemaphoreInterface::post()`] call incremented the semaphore by one. A semaphores internal
    /// value is always greater or equal to zero.
    fn wait(&self) -> Result<(), SemaphoreWaitError> {
        if unsafe { posix::sem_wait(self.handle()) } == 0 {
            return Ok(());
        }

        let msg = "Unable to wait on semaphore";
        handle_errno!(SemaphoreWaitError, from self,
            fatal Errno::EINVAL => ("This should never happen! {} since an invalid handle was provided!", msg),
            Errno::ENOSYS => (NotSupported, "{} since sem_wait is not supported by the system.", msg),
            Errno::EDEADLK => (DeadlockConditionDetected, "{} since a deadlock condition was detected.", msg),
            Errno::EINTR => (Interrupt, "{} since an interrupt signal was received.", msg),
            v => (UnknownError(v as i32), "{} since an unknown error occurred ({}).", msg, v)
        );
    }

    /// Tries to decrement the semaphore by one if it is greater zero and returns true. If the semaphores
    /// internal value is zero it returns false and does not decrement the semaphore.
    fn try_wait(&self) -> Result<bool, SemaphoreWaitError> {
        if unsafe { posix::sem_trywait(self.handle()) } == 0 {
            return Ok(true);
        }

        let msg = "Unable to wait on semaphore";
        handle_errno!(SemaphoreWaitError, from self,
            success Errno::EAGAIN => false,
            fatal Errno::EINVAL => ("This should never happen! {} since an invalid handle was provided!", msg),
            Errno::ENOSYS => (NotSupported, "{} since sem_wait is not supported by the system.", msg),
            Errno::EDEADLK => (DeadlockConditionDetected, "{} since a deadlock condition was detected.", msg),
            Errno::EINTR => (Interrupt, "{} since an interrupt signal was received.", msg),
            v => (UnknownError(v as i32), "{} since an unknown error occurred ({}).", msg, v)
        );
    }

    /// Tries to decrement the semaphore until the decrement was successful and returns true
    /// or the timeout has passed and then returns false.
    fn timed_wait(&self, timeout: Duration) -> Result<bool, SemaphoreTimedWaitError> {
        let msg = "Unable to timed wait on semaphore";
        match self.clock_type() {
            ClockType::Monotonic => {
                let mut adaptive_wait = fail!(from self, when AdaptiveWaitBuilder::new()
                    .clock_type(self.clock_type())
                    .create(), "{} since the adaptive wait could not be created.", msg);

                match adaptive_wait.timed_wait_while(
                    || -> Result<bool, SemaphoreWaitError> { Ok(!self.try_wait()?) },
                    timeout,
                ) {
                    Ok(v) => Ok(v),
                    Err(AdaptiveTimedWaitWhileError::PredicateFailure(v)) => {
                        fail!(from self, with SemaphoreTimedWaitError::from(v),
                            "{} since try_wait() failed with ({:?}).", msg, v);
                    }
                    Err(AdaptiveTimedWaitWhileError::AdaptiveWaitError(v)) => {
                        fail!(from self, with SemaphoreTimedWaitError::from(v),
                             "{} since adaptive wait failed with ({:?}).", msg, v);
                    }
                }
            }
            ClockType::Realtime => {
                let wait_time = timeout
                    + fail!(from self, when Time::now_with_clock(self.clock_type()),
                    "{} due to a failure while acquiring the current system time.", msg)
                    .as_duration();
                if unsafe { posix::sem_timedwait(self.handle(), &wait_time.as_timespec()) } == 0 {
                    return Ok(true);
                }

                let msg = "Failed to perform timedwait";
                handle_errno!(SemaphoreTimedWaitError, from self,
                    success Errno::ETIMEDOUT => false,
                    Errno::EINVAL => (WaitingTimeExceedsSystemLimits, "{} since the provided duration {:?} exceeds the maximum supported limit.", msg, timeout),
                    Errno::EDEADLK => (SemaphoreWaitError(SemaphoreWaitError::DeadlockConditionDetected), "{} since a deadlock condition was detected.", msg),
                    Errno::EINTR => (SemaphoreWaitError(SemaphoreWaitError::Interrupt), "{} since an interrupt signal occurred.", msg),
                    v => (SemaphoreWaitError(SemaphoreWaitError::UnknownError(v as i32)), "{} since an unknown error occurred ({}).", msg, v)
                )
            }
        }
    }

    fn clock_type(&self) -> ClockType {
        self.get_clock_type()
    }
}

/// Builder for the [`NamedSemaphore`].
///
/// # Example
///
/// ## Create new named semaphore
///
/// ```ignore
/// use iceoryx2_bb_posix::semaphore::*;
/// use iceoryx2_bb_system_types::file_name::FileName;
/// use iceoryx2_bb_container::semantic_string::*;
///
/// let name = FileName::new(b"mySemaphoreName").unwrap();
/// let semaphore = NamedSemaphoreBuilder::new(&name)
///     // defines the clock which is used in [`SemaphoreInterface::timed_wait()`]
///                     .clock_type(ClockType::Monotonic)
///     // the semaphore is created, if there already exists a semaphore it is deleted
///                     .creation_mode(CreationMode::PurgeAndCreate)
///                     .initial_value(5)
///                     .permission(Permission::OWNER_ALL | Permission::GROUP_ALL)
///                     .create()
///                     .expect("failed to create semaphore");
/// ```
///
/// ## Open existing semaphore
///
/// ```no_run
/// use iceoryx2_bb_posix::semaphore::*;
/// use iceoryx2_bb_system_types::file_name::FileName;
/// use iceoryx2_bb_container::semantic_string::*;
///
/// let name = FileName::new(b"mySemaphoreName").unwrap();
/// let semaphore = NamedSemaphoreBuilder::new(&name)
///                     .clock_type(ClockType::Monotonic)
///                     .open_existing()
///                     .expect("failed to open semaphore");
/// ```
#[derive(Debug)]
pub struct NamedSemaphoreBuilder {
    name: FileName,
    initial_value: u32,
    permission: Permission,
    clock_type: ClockType,
    creation_mode: Option<CreationMode>,
}

impl NamedSemaphoreBuilder {
    pub fn new(name: &FileName) -> Self {
        Self {
            creation_mode: None,
            name: *name,
            initial_value: 0,
            permission: Permission::OWNER_ALL,
            clock_type: ClockType::default(),
        }
    }

    /// Sets the type of clock which will be used in [`SemaphoreInterface::timed_wait()`]. Be
    /// aware a clock like [`ClockType::Realtime`] is depending on the systems local time. If this
    /// time changes while waiting it can cause extrem long waits or no wait at all.
    pub fn clock_type(mut self, value: ClockType) -> Self {
        self.clock_type = value;
        self
    }

    /// Opens an already existing [`NamedSemaphore`].
    pub fn open_existing(self) -> Result<NamedSemaphore, NamedSemaphoreCreationError> {
        NamedSemaphore::new(self)
    }

    /// Defines how the semaphore will be created and returns the [`NamedSemaphoreCreationBuilder`]
    /// which provides further means of configuration only available when a semaphore is created.
    pub fn creation_mode(mut self, creation_mode: CreationMode) -> NamedSemaphoreCreationBuilder {
        self.creation_mode = Some(creation_mode);
        NamedSemaphoreCreationBuilder { config: self }
    }
}

/// Provides additional settings which are only available for newly created semaphores. Is
/// returned by [`NamedSemaphoreBuilder::creation_mode()`].
///
/// For an example see [`NamedSemaphoreBuilder`]
pub struct NamedSemaphoreCreationBuilder {
    config: NamedSemaphoreBuilder,
}

impl NamedSemaphoreCreationBuilder {
    /// Sets the initial value of the semaphore. Must be less than [`MAX_INITIAL_SEMAPHORE_VALUE`].
    pub fn initial_value(mut self, value: u32) -> Self {
        self.config.initial_value = value;
        self
    }

    /// Sets the permission of the newly created semaphore.
    pub fn permission(mut self, value: Permission) -> Self {
        self.config.permission = value;
        self
    }

    /// Creates a [`NamedSemaphore`].
    pub fn create(self) -> Result<NamedSemaphore, NamedSemaphoreCreationError> {
        NamedSemaphore::new(self.config)
    }
}

/// Represents a POSIX named semaphore - a semaphore with a corresponding file handle which can
/// be opened by other processes. The filename corresponds to the semaphore name. A named semaphore
/// is created by the [`NamedSemaphoreBuilder`].
///
/// # Example
///
/// ## In process 1
/// ```no_run
/// use iceoryx2_bb_posix::semaphore::*;
/// use iceoryx2_bb_posix::clock::*;
/// use std::time::Duration;
/// use iceoryx2_bb_system_types::file_name::FileName;
/// use iceoryx2_bb_container::semantic_string::*;
///
/// let name = FileName::new(b"mySemaphoreName").unwrap();
/// let semaphore = NamedSemaphoreBuilder::new(&name)
///                     .creation_mode(CreationMode::PurgeAndCreate)
///                     .permission(Permission::OWNER_ALL)
///                     .create()
///                     .expect("failed to create semaphore");
///
/// loop {
///     nanosleep(Duration::from_secs(1));
///     println!("trigger process 2");
///     semaphore.post().expect("failed to trigger semaphore");
/// }
/// ```
///
/// ## In process 2
/// ```no_run
/// use iceoryx2_bb_posix::semaphore::*;
/// use iceoryx2_bb_system_types::file_name::FileName;
/// use iceoryx2_bb_container::semantic_string::*;
///
/// let name = FileName::new(b"mySemaphoreName").unwrap();
/// let semaphore = NamedSemaphoreBuilder::new(&name)
///                     .open_existing()
///                     .expect("failed to open semaphore");
///
/// loop {
///     semaphore.wait().expect("failed to wait on semaphore");
///     println!("process 1 has triggered me");
/// }
/// ```
///
/// ## Output
///
/// When both processes are running in two separate terminals one can observe that process 1 triggers
/// process 2 every second.
#[derive(Debug)]
pub struct NamedSemaphore {
    name: FileName,
    handle: *mut posix::sem_t,
    has_ownership: bool,
    clock_type: ClockType,
}

unsafe impl Send for NamedSemaphore {}
unsafe impl Sync for NamedSemaphore {}

impl Drop for NamedSemaphore {
    fn drop(&mut self) {
        if self.handle == posix::SEM_FAILED {
            return;
        }

        if unsafe { posix::sem_close(self.handle) } != 0 {
            fatal_panic!(from self, "This should never happen! The semaphore handle is invalid and cannot be closed.");
        }

        if self.has_ownership
            && self
                .unlink(UnlinkMode::FailWhenSemaphoreDoesNotExist)
                .is_err()
        {
            fatal_panic!(from self, "Failed to cleanup semaphore. Something else removed a managed semaphore which should never happen!");
        }
    }
}

impl NamedSemaphore {
    fn new(config: NamedSemaphoreBuilder) -> Result<NamedSemaphore, NamedSemaphoreCreationError> {
        let mut new_sem = NamedSemaphore {
            name: config.name,
            handle: posix::SEM_FAILED,
            has_ownership: false,
            clock_type: config.clock_type,
        };

        match config.creation_mode {
            None => {
                new_sem.open(Permission::none(), InitMode::Open, 0)?;
            }
            Some(CreationMode::PurgeAndCreate) => {
                new_sem.has_ownership = true;
                fail!(from new_sem, when new_sem.unlink(UnlinkMode::IgnoreNonExistingSemaphore), "Failed to remove semaphore before creating a new one.");
                new_sem.open(config.permission, InitMode::Create, config.initial_value)?;
            }
            Some(CreationMode::CreateExclusive) => {
                new_sem.has_ownership = true;
                new_sem.open(config.permission, InitMode::Create, config.initial_value)?;
            }
            Some(CreationMode::OpenOrCreate) => {
                match new_sem.open(Permission::none(), InitMode::TryOpen, 0) {
                    Ok(()) => (),
                    Err(NamedSemaphoreCreationError::DoesNotExist) => {
                        new_sem.has_ownership = true;
                        new_sem.open(config.permission, InitMode::Create, config.initial_value)?;
                    }
                    Err(v) => return Err(v),
                }
            }
        };

        Ok(new_sem)
    }

    fn unlink(&mut self, mode: UnlinkMode) -> Result<(), NamedSemaphoreCreationError> {
        let file_path =
            FilePath::from_path_and_file(&Path::new(b"/").unwrap(), &self.name).unwrap();
        if unsafe { posix::sem_unlink(file_path.as_c_str()) } == 0 {
            debug!(from self, "semaphore removed.");
            return Ok(());
        }

        let msg = "Unable to unlink semaphore";
        let ignore_non_existing_semaphore = mode == UnlinkMode::IgnoreNonExistingSemaphore;
        handle_errno!(NamedSemaphoreCreationError, from self,
            success_when ignore_non_existing_semaphore,
                Errno::ENOENT => ((), AlreadyExists, "{} since no semaphore with the given name exists.", msg),
            Errno::EACCES => (InsufficientPermissions, "{} due to insufficient permissions.", msg),
            Errno::ENAMETOOLONG => (MaxFilePathLengthExceeded, "{} since the name exceeds the maximum supported length.", msg),
            v => (UnknownError(v as i32), "{} since an unknown error occurred ({}).", msg, v)
        )
    }

    fn open(
        &mut self,
        permission: Permission,
        mode: InitMode,
        initial_value: u32,
    ) -> Result<(), NamedSemaphoreCreationError> {
        let msg;
        if initial_value > MAX_INITIAL_SEMAPHORE_VALUE {
            fail!(from self, with NamedSemaphoreCreationError::InitialValueTooLarge,
                "Unable to create semaphore since the initial semaphore value {} is greater than the maximum supported value of {}.", initial_value, MAX_INITIAL_SEMAPHORE_VALUE);
        }

        let file_path =
            FilePath::from_path_and_file(&Path::new(b"/").unwrap(), &self.name).unwrap();
        Errno::reset();
        self.handle = match mode {
            InitMode::Create => unsafe {
                msg = "Unable to create semaphore";
                posix::sem_create(
                    file_path.as_c_str(),
                    posix::O_CREAT | posix::O_EXCL,
                    permission.as_mode(),
                    initial_value,
                )
            },
            InitMode::Open | InitMode::TryOpen => unsafe {
                msg = "Unable to open semaphore";
                posix::sem_open(file_path.as_c_str(), 0)
            },
        };

        if self.handle != posix::SEM_FAILED {
            match mode {
                InitMode::Create => debug!(from self, "semaphore created."),
                _ => debug!(from self, "semaphore opened."),
            }
            return Ok(());
        }

        let has_try_open_mode = mode == InitMode::TryOpen;
        handle_errno!(NamedSemaphoreCreationError, from self,
            success_when has_try_open_mode,
                Errno::ENOENT => ((), DoesNotExist, "{} since the semaphore does not exist." ,msg),
            Errno::EACCES => (InsufficientPermissions, "{} due to insufficient permissions.", msg),
            Errno::EEXIST => (AlreadyExists, "{} since the semaphore already exists.", msg),
            Errno::EINTR => (Interrupt, "{} since an interrupt signal was received.", msg),
            Errno::EINVAL => (NotSupportForGivenName, "{} since the operation is not supported for the given name.", msg),
            Errno::EMFILE => (PerProcessFileHandleLimitReached, "{} since the current process already holds the maximum amount of semaphore or file descriptos.", msg),
            Errno::ENAMETOOLONG => (MaxFilePathLengthExceeded, "{} since the name exceeds the maximum supported length.", msg),
            Errno::ENFILE => (SystemWideFileHandleLimitReached, "{} since the system-wide semaphore or file-handle limit is reached.", msg),
            Errno::ENOSPC => (NoSpaceLeft, "{} due to insufficient space on the target.", msg),
            v => (UnknownError(v as i32), "{} since an unknown error occurred ({}).", msg,v)
        );
    }

    /// Returns the name of the named semaphore
    pub fn name(&self) -> &FileName {
        &self.name
    }
}

impl internal::SemaphoreHandle for NamedSemaphore {
    fn handle(&self) -> *mut posix::sem_t {
        self.handle
    }

    fn get_clock_type(&self) -> ClockType {
        self.clock_type
    }
}

impl SemaphoreInterface for NamedSemaphore {}

/// Creates an [`UnnamedSemaphore`] which can be either used process locally or can be stored in a
/// shared memory segment and then used during inter-process communication.
///
/// # Example
///
/// ```
/// use iceoryx2_bb_posix::semaphore::*;
///
/// let semaphore_handle = UnnamedSemaphoreHandle::new();
/// let semaphore = UnnamedSemaphoreBuilder::new().initial_value(5)
///                                               .is_interprocess_capable(false)
///                                               .clock_type(ClockType::Monotonic)
///                                               .create(&semaphore_handle)
///                                               .expect("failed to create unnamed semaphore");
/// ```
#[derive(Debug)]
pub struct UnnamedSemaphoreBuilder {
    clock_type: ClockType,
    is_interprocess_capable: bool,
    initial_value: u32,
}

impl Default for UnnamedSemaphoreBuilder {
    fn default() -> Self {
        UnnamedSemaphoreBuilder {
            clock_type: ClockType::default(),
            is_interprocess_capable: true,
            initial_value: 0,
        }
    }
}

impl UnnamedSemaphoreBuilder {
    pub fn new() -> UnnamedSemaphoreBuilder {
        Self::default()
    }

    /// Sets the initial value of the semaphore. Must be less than [`MAX_INITIAL_SEMAPHORE_VALUE`].
    pub fn initial_value(mut self, value: u32) -> Self {
        self.initial_value = value;
        self
    }

    /// Defines if the [`UnnamedSemaphore`] can be used in an inter-process communication context.
    pub fn is_interprocess_capable(mut self, value: bool) -> Self {
        self.is_interprocess_capable = value;
        self
    }

    /// Sets the type of clock which will be used in [`SemaphoreInterface::timed_wait()`]. Be
    /// aware a clock like [`ClockType::Realtime`] is depending on the systems local time. If this
    /// time changes while waiting it can cause extrem long waits or no wait at all.
    pub fn clock_type(mut self, value: ClockType) -> Self {
        self.clock_type = value;
        self
    }

    /// Creates an [`UnnamedSemaphore`].
    pub fn create(
        self,
        handle: &UnnamedSemaphoreHandle,
    ) -> Result<UnnamedSemaphore, UnnamedSemaphoreCreationError> {
        let msg = "Unable to create semaphore";

        if handle
            .reference_counter
            .compare_exchange(
                IpcHandleState::Uninitialized as _,
                IpcHandleState::PerformingInitialization as _,
                Ordering::Relaxed,
                Ordering::Relaxed,
            )
            .is_err()
        {
            fail!(from self, with UnnamedSemaphoreCreationError::HandleAlreadyInitialized,
                "{} since the handle is already initialized with another semaphore.", msg);
        }

        handle
            .is_interprocess_capable
            .store(self.is_interprocess_capable, Ordering::Relaxed);

        unsafe { *handle.clock_type.get() = self.clock_type };

        if self.initial_value > MAX_INITIAL_SEMAPHORE_VALUE {
            handle.reference_counter.store(-1, Ordering::Relaxed);
            fail!(from self, with UnnamedSemaphoreCreationError::InitialValueTooLarge,
                "{} since the initial value {} is too large.", msg, self.initial_value);
        }

        if unsafe {
            posix::sem_init(
                handle.as_ptr(),
                if self.is_interprocess_capable { 1 } else { 0 },
                self.initial_value,
            )
        } != -1
        {
            handle
                .reference_counter
                .store(IpcHandleState::Initialized as _, Ordering::Release);
            return Ok(UnnamedSemaphore::new(handle));
        }

        handle_errno!(UnnamedSemaphoreCreationError, from self,
            Errno::EINVAL => (InitialValueTooLarge, "{} since the initial value {} is too large. Please verify posix configuration!", msg, self.initial_value),
            Errno::ENOSPC => (ExceedsMaximumNumberOfSemaphores, "{} since it exceeds the maximum amount of semaphores {}.", msg, Limit::MaxNumberOfSemaphores.value()),
            Errno::EPERM => (InsufficientPermissions, "{} due to insufficient permissions.", msg),
            v => (UnknownError(v as i32), "{} since an unknown error occurred ({}).", msg, v)
        );
    }
}

#[derive(Debug)]
pub struct UnnamedSemaphoreHandle {
    handle: UnsafeCell<posix::sem_t>,
    clock_type: UnsafeCell<ClockType>,
    is_interprocess_capable: AtomicBool,
    reference_counter: AtomicI64,
}

unsafe impl Send for UnnamedSemaphoreHandle {}
unsafe impl Sync for UnnamedSemaphoreHandle {}

impl crate::unmovable_ipc_handle::internal::UnmovableIpcHandle for UnnamedSemaphoreHandle {
    fn reference_counter(&self) -> &AtomicI64 {
        &self.reference_counter
    }

    fn is_interprocess_capable(&self) -> bool {
        self.is_interprocess_capable.load(Ordering::Relaxed)
    }
}

impl Default for UnnamedSemaphoreHandle {
    fn default() -> Self {
        Self {
            handle: UnsafeCell::new(posix::sem_t::new()),
            clock_type: UnsafeCell::new(ClockType::default()),
            is_interprocess_capable: AtomicBool::new(false),
            reference_counter: AtomicI64::new(IpcHandleState::Uninitialized as _),
        }
    }
}

impl UnnamedSemaphoreHandle {
    pub fn new() -> Self {
        Self::default()
    }

    fn as_ptr(&self) -> *mut posix::sem_t {
        self.handle.get()
    }
}

/// An unnamed semaphore which can be used process locally or for inter-process triggers.
///
/// # Example
///
/// ```no_run
/// use iceoryx2_bb_posix::semaphore::*;
/// use std::thread;
/// use iceoryx2_bb_posix::clock::*;
/// use std::time::Duration;
///
/// let semaphore_handle = UnnamedSemaphoreHandle::new();
/// let semaphore = UnnamedSemaphoreBuilder::new().create(&semaphore_handle)
///     .expect("failed to create semaphore");
///
/// thread::scope(|s| {
///     s.spawn(|| {
///         loop {
///             semaphore.wait().expect("failed to wait on semaphore");
///             println!("the thread was triggered");
///         }
///     });
///
///     loop {
///         nanosleep(Duration::from_secs(1));
///         println!("trigger thread");
///         semaphore.post().expect("failed to trigger semaphore");
///     }
/// });
/// ```
#[derive(Debug)]
pub struct UnnamedSemaphore<'a> {
    handle: &'a UnnamedSemaphoreHandle,
}

unsafe impl Send for UnnamedSemaphore<'_> {}
unsafe impl Sync for UnnamedSemaphore<'_> {}

impl Drop for UnnamedSemaphore<'_> {
    fn drop(&mut self) {
        if self.handle.reference_counter.fetch_sub(1, Ordering::AcqRel) == 1 {
            if unsafe { posix::sem_destroy(self.handle.as_ptr()) } != 0 {
                fatal_panic!(from self, "This should never happen! Unable to destroy semaphore since the file-descriptor was invalid.");
            }

            self.handle.reference_counter.store(-1, Ordering::Release);
        }
    }
}

impl<'a> CreateIpcConstruct<'a, UnnamedSemaphoreHandle> for UnnamedSemaphore<'a> {
    fn new(handle: &'a UnnamedSemaphoreHandle) -> Self {
        Self { handle }
    }
}

impl<'a> IpcCapable<'a, UnnamedSemaphoreHandle> for UnnamedSemaphore<'a> {}

impl<'a> UnnamedSemaphore<'a> {
    /// Returns true if the semaphore is interprocess capable, otherwise false
    pub fn is_interprocess_capable(&self) -> bool {
        self.handle.is_interprocess_capable.load(Ordering::Relaxed)
    }
}

impl internal::SemaphoreHandle for UnnamedSemaphore<'_> {
    fn handle(&self) -> *mut posix::sem_t {
        self.handle.as_ptr()
    }

    fn get_clock_type(&self) -> ClockType {
        unsafe { *self.handle.clock_type.get() }
    }
}

impl SemaphoreInterface for UnnamedSemaphore<'_> {}