1#![warn(missing_docs)]
20#[cfg(windows)]
21pub mod windows;
22pub mod posix;
23use std::io::Result;
24
25pub trait Encoder {
27 fn to_string(self: &Self, data: &[u8]) -> Result<String>;
29
30 fn to_bytes(self: &Self, data: &str) -> Result<Vec<u8>>;
32}
33
34pub enum Encoding {
36 ANSI,
38 OEM,
40}
41
42#[cfg(windows)]
43trait CodePage {
44 fn codepage(self: &Self) -> u32;
45}
46
47#[cfg(windows)]
48impl CodePage for Encoding {
49 fn codepage(self: &Self) -> u32 {
50 extern crate winapi;
51
52 match self {
53 &Encoding::ANSI => winapi::CP_ACP,
54 &Encoding::OEM => winapi::CP_OEMCP,
55 }
56 }
57}
58
59#[cfg(windows)]
60impl Encoder for Encoding {
61 fn to_string(self: &Self, data: &[u8]) -> Result<String> {
63 windows::EncoderCodePage(self.codepage()).to_string(data)
64
65 }
66 fn to_bytes(self: &Self, data: &str) -> Result<Vec<u8>> {
68 windows::EncoderCodePage(self.codepage()).to_bytes(data)
69 }
70}
71
72#[cfg(not(windows))]
73impl Encoder for Encoding {
74 fn to_string(self: &Self, data: &[u8]) -> Result<String> {
76 posix::EncoderUtf8.to_string(data)
77
78 }
79 fn to_bytes(self: &Self, data: &str) -> Result<Vec<u8>> {
81 posix::EncoderUtf8.to_bytes(data)
82 }
83}
84
85#[cfg(test)]
86mod tests {
87 use super::*;
88
89 #[test]
90 fn oem_to_string_test() {
91 to_string_test(Encoding::OEM);
92 }
93
94 #[test]
95 fn ansi_to_string_test() {
96 to_string_test(Encoding::ANSI);
97 }
98
99 #[test]
100 fn string_to_oem_test() {
101 from_string_test(Encoding::OEM);
102 }
103
104 #[test]
105 fn string_to_ansi_test() {
106 from_string_test(Encoding::ANSI);
107 }
108
109 fn to_string_test(encoding: Encoding) {
110 assert_eq!(encoding.to_string(b"Test").unwrap(), "Test");
111 }
112
113 fn from_string_test(encoding: Encoding) {
114 assert_eq!(encoding.to_bytes("Test").unwrap(), b"Test");
115 }
116}