added initialise()

master
Avril 5 years ago
parent 9bd5698b9d
commit b8b2793d2b
Signed by: flanchan
GPG Key ID: 284488987C31F630

@ -0,0 +1,95 @@
use super::*;
use std::{
marker::PhantomData,
};
pub struct InitIter<'a, T>
{
from: &'a mut HeapArray<T>,
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<T>, 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<Self::Item>
{
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
}
}
}
}

@ -4,6 +4,9 @@ use std::{
mem::{ mem::{
forget, forget,
}, },
marker::{
Send,Sync,
},
}; };
use ptr::{ use ptr::{
VoidPointer, VoidPointer,
@ -16,6 +19,9 @@ pub struct IntoIter<T>
sz: usize, sz: usize,
} }
unsafe impl<T: Send> Send for IntoIter<T>{}
unsafe impl<T: Sync> Sync for IntoIter<T>{}
impl<T> IntoIter<T> impl<T> IntoIter<T>
{ {
fn current(&mut self) -> *mut T fn current(&mut self) -> *mut T

@ -108,11 +108,27 @@ mod tests {
let vector = Vec::from(slice); let vector = Vec::from(slice);
assert_eq!(&vector[..], &array[..]); 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 ptr;
mod alloc; mod alloc;
mod reinterpret; mod reinterpret;
pub mod init;
use std::{ use std::{
ops::{ ops::{
@ -254,6 +270,12 @@ impl<T> HeapArray<T>
std::mem::size_of::<T>() == 1 std::mem::size_of::<T>() == 1
} }
pub fn initialise<'a>(&'a mut self) -> init::InitIter<'a, T>
{
init::InitIter::new(self, 0)
}
/// Set each byte to a value. /// Set each byte to a value.
pub unsafe fn set_memory(&mut self, value: u8) pub unsafe fn set_memory(&mut self, value: u8)
{ {

Loading…
Cancel
Save