Writing a library with a Windows and a Unix implementation?


#1

I’m playing around with implementing Termbox in Rust since the existing libraries only wrap the C library and so don’t provide support for the Windows Console. As I’m doing this, I’m thinking about what it would take to make the library support both Windows and Unix.

What are the “accepted” ways to write a library that supports both Windows and Unix through largely different OS APIs? Are there good, and relatively simple, examples of libraries that do this? It would be nice to be able to share some of the code, but I’m not really sure where or how to do all that.


#2

The usual pattern is to do something like this (i didn’t compile this, but it should be close):

mod sys {
    mod nix {
    }

    mod win {
    }
}

#[cfg(windows)]
use sys::win as sys;
#[cfg(unix)]
use sys::nix as sys;

This isolates the specific bits. You then give both modules the same external interface, and write the code in common on top. Does that make sense?


#3

“write the code in common on top” - like?

pub mod api {
    pub fn some_function() {
        sys::some_os_abstraction_function()
    } 
}

#4

Yes. You can see this pattern in the standard library. Well, actually:

It’s sliiightly different but ends up as the same thing:

These then get used like this:

and:

both get used like this:

So that Thread::new is correct on both systems.