2017-08-31

Rust is finally starting to click, I think. I've now written two small CLI tools in it; this may not be much, but they're both useful tools and it represents making progress in getting comfortable in the language.

The first was a tool to set the console brightness on the Chromebook. xbacklight wasn't working, so this reads and writes from sysfs directly. It was useful to write to learn how to do file I/O and pathname building.

The second was a tool to check whether the network is currently down on the Jetson. It would have been easy enough to do in a shell script: some calls to dig, some calls to netcat, voilĂ . I made myself do it in Rust to learn. Fortunately, there's a Rust build for aarch64, so I'm all set. It did require nightly, because there's an unstable function in use.

One thing that's taking some getting used to is that I can't build &strs in a function the way I'd normally do it in Go. Normally, I'd try something like the following, neverminding that most of the Go functions take strings:

func joinHostPort(host string, port uint16) []byte {
    return []byte(fmt.Sprintf("%s:%d", host, port))
}

Although, I guess what tends to happen is

func joinHostPort(host string, port uint16) string {
    return fmt.Sprintf("%s:%d", host, port)
}

func setupConnection(host string, port uint16) error {
    // ...
    addr := joinHostPort(host, port)
    if err := connect([]byte(addr)); err != nil {
        return err
    }
}

In Rust, I've got something like

fn join_host_port(host: &str, port: u16) -> String {
    return format!("{}:{}", host, port)
}

fn can_connect(host: &str, port: u16) -> bool {
    let addr = join_host_port(host, port);
    match std::net::TcpStream::connect(addr) {
        Ok(_)  => return true,
        Err(_) => return false,
    }
}

The connect function is painful because I can't set a timeout on it; the timeout is hardcoded to 60 seconds. I'd rather a 3-5s timeout.

Getting used to having to specify parameter: type in functions is weird, and I keep trying to do parameter type instead. Array types are also weird: [type; size], and I keep forgetting semicolons. Things to get used to, I suppose.


Tags: ,