forked from eclipse-iceoryx/iceoryx2
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[eclipse-iceoryx#224] Implement placement new for unions and unnamed …
…structs
- Loading branch information
Showing
2 changed files
with
69 additions
and
8 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,23 +1,62 @@ | ||
#[cfg(test)] | ||
mod placement_new { | ||
use std::alloc::{alloc, dealloc, Layout}; | ||
use std::{ | ||
alloc::{alloc, dealloc, Layout}, | ||
sync::atomic::{AtomicUsize, Ordering}, | ||
}; | ||
|
||
use iceoryx2_bb_derive_macros::PlacementDefault; | ||
use iceoryx2_bb_elementary::placement_new::PlacementDefault; | ||
use iceoryx2_bb_testing::assert_that; | ||
|
||
#[derive(Default, PlacementDefault)] | ||
static DEFAULT_CTOR_COUNT: AtomicUsize = AtomicUsize::new(0); | ||
|
||
#[derive(Copy, Clone)] | ||
struct UnitStruct; | ||
|
||
impl PlacementDefault for UnitStruct { | ||
unsafe fn placement_default(_ptr: *mut Self) { | ||
DEFAULT_CTOR_COUNT.fetch_add(1, Ordering::Relaxed); | ||
} | ||
} | ||
|
||
struct Fuu(i32); | ||
|
||
impl PlacementDefault for Fuu { | ||
unsafe fn placement_default(ptr: *mut Self) { | ||
DEFAULT_CTOR_COUNT.fetch_add(1, Ordering::Relaxed); | ||
ptr.write(Self(0)) | ||
} | ||
} | ||
|
||
struct Bar { | ||
value: u64, | ||
} | ||
|
||
impl PlacementDefault for Bar { | ||
unsafe fn placement_default(ptr: *mut Self) { | ||
DEFAULT_CTOR_COUNT.fetch_add(1, Ordering::Relaxed); | ||
ptr.write(Self { value: 123 }) | ||
} | ||
} | ||
|
||
#[derive(PlacementDefault)] | ||
struct TestStruct { | ||
a: i32, | ||
b: u64, | ||
value1: UnitStruct, | ||
value2: Fuu, | ||
value3: Bar, | ||
} | ||
|
||
#[test] | ||
fn whatever() { | ||
fn placement_default_works() { | ||
DEFAULT_CTOR_COUNT.store(0, Ordering::Relaxed); | ||
|
||
let layout = Layout::new::<TestStruct>(); | ||
let memory = unsafe { alloc(layout) } as *mut TestStruct; | ||
let sut = TestStruct::default(); | ||
unsafe { TestStruct::placement_default(memory) }; | ||
|
||
assert_that!(DEFAULT_CTOR_COUNT.load(Ordering::Relaxed), eq 3); | ||
|
||
unsafe { dealloc(memory.cast(), layout) }; | ||
} | ||
} |