cli: add bounded std copy/search and checked arithmetic
This commit is contained in:
36 files changed
+1533
-7
No files matched your search
@@ -0,0 +1,39 @@
|
||||
// expect: run
|
||||
// result: 10
|
||||
// phase: 6
|
||||
// spec: docs/spec/16-standard-library.md §2.1.1, §2.4
|
||||
module demo.bounded
|
||||
import std.bytes;
|
||||
import std.math;
|
||||
|
||||
fn encode(dst: slice_mut<u8>, data: slice<u8>) -> usize
|
||||
effects []
|
||||
{
|
||||
match std.math.checked_add_usize(data.len, 1) {
|
||||
std.math.UsizeResult::ok(total) => {
|
||||
if total > dst.len { return 0; }
|
||||
match std.bytes.copy(mut dst, ref data) {
|
||||
std.bytes.WriteResult::ok => { dst[data.len] = 0; return total; }
|
||||
std.bytes.WriteResult::short_output => { return 0; }
|
||||
}
|
||||
}
|
||||
std.math.UsizeResult::overflow => { return 0; }
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> usize
|
||||
effects []
|
||||
{
|
||||
var buf: [u8; 16] = [165; 16];
|
||||
let size = encode(mut buf, b"key=value");
|
||||
assert(size == 10);
|
||||
assert(buf[9] == 0 and buf[10] == 165);
|
||||
match std.bytes.find_slice(ref buf[0..size - 1], b"=") {
|
||||
std.bytes.FindResult::found(index) => {
|
||||
assert(std.bytes.equal(ref buf[0..index], b"key"));
|
||||
assert(std.bytes.equal(ref buf[index + 1..size - 1], b"value"));
|
||||
}
|
||||
std.bytes.FindResult::not_found => { trap; }
|
||||
}
|
||||
return size;
|
||||
}
|
||||
Reference in new issue
Block a user