modularml / mojo

The Mojo Programming Language
https://docs.modular.com/mojo/manual/
Other
22.71k stars 2.57k forks source link

[BUG]: String splicing introduces null characters! #1760

Open HelloWorld-n opened 6 months ago

HelloWorld-n commented 6 months ago

Bug description

Code

print("...." + str("abcdef")[0:16] + "....")

in python gives

....abcdef....

giving entire text but in mojo it gives

....abcdef

having .... at start of text but lacking the .... at end of text.

Steps to reproduce

Save

fn main() raises:
    print("...." + str("abcdef")[0:16] + "....")

to file test.mojo then run that file!

System information

- Ubuntu 22.04.3 LTS on Windows 11 x86_64
- mojo 0.7.0 (af002202)
- modular 0.4.1 (2d8afe15)
gabrieldemarmiesse commented 6 months ago

I think the more general issue is that strings have no "bounds checks" and do not support negative integers or limits at 0 or len(my_str). It's just was bytes in memory when using indexing with []. eg

a = str("dodo")
a[-1] # error, wrong memory address
a[5] # error, wrong memory address
a[0:10] # error, wrong memory address
bgreni commented 2 months ago

With the recent fix Slice it appears this behaviour has been fixed

Tested with mojo 2024.6.1305 (ec42f7b2)