🚀feat: add rust codes for array_deque (#418)

* update zig codes style

* feat: add rust codes for array_deque

* Update array_deque.rs

---------

Co-authored-by: Yudong Jin <krahets@163.com>
This commit is contained in:
sjinzh
2023-03-14 20:45:27 +08:00
committed by GitHub
parent 567497a6b8
commit c2be6ebfbe
7 changed files with 235 additions and 73 deletions

View File

@@ -11,9 +11,9 @@ pub fn MyList(comptime T: type) type {
const Self = @This();
nums: []T = undefined, // 数组(存储列表元素)
numsCapacity: usize = 10, // 列表容量
numSize: usize = 0, // 列表长度(即当前元素数量)
extendRatio: usize = 2, // 每次列表扩容的倍数
nums_capacity: usize = 10, // 列表容量
num_size: usize = 0, // 列表长度(即当前元素数量)
extend_ratio: usize = 2, // 每次列表扩容的倍数
mem_arena: ?std.heap.ArenaAllocator = null,
mem_allocator: std.mem.Allocator = undefined, // 内存分配器
@@ -23,7 +23,7 @@ pub fn MyList(comptime T: type) type {
self.mem_arena = std.heap.ArenaAllocator.init(allocator);
self.mem_allocator = self.mem_arena.?.allocator();
}
self.nums = try self.mem_allocator.alloc(T, self.numsCapacity);
self.nums = try self.mem_allocator.alloc(T, self.nums_capacity);
std.mem.set(T, self.nums, @as(T, 0));
}
@@ -35,12 +35,12 @@ pub fn MyList(comptime T: type) type {
// 获取列表长度(即当前元素数量)
pub fn size(self: *Self) usize {
return self.numSize;
return self.num_size;
}
// 获取列表容量
pub fn capacity(self: *Self) usize {
return self.numsCapacity;
return self.nums_capacity;
}
// 访问元素
@@ -63,7 +63,7 @@ pub fn MyList(comptime T: type) type {
if (self.size() == self.capacity()) try self.extendCapacity();
self.nums[self.size()] = num;
// 更新元素数量
self.numSize += 1;
self.num_size += 1;
}
// 中间插入元素
@@ -78,7 +78,7 @@ pub fn MyList(comptime T: type) type {
}
self.nums[index] = num;
// 更新元素数量
self.numSize += 1;
self.num_size += 1;
}
// 删除元素
@@ -91,22 +91,22 @@ pub fn MyList(comptime T: type) type {
self.nums[j] = self.nums[j + 1];
}
// 更新元素数量
self.numSize -= 1;
self.num_size -= 1;
// 返回被删除元素
return num;
}
// 列表扩容
pub fn extendCapacity(self: *Self) !void {
// 新建一个长度为 size * extendRatio 的数组,并将原数组拷贝到新数组
var newCapacity = self.capacity() * self.extendRatio;
// 新建一个长度为 size * extend_ratio 的数组,并将原数组拷贝到新数组
var newCapacity = self.capacity() * self.extend_ratio;
var extend = try self.mem_allocator.alloc(T, newCapacity);
std.mem.set(T, extend, @as(T, 0));
// 将原数组中的所有元素复制到新数组
std.mem.copy(T, extend, self.nums);
self.nums = extend;
// 更新列表容量
self.numsCapacity = newCapacity;
self.nums_capacity = newCapacity;
}
// 将列表转换为数组