Skip to content

Not a code issue, just a question #2

@txdv

Description

@txdv
#[allow(ctypes)];
#[no_std];
#[no_core];

mod zero;

enum Color {
    Black       = 0,
    Blue        = 1,
    Green       = 2,
    Cyan        = 3,
    Red         = 4,
    Pink        = 5,
    Brown       = 6,
    LightGray   = 7,
    DarkGray    = 8,
    LightBlue   = 9,
    LightGreen  = 10,
    LightCyan   = 11,
    LightRed    = 12,
    LightPink   = 13,
    Yellow      = 14,
    White       = 15,
}

fn range(lo: uint, hi: uint, it: &fn(uint)) {
    let mut iter = lo;
    while iter < hi {
        it(iter);
        iter += 1;
    }
}

unsafe fn print_screen(i: uint, ch: u8) {
    *((0xb8000 + i * 2) as *mut u8) = ch;
}

unsafe fn set_color(i: uint, foreground: Color, background: Color) {
    *((0xb8000 + i * 2 + 1) as *mut u8) = ((background as u8) << 4) ^ (foreground as u8);
}

unsafe fn clear_screen(foreground: Color, background: Color) {
    range(0, 80*25, |i| {
        set_color(i, foreground, background);
        print_screen(i, 0)
    });
}

fn is_char(ch: u8) -> bool {
    return (ch >= 97 && ch <= 122) ||
           (ch >= 65 && ch <= 90);
}

fn is_whitespace(ch: u8) -> bool {
    return (ch == 32);
}

pub fn len(s: &str) -> uint {
    let mut i: uint = 0;
    while is_char(s[i]) {
        i += 1;
    }
    return i;
}

unsafe fn print_num(number: uint)
{
    let mut j = 0;
    let mut i = number;
    while i != 0 {
        let sym = i % 10 as u8;
        print_screen(j, sym + 48);
        j += 1;
        i = i / 10;
    }
}

#[no_mangle]
pub unsafe fn main() {
    let string: &str = "Hello World";
    let length = len(string);
    clear_screen(White, Blue);
    range(0, length, |i| {
        print_screen(i, string[i] as u8)
    });
    print_num(length);
}

This program should return 5ello, first printing 'Hello' and then printing '5'.
However, it just prints 5, if I change the length variable to 5, it will print out 5ello.
I am confused at what is happening, maybe someone with deeper asm knowledge could explain?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions