mojo
mojo copied to clipboard
[BUG] Store on bitcasted unsafe pointer not working as expected
Bug description
What I'm trying to achieve is to force it to interpret the buffer of uint8 as uint64 to only use 1 xor operation for 8+ values at once
This should xor each value with 0x30 and get the num value out of the string but the pointer doesn't edit the values
fn atol_utf8[min_str_len: Int](owned str_ref: StringRef) -> UInt64:
"""Parses the given utf-8 string assuming the string is clean and contains
only number characters: [0, 9].
For example, `atol_utf8[2]("19")` returns `19`. If the given string cannot be parsed
as an integer value, garbage is returned e.g. `atol_utf8[2](" 19")` returns `1619`
`atol_utf8[2]("-19")` returns `2919`.
Parameters:
min_str_len: The minimum length that the string must have.
Args:
str_ref: A utf-8 string to be parsed as an integer.
Returns:
An integer value that represents the string.
"""
var ptr = str_ref.unsafe_ptr().bitcast[DType.uint64]()
var str_len = len(str_ref)
alias factor = 8
alias amnt_full = min_str_len // factor
for i in range(amnt_full):
# this should edit the buffer but it doesn't
ptr[i] ^= 0x3030303030303030
var ptr_8 = ptr.bitcast[DType.uint8]()
var int_res = UInt64(0)
for i in range(str_len):
# manually doing xor for each works
# print(value ^ 0x30)
var value = ptr_8[i].cast[DType.uint64]()
if i >= amnt_full * factor:
value ^= 0x30
int_res = int_res * 10 + value
return int_res
fn main():
var result = atol_utf8[9]("123456789")
print(result) # should print `123456789` but prints `5456790069` which xored to 0x30 is `123456789`
Steps to reproduce
- Include relevant code snippet or link to code that did not work as expected.
- If applicable, add screenshots to help explain the problem.
- If using the Playground, name the pre-existing notebook that failed and the steps that led to failure.
- Include anything else that might help us debug the issue.
System information
- What OS did you do install Mojo on ?
Ubuntu 22
- Provide version information for Mojo by pasting the output of `mojo -v`
mojo 2024.5.1619
- Provide Modular CLI version by pasting the output of `modular -v`