~sircmpwn/hare-users

1

Possible Bug found using strings

Details
Message ID
<660173626.132413.1656390144589@privateemail.com>
DKIM signature
pass
Download raw message
Hello,

I have encountered an issue using strings.  The code to reproduce this
issue as well as a sample output is located in this repo:
https://codeberg.org/Atlas/hare-string-error

The code has a function named readFile that reads a file into a buffer
using the io::drain function. Then it uses strings::fromutf8 to get a
string from the buffer and prints the resulting string with
fmt::println.  This works as expected.  The issue occurs after this
function returns the string.  The returned value is assigned to a
string variable and that is also printed with fmt::println.  This call
to fmt::println results in some sort of mangled output at the
beginning of the string (see output.txt in the above mentioned repo).

My apologies if I am overlooking something obvious.  If this is
already a known bug then please disregard.

Thanks,
Atlas N.
Details
Message ID
<CL1HIJLJ6YCO.FNSDLFWDQ6WW@archlinux-x220>
In-Reply-To
<660173626.132413.1656390144589@privateemail.com> (view parent)
DKIM signature
pass
Download raw message
The clue to your problem can be found in the documentation for
strings::fromutf8 (emphasis mine):

> // Converts a byte slice into a string, aborting the program if the bytes
> // contain invalid UTF-8. **The return value is borrowed from the input.** To handle
> // errors without aborting, see [[try_fromutf8]] or [[encoding::utf8]].
> fn fromutf8(in: []u8) str;

This can be fixed by two ways. 1) Poorly, by simply removing the `defer
free(buffer)` line, or 2) duplicating the string and then freeing it:

	use fmt;
	use io;
	use strings;
	use os;
	use fs;
	
	export fn main() void = {
	        let body: str = genRes();
		free(body);
	};
	
	fn genRes() str = {
	        let body: str = readFile();
	        fmt::println(body)!; // This is the second print
	        return body;
	};
	
	fn readFile() str = {
	        let file = os::open(os::args[1])!;
	        defer io::close(file)!;
	        let buffer: []u8 = io::drain(file)!;
	        defer free(buffer);
	        let page: str = strings::dup(strings::fromutf8(buffer));
	        fmt::println(page)!; // This is the first print
	        return page;
	};

This section of the introductory tutorial may help you grok the concept
better:

https://harelang.org/tutorials/introduction/#thinking-in-terms-of-ownership

-- 
Sebastian LaVine | https://smlavine.com
Reply to thread Export thread (mbox)