pub mod config;
mod conversion;
pub mod dictionary;
pub mod error;
#[cfg(not(target_arch = "wasm32"))]
pub mod ffi;
use std::path::Path;
use config::Config;
use conversion::ConversionChain;
use error::Result;
#[cfg(feature = "wasm")]
use wasm_bindgen::prelude::*;
use crate::{
config::BuiltinConfig,
dictionary::embedded,
};
#[cfg_attr(feature = "wasm", wasm_bindgen)]
pub struct OpenCC {
name: String,
conversion_chain: ConversionChain,
}
impl OpenCC {
pub fn new<P: AsRef<Path>>(config_path: P) -> Result<Self> {
let config = Config::from_file(config_path)?;
let config_dir = config.get_config_directory();
let conversion_chain = ConversionChain::from_config(&config.conversion_chain, config_dir)?;
Ok(Self {
name: config.name,
conversion_chain,
})
}
pub fn from_config(config_enum: BuiltinConfig) -> Result<Self> {
let name = config_enum.to_filename();
let config_str = embedded::EMBEDDED_CONFIGS
.get(name)
.ok_or_else(|| error::OpenCCError::ConfigNotFound(name.to_string()))?;
let config: Config = config_str.parse()?;
let conversion_chain = ConversionChain::from_config_embedded(&config.conversion_chain)?;
Ok(Self {
name: config.name,
conversion_chain,
})
}
#[must_use]
pub fn convert(&self, input: &str) -> String {
self.conversion_chain.convert(input)
}
#[must_use]
pub fn name(&self) -> &str {
&self.name
}
}
#[cfg(feature = "wasm")]
#[wasm_bindgen]
impl OpenCC {
#[wasm_bindgen(constructor)]
pub fn new_wasm(config_name: &str) -> std::result::Result<Self, JsValue> {
let config_enum = BuiltinConfig::from_filename(config_name)
.map_err(|e| JsValue::from_str(&e.to_string()))?;
Self::from_config(config_enum).map_err(|e| JsValue::from_str(&e.to_string()))
}
#[wasm_bindgen(js_name = convert)]
#[must_use]
pub fn convert_wasm(&self, input: &str) -> String {
self.convert(input)
}
#[wasm_bindgen(getter, js_name = name)]
#[must_use]
pub fn name_wasm(&self) -> String {
self.name.clone()
}
}