From b8b2793d2bfd7857db9ea6d3c03c03a637c9faa5 Mon Sep 17 00:00:00 2001 From: Avril Date: Wed, 10 Jun 2020 17:28:11 +0100 Subject: [PATCH] added initialise() --- src/init.rs | 95 +++++++++++++++++++++++++++++++++++++++++++++++++++++ src/iter.rs | 6 ++++ src/lib.rs | 22 +++++++++++++ 3 files changed, 123 insertions(+) create mode 100644 src/init.rs diff --git a/src/init.rs b/src/init.rs new file mode 100644 index 0000000..924f973 --- /dev/null +++ b/src/init.rs @@ -0,0 +1,95 @@ +use super::*; +use std::{ + marker::PhantomData, +}; + +pub struct InitIter<'a, T> +{ + from: &'a mut HeapArray, + current_idex: usize, +} + +pub struct Init<'a, T> +{ + ptr: *mut T, + init_ok: bool, + _marker: PhantomData<&'a T>, +} + +impl<'a, T> InitIter<'a, T> +{ + pub(crate) fn new(from: &'a mut HeapArray, current_idex: usize) -> InitIter<'a, T> + { + InitIter { + from, + current_idex, + } + } +} + +impl<'a, T> Iterator for InitIter<'a, T> +{ + type Item = Init<'a, T>; + + fn next(&mut self) -> Option + { + if self.current_idex >= self.from.len() { + None + } else { + self.current_idex+=1; + unsafe { + Some(Init{ + ptr: self.from.as_mut_ptr().offset((self.current_idex as isize)-1), + init_ok: false, + _marker: PhantomData, + }) + } + } + } +} + +impl<'a, T> Init<'a, T> +{ + pub fn is_init(&self) -> bool + { + self.init_ok + } + pub unsafe fn assume_init(&mut self) + { + self.init_ok = true; + } + pub fn put(&mut self, value: T) -> &mut T + { + if self.init_ok { + unsafe { + *self.ptr = value; + return &mut (*self.ptr); + } + } + self.init_ok = true; + unsafe { + ptr::put(self.ptr, value); + &mut (*self.ptr) + } + } + pub fn get(&self) -> Option<&T> + { + unsafe { + if self.init_ok { + Some(& (*self.ptr)) + } else { + None + } + } + } + pub fn get_mut(&mut self) -> Option<&mut T> + { + unsafe { + if self.init_ok { + Some(&mut (*self.ptr)) + } else { + None + } + } + } +} diff --git a/src/iter.rs b/src/iter.rs index 5991f5b..ab830ca 100644 --- a/src/iter.rs +++ b/src/iter.rs @@ -4,6 +4,9 @@ use std::{ mem::{ forget, }, + marker::{ + Send,Sync, + }, }; use ptr::{ VoidPointer, @@ -16,6 +19,9 @@ pub struct IntoIter sz: usize, } +unsafe impl Send for IntoIter{} +unsafe impl Sync for IntoIter{} + impl IntoIter { fn current(&mut self) -> *mut T diff --git a/src/lib.rs b/src/lib.rs index 3a646bb..3cd99be 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -108,11 +108,27 @@ mod tests { let vector = Vec::from(slice); assert_eq!(&vector[..], &array[..]); } + + #[test] + fn init() + { + let mut array = heap![String; 32]; + for mut string in array.initialise() + { + string.put("Hiya".to_owned()); + } + + for x in array.into_iter() + { + assert_eq!(x, "Hiya"); + } + } } mod ptr; mod alloc; mod reinterpret; +pub mod init; use std::{ ops::{ @@ -254,6 +270,12 @@ impl HeapArray std::mem::size_of::() == 1 } + + pub fn initialise<'a>(&'a mut self) -> init::InitIter<'a, T> + { + init::InitIter::new(self, 0) + } + /// Set each byte to a value. pub unsafe fn set_memory(&mut self, value: u8) {