Fix adding to string that was allocated earlier

This commit is contained in:
Sofia 2025-07-23 21:27:45 +03:00
parent 0d3abe8e42
commit d96fc51b9c
2 changed files with 14 additions and 15 deletions

View File

@ -1,13 +1,13 @@
// Arithmetic, function calls and imports! // Arithmetic, function calls and imports!
import std::print; import std::print;
import std::new_string; import std::from_str;
import std::add_num_to_str; import std::add_num_to_str;
import std::free_string; import std::free_string;
fn main() -> u32 { fn main() -> u32 {
for i in 0 .. 15 { for i in 0 .. 15 {
let mut text = new_string(); let mut text = from_str("num: ");
add_num_to_str(&mut text, i); add_num_to_str(&mut text, i);
print(&text); print(&text);
free_string(&mut text); free_string(&mut text);

View File

@ -38,12 +38,12 @@ pub fn new_string() -> String {
} }
pub fn from_str(str: *char) -> String { pub fn from_str(str: *char) -> String {
let length = str_length(str, 0); let length = str_length(str);
let cloned = malloc(length as u64) as *char; let cloned = malloc(length as u64) as *char;
copy_bits(str, cloned, 0, length as u64); copy_bits(str, cloned, length as u64);
return String { return String {
inner: cloned, inner: cloned,
length: length, length: length -1,
max_length: length, max_length: length,
must_be_freed: false, must_be_freed: false,
}; };
@ -52,7 +52,7 @@ pub fn from_str(str: *char) -> String {
pub fn add_char(string: &mut String, c: char) { pub fn add_char(string: &mut String, c: char) {
if ((*string).length + 1) >= (*string).max_length { if ((*string).length + 1) >= (*string).max_length {
let new = allocate((*string).max_length + 4) as *char; let new = allocate((*string).max_length + 4) as *char;
copy_bits((*string).inner, new, 0, (*string).max_length); copy_bits((*string).inner, new, (*string).max_length);
if (*string).must_be_freed == true { if (*string).must_be_freed == true {
free((*string).inner as *u8); free((*string).inner as *u8);
@ -77,19 +77,18 @@ pub fn free_string(string: &mut String) {
free((*string).inner as *u8); free((*string).inner as *u8);
} }
fn copy_bits(from: *char, to: *char, pos: u64, max: u64) -> u8 { fn copy_bits(from: *char, to: *char, length: u64) {
if (pos >= max) { for i in 0 .. length {
return 0; to[i] = from[i];
} }
to[pos] = from[pos];
return copy_bits(from, to, pos + 1, max);
} }
fn str_length(string: *char, position: u32) -> u32 { fn str_length(string: *char) -> u32 {
if (string[position] == '\0') { let mut pos = 0;
return 0; while ((string[pos] == '\0') == false) {
pos = pos + 1;
} }
return str_length(string, position + 1) + 1; return pos + 1;
} }
pub fn add_num_to_str(string: &mut String, num: u64) { pub fn add_num_to_str(string: &mut String, num: u64) {