-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
4 changed files
with
29 additions
and
32 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
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,28 +1,23 @@ | ||
from memory import memset_zero | ||
|
||
|
||
struct UnsafeBuffer: | ||
var data: UnsafePointer[UInt8] | ||
var size: Int | ||
|
||
fn __init__(inout self, size: Int): | ||
self.data = UnsafePointer[UInt8].alloc(size) | ||
memset_zero(self.data, size) | ||
self.size = size | ||
|
||
fn write(inout self, index: Int, value: UInt8): | ||
# note `self.data` is uninitialized so we have to use `init_pointee_copy/move` | ||
# methods to safely initialize the allocated memory | ||
self.data.init_pointee_copy(value) | ||
|
||
fn read(self, index: Int) -> UInt8: | ||
return self.data[index] | ||
|
||
fn __del__(owned self): | ||
self.data.free() | ||
|
||
|
||
def main(): | ||
ub = UnsafeBuffer(10) | ||
ub.write(0, 255) | ||
ub.write(1, 128) | ||
print("unsafe buffer outputs:") | ||
print(ub.read(0)) | ||
print("the data of the unsafe buffer is freed here bc there's no lifetime associate with it") | ||
print(ub.read(1)) | ||
print("initial value at index 0:") | ||
print(ub.data[0]) | ||
ub.data[0] = 255 | ||
print("value at index 0 after getting set to 255:") | ||
print(ub.data[0]) |