#![warn(missing_docs)]
#[cfg(windows)]
pub mod windows;
pub mod posix;
use std::io::Result;
pub trait Encoder {
fn to_string(self: &Self, data: &[u8]) -> Result<String>;
fn to_bytes(self: &Self, data: &str) -> Result<Vec<u8>>;
}
pub enum Encoding {
ANSI,
OEM,
}
#[cfg(windows)]
trait CodePage {
fn codepage(self: &Self) -> u32;
}
#[cfg(windows)]
impl CodePage for Encoding {
fn codepage(self: &Self) -> u32 {
extern crate winapi;
match self {
&Encoding::ANSI => winapi::CP_ACP,
&Encoding::OEM => winapi::CP_OEMCP,
}
}
}
#[cfg(windows)]
impl Encoder for Encoding {
fn to_string(self: &Self, data: &[u8]) -> Result<String> {
windows::EncoderCodePage(self.codepage()).to_string(data)
}
fn to_bytes(self: &Self, data: &str) -> Result<Vec<u8>> {
windows::EncoderCodePage(self.codepage()).to_bytes(data)
}
}
#[cfg(not(windows))]
impl Encoder for Encoding {
fn to_string(self: &Self, data: &[u8]) -> Result<String> {
posix::EncoderUtf8.to_string(data)
}
fn to_bytes(self: &Self, data: &str) -> Result<Vec<u8>> {
posix::EncoderUtf8.to_bytes(data)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn oem_to_string_test() {
to_string_test(Encoding::OEM);
}
#[test]
fn ansi_to_string_test() {
to_string_test(Encoding::ANSI);
}
#[test]
fn string_to_oem_test() {
from_string_test(Encoding::OEM);
}
#[test]
fn string_to_ansi_test() {
from_string_test(Encoding::ANSI);
}
fn to_string_test(encoding: Encoding) {
assert_eq!(encoding.to_string(b"Test").unwrap(), "Test");
}
fn from_string_test(encoding: Encoding) {
assert_eq!(encoding.to_bytes("Test").unwrap(), b"Test");
}
}