1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

builtin, checker, cgen: implement x = a[k] or { ... } for maps and arrays (#8193)

This commit is contained in:
Uwe Krüger
2021-01-19 06:06:57 +01:00
committed by GitHub
parent a65b73d3e4
commit b74690cbec
5 changed files with 152 additions and 31 deletions

View File

@ -229,6 +229,16 @@ fn (a array) get(i int) voidptr {
}
}
// Private function. Used to implement x = a[i] or { ... }
fn (a array) get_with_check(i int) voidptr {
if i < 0 || i >= a.len {
return 0
}
unsafe {
return byteptr(a.data) + i * a.element_size
}
}
// first returns the first element of the array.
pub fn (a array) first() voidptr {
$if !no_bounds_checking ? {

View File

@ -552,6 +552,29 @@ fn (m &map) get_1(key voidptr, zero voidptr) voidptr {
return zero
}
// If `key` matches the key of an element in the container,
// the method returns a reference to its mapped value.
// If not, a zero pointer is returned.
// This is used in `x := m['key'] or { ... }`
fn (m &map) get_1_check(key voidptr) voidptr {
mut index, mut meta := m.key_to_index(key)
for {
if meta == unsafe { m.metas[index] } {
kv_index := int(unsafe { m.metas[index + 1] })
pkey := unsafe { m.key_values.key(kv_index) }
if m.key_eq_fn(key, pkey) {
return unsafe { byteptr(pkey) + m.key_values.key_bytes }
}
}
index += 2
meta += probe_inc
if meta > unsafe { m.metas[index] } {
break
}
}
return 0
}
// Checks whether a particular key exists in the map.
fn (m &map) exists_1(key voidptr) bool {
mut index, mut meta := m.key_to_index(key)