033 Rust死灵书之重构Vec
介绍
本系列录制的视频主要放在B站上Rust死灵书学习视频
Rust 死灵书相关的源码资料在https://github.com/anonymousGiga/Rustonomicon-Source
详细内容
在本节中,抽取出来一个RawVec对之前的代码进行重构,如下(重建一个工程):
#![feature(ptr_internals)]
use std::mem;
use std::alloc::{alloc, realloc, dealloc, Layout, handle_alloc_error};
use std::ptr::{Unique, self};
use std::ops::{Deref, DerefMut};
use std::slice;#[derive(Debug)]
struct RawVec<T> {ptr: Unique<T>,cap: usize,
}impl<T> RawVec<T> {fn new() -> Self {assert!(mem::size_of::<T>() != 0, "还没准备好处理零尺寸类型");RawVec { ptr: Unique::dangling(), cap: 0 }}fn grow(&mut self) {unsafe {let align = mem::align_of::<T>();let elem_size = mem::size_of::<T>();let layout: Layout;let (new_cap, ptr) = if self.cap == 0 {layout = Layout::from_size_align_unchecked(elem_size, align);let ptr = alloc(layout);(1, ptr)} else {let new_cap = self.cap * 2;let old_num_bytes = self.cap * elem_size;assert!(old_num_bytes <= (isize::MAX as usize) / 2,"capacity overflow");let new_num_bytes = old_num_bytes * 2;layout = Layout::from_size_align_unchecked(new_num_bytes, align);let ptr = realloc(self.ptr.as_ptr() as *mut _,layout,new_num_bytes);(new_cap, ptr)};if ptr.is_null() { handle_alloc_error(layout); }if let Some(ptr) = Unique::new(ptr as *mut _) {self.ptr = ptr;} else {panic!("error!");}self.cap = new_cap;}}
}impl<T> Drop for RawVec<T> {fn drop(&mut self) {if self.cap != 0 {let align = mem::align_of::<T>();let elem_size = mem::size_of::<T>();let num_bytes = elem_size * self.cap;unsafe {let layout: Layout = Layout::from_size_align_unchecked(num_bytes, align);dealloc(self.ptr.as_ptr() as *mut _, layout)}println!("release memory in drop function!");}}
}struct IntoIter<T> {_buf: RawVec<T>, start: *const T,end: *const T,
}impl<T> Drop for IntoIter<T> {fn drop(&mut self) {for _ in &mut *self {}}
}#[derive(Debug)]
pub struct MyVec<T> {buf: RawVec<T>,len: usize,
}impl<T> MyVec<T> {fn ptr(&self) -> *mut T { self.buf.ptr.as_ptr() }fn cap(&self) -> usize { self.buf.cap }pub fn new() -> Self {MyVec { buf: RawVec::new(), len: 0 }}fn push(&mut self, elem: T) {if self.len == self.cap() { self.buf.grow(); }//关键点在于要直接覆盖,因为不知道内存之前是否有东西unsafe {ptr::write(self.ptr().offset(self.len as isize), elem);}self.len += 1;}fn pop(&mut self) -> Option<T> {if self.len == 0 {None} else {self.len -= 1;unsafe {Some(ptr::read(self.ptr().offset(self.len as isize))}}}fn insert(&mut self, index: usize, elem: T) {assert!(index <= self.len, "越界");if self.cap() == self.len { self.buf.grow(); }unsafe {if index < self.len {ptr::copy(self.ptr().offset(index as isize),self.ptr().offset((index as isize) + 1),self.len - index);}ptr::write(self.ptr().offset(index as isize), elem);self.len += 1;}}fn remove(&mut self, index: usize) -> T {assert!(index < self.len, "越界");unsafe {self.len -= 1;let result = ptr::read(self.ptr().offset(index as isize));ptr::copy(self.ptr().offset(index as isize + 1), self.ptr().offset(index as isize),self.len - index);result}}fn into_iter(self) -> IntoIter<T> {unsafe {let buf = ptr::read(&self.buf);let len = self.len;mem::forget(self);IntoIter {start: buf.ptr.as_ptr(),end: buf.ptr.as_ptr().offset(len as isize),_buf: buf,}}}
}impl<T> Drop for MyVec<T> {fn drop(&mut self) {while let Some(_) = self.pop() {}}
}impl<T> Deref for MyVec<T> {type Target = [T];fn deref(&self) -> &[T] {unsafe {slice::from_raw_parts(self.buf.ptr.as_ptr(), self.len)}}
}impl<T> DerefMut for MyVec<T> {fn deref_mut(&mut self) -> &mut [T] {unsafe {slice::from_raw_parts_mut(self.buf.ptr.as_ptr(), self.len)}}
}//为IntoIter实现迭代器
impl<T> Iterator for IntoIter<T> {type Item = T;fn next(&mut self) -> Option<T> {if self.start == self.end {None} else {unsafe {let result = ptr::read(self.start);self.start = self.start.offset(1);Some(result)}}}fn size_hint(&self) -> (usize, Option<usize>) {let len = (self.end as usize - self.start as usize) / mem::size_of::<T>();(len, Some(len))}
}impl<T> DoubleEndedIterator for IntoIter<T> {fn next_back(&mut self) -> Option<T> {if self.start == self.end {None} else {unsafe {self.end = self.end.offset(-1);Some(ptr::read(self.end))}}}
}fn main() {{let mut vec: MyVec<i32> = MyVec::new();vec.push(8);vec.push(7);vec.push(6);while let Some(v) = vec.pop() {println!("v == {}", v);}vec.push(8);vec.push(7);vec.push(6);let s = &vec[1..];println!("s[0] == {}", s[0]);let s = &mut vec[1..];s[0] = 10;println!("s[0] == {}", s[0]);println!("-------------------------------");let mut vec2: MyVec<i32> = MyVec::new();vec2.push(1);vec2.push(2);vec2.push(3);//打印//while let Some(v) = vec2.pop() {// println!("v == {}", v);//}vec2.insert(1, 11);let ret = vec2.remove(2);println!("remove elem: {}", ret);//打印while let Some(v) = vec2.pop() {println!("v == {}", v);}println!("-------------------------------");let mut vec3: MyVec<i32> = MyVec::new();vec3.push(1);vec3.push(2);vec3.push(3);vec3.push(4);let iter = vec3.iter();for val in iter {println!("Got: {}", val);}println!("-------------------------------");let iter3: IntoIter<i32> = vec3.into_iter();for mut val in iter3 {println!("Got: {}", val);val = 111;println!("Got: {}", val);}println!("-------------------------------");let mut vec4: MyVec<i32> = MyVec::new();vec4.push(1);vec4.push(2);let mut iter4: IntoIter<i32> = vec4.into_iter();while let Some(val) = iter4.next_back() {println!("Got: {}", val);}}println!("Hello, world!");
}
033 Rust死灵书之重构Vec相关推荐
- 026 Rust死灵书之实现Vec
介绍 本系列录制的视频主要放在B站上Rust死灵书学习视频 Rust 死灵书相关的源码资料在https://github.com/anonymousGiga/Rustonomicon-Source 从 ...
- 030 Rust死灵书之让Vec支持slice
介绍 本系列录制的视频主要放在B站上Rust死灵书学习视频 Rust 死灵书相关的源码资料在https://github.com/anonymousGiga/Rustonomicon-Source 详 ...
- 027 Rust死灵书之Vec内存分配
介绍 本系列录制的视频主要放在B站上Rust死灵书学习视频 Rust 死灵书相关的源码资料在https://github.com/anonymousGiga/Rustonomicon-Source V ...
- 035 Rust死灵书之Vec处理零尺寸类型
介绍 本系列录制的视频主要放在B站上Rust死灵书学习视频 Rust 死灵书相关的源码资料在https://github.com/anonymousGiga/Rustonomicon-Source 详 ...
- 032 Rust死灵书之Vec的IntoIter
介绍 本系列录制的视频主要放在B站上Rust死灵书学习视频 Rust 死灵书相关的源码资料在https://github.com/anonymousGiga/Rustonomicon-Source 详 ...
- 029 Rust死灵书之Vec实现Drop
介绍 本系列录制的视频主要放在B站上Rust死灵书学习视频 Rust 死灵书相关的源码资料在https://github.com/anonymousGiga/Rustonomicon-Source 详 ...
- 036 Rust死灵书之Vec的完整代码测试
介绍 本系列录制的视频主要放在B站上Rust死灵书学习视频 Rust 死灵书相关的源码资料在https://github.com/anonymousGiga/Rustonomicon-Source 详 ...
- 028 Rust死灵书之Vec的push和pop
介绍 本系列录制的视频主要放在B站上Rust死灵书学习视频 Rust 死灵书相关的源码资料在https://github.com/anonymousGiga/Rustonomicon-Source V ...
- 031 Rust死灵书之Vec实现insert和remove
介绍 本系列录制的视频主要放在B站上Rust死灵书学习视频 Rust 死灵书相关的源码资料在https://github.com/anonymousGiga/Rustonomicon-Source 详 ...
最新文章
- python excle写数据
- hdu1999 不可摸数 好题.
- MySQL规格列表(硬件优化上限)
- Java开发必须掌握的 20+ 种 Spring 常用注解
- javascript笔记:javascript的前世,至于今生嘛地球人都知道了哈
- C 实现 删除字符串空白符的函数 strtrim
- SpringMVC自学日志04(Controller 及 RestFul风格 )
- 单片机工作笔记002---认识CPU的结构_哈佛结构和冯·诺依曼结构的区别
- HDU1236 排名【排序】
- 前端开发利器 - WebStorm
- mysql 密码保存格式_mysql5.6使用老格式密码
- ajax的param方法,jQuery ajax - param() 方法
- ​以太网的发展历史、演化过程以及工作基理
- 物联网平台Thingsboard接入PM2.5数据实战
- 内存的读写速度是硬盘的多少倍
- 1016: 委派任务*
- 主引导记录(MBR)分析
- Sicily 1140. 国王的遗产
- CloseableHttpClient方式配置代理服务器访问外网
- 【文学文娱】《人类简史》--从动物到上帝
热门文章
- 伪造邮件钓鱼,要知道的秘密!
- mysql数据库5.7版本二进制安装与破解mysql数据库密码
- 荣耀手环四有计算机功能吗,荣耀手环4有什么特点 如何使用荣耀手环4
- 战网服务器修改,怎么修改战网客户端?修改战网客户端的方法
- 数据挖掘相关岗位分析及规划
- JQ+ ES6模板字符串 + $.each(数组, function(index, 数组中的对象) {操作程序} 循环遍历添加新html结构标签
- 【查看】 - 内网(局域网)ip 、公网(外网)ip - ipconfig 、 tracert
- [SWPU2019]Web1 1
- 赛道持续降温!又一家自动驾驶公司裁员,市值曾超50亿美元
- 【python】小技巧-判断一个字典中是否包含另一个字典的值,即实际结果中是否包含预期结果