#![warn(missing_docs)]
#![deny(unsafe_code)]
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
pub mod b64;
#[doc(hidden)]
pub mod cldr;
pub mod codepage;
pub mod enc;
pub mod garble;
pub mod guard;
#[doc(hidden)]
pub mod plural_table;
pub mod profile;
mod pytables;
pub mod pytext;
pub mod smallmap;
#[doc(hidden)]
pub mod work;
pub mod icu;
mod plural;
pub use plural::{PluralKind, PluralSlot};
pub use encoding_rs;
pub use guard::{LimitError, LimitKind, Limits};
pub use smallmap::{SmallMap, TextMap};
pub use pytext::{py_is_word_char, py_is_word_start_char, py_isdecimal_char, py_isalnum_char, py_isalpha_char, py_isspace_char, py_has_alnum, py_has_alpha, py_isalnum, py_isalpha, py_isspace, py_lstrip, py_rstrip, py_strip};
pub trait IntoOptionString: sealed::Sealed {
fn into_option_string(self) -> Option<String>;
}
mod sealed {
pub trait Sealed {}
impl Sealed for &str {}
impl Sealed for String {}
impl Sealed for &String {}
impl Sealed for Option<String> {}
impl Sealed for Option<&str> {}
impl Sealed for Option<&String> {}
}
impl IntoOptionString for &str {
fn into_option_string(self) -> Option<String> {
Some(self.to_string())
}
}
impl IntoOptionString for String {
fn into_option_string(self) -> Option<String> {
Some(self)
}
}
impl IntoOptionString for &String {
fn into_option_string(self) -> Option<String> {
Some(self.clone())
}
}
impl IntoOptionString for Option<String> {
fn into_option_string(self) -> Option<String> {
self
}
}
impl IntoOptionString for Option<&str> {
fn into_option_string(self) -> Option<String> {
self.map(str::to_string)
}
}
impl IntoOptionString for Option<&String> {
fn into_option_string(self) -> Option<String> {
self.cloned()
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Inline {
Text(String),
#[non_exhaustive]
Tag {
id: String,
kind: TagKind,
display: String,
#[serde(default, skip_serializing_if = "is_false")]
free: bool,
},
}
fn is_false(b: &bool) -> bool {
!*b
}
impl Inline {
pub fn text(s: impl Into<String>) -> Inline {
Inline::Text(s.into())
}
pub fn tag(id: impl Into<String>, kind: TagKind, display: impl Into<String>) -> Inline {
Inline::Tag { id: id.into(), kind, display: display.into(), free: false }
}
pub fn free_tag(id: impl Into<String>, display: impl Into<String>) -> Inline {
Inline::Tag { id: id.into(), kind: TagKind::Standalone, display: display.into(), free: true }
}
pub fn is_free(&self) -> bool {
matches!(self, Inline::Tag { free: true, .. })
}
pub fn with_free(mut self, value: bool) -> Inline {
if let Inline::Tag { kind, free, .. } = &mut self {
*free = value && *kind == TagKind::Standalone;
}
self
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum TagKind {
Open,
Close,
Standalone,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct CodeData {
pub open: Option<String>,
pub close: Option<String>,
pub standalone: Option<String>,
pub label: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub ty: Option<CodeType>,
#[serde(default, skip_serializing_if = "TextMap::is_empty")]
pub attrs: TextMap,
}
impl CodeData {
pub fn new() -> CodeData {
CodeData::default()
}
pub fn paired(open: impl Into<String>, close: impl Into<String>) -> CodeData {
let (open, close): (String, String) = (open.into(), close.into());
CodeData::new().with_open(open).with_close(close)
}
pub fn standalone(markup: impl Into<String>) -> CodeData {
let markup: String = markup.into();
CodeData::new().with_standalone(markup)
}
pub fn with_open(mut self, open: impl IntoOptionString) -> CodeData {
self.open = open.into_option_string();
self
}
pub fn with_close(mut self, close: impl IntoOptionString) -> CodeData {
self.close = close.into_option_string();
self
}
pub fn with_standalone(mut self, standalone: impl IntoOptionString) -> CodeData {
self.standalone = standalone.into_option_string();
self
}
pub fn with_label(mut self, label: impl IntoOptionString) -> CodeData {
self.label = label.into_option_string();
self
}
pub fn open_markup(&self) -> Option<&str> {
self.open.as_deref()
}
pub fn close_markup(&self) -> Option<&str> {
self.close.as_deref()
}
pub fn standalone_markup(&self) -> Option<&str> {
self.standalone.as_deref()
}
pub fn label(&self) -> Option<&str> {
self.label.as_deref()
}
pub fn set_open(&mut self, open: impl IntoOptionString) {
self.open = open.into_option_string();
}
pub fn set_close(&mut self, close: impl IntoOptionString) {
self.close = close.into_option_string();
}
pub fn set_standalone(&mut self, standalone: impl IntoOptionString) {
self.standalone = standalone.into_option_string();
}
pub fn set_label(&mut self, label: impl IntoOptionString) {
self.label = label.into_option_string();
}
}
impl CodeData {
pub fn with_code_type(mut self, ty: Option<CodeType>) -> CodeData {
self.ty = ty;
self
}
pub fn with_attr(mut self, key: &str, value: impl Into<Box<str>>) -> CodeData {
self.set_attr(key, value);
self
}
pub fn code_type(&self) -> Option<CodeType> {
self.ty
}
pub fn set_code_type(&mut self, ty: Option<CodeType>) {
self.ty = ty;
}
pub fn attrs(&self) -> &TextMap {
&self.attrs
}
pub fn attrs_mut(&mut self) -> &mut TextMap {
&mut self.attrs
}
pub fn attr(&self, key: &str) -> Option<&str> {
self.attrs.get(key)
}
pub fn set_attr(&mut self, key: &str, value: impl Into<Box<str>>) {
let value: Box<str> = value.into();
if value.is_empty() {
self.attrs.remove(key);
} else {
self.attrs.insert(key, value);
}
}
pub fn clear_typing(&mut self) {
self.ty = None;
self.attrs.clear();
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum CodeType {
Bold,
Italic,
Underline,
Strike,
Superscript,
Subscript,
Code,
Style,
Link,
Image,
Linebreak,
Tab,
Field,
Footnoteref,
Placeholder,
#[serde(other)]
Other,
}
impl CodeType {
pub fn as_str(self) -> &'static str {
match self {
CodeType::Bold => "bold",
CodeType::Italic => "italic",
CodeType::Underline => "underline",
CodeType::Strike => "strike",
CodeType::Superscript => "superscript",
CodeType::Subscript => "subscript",
CodeType::Code => "code",
CodeType::Style => "style",
CodeType::Link => "link",
CodeType::Image => "image",
CodeType::Linebreak => "linebreak",
CodeType::Tab => "tab",
CodeType::Field => "field",
CodeType::Footnoteref => "footnoteref",
CodeType::Placeholder => "placeholder",
CodeType::Other => "other",
}
}
pub fn from_name(name: &str) -> CodeType {
CodeType::ALL.iter().copied().find(|t| t.as_str() == name).unwrap_or(CodeType::Other)
}
pub const ALL: [CodeType; 16] = [
CodeType::Bold,
CodeType::Italic,
CodeType::Underline,
CodeType::Strike,
CodeType::Superscript,
CodeType::Subscript,
CodeType::Code,
CodeType::Style,
CodeType::Link,
CodeType::Image,
CodeType::Linebreak,
CodeType::Tab,
CodeType::Field,
CodeType::Footnoteref,
CodeType::Placeholder,
CodeType::Other,
];
pub fn attr_keys(self) -> &'static [&'static str] {
match self {
CodeType::Link => &["href", "title"],
CodeType::Field => &["field"],
CodeType::Image => &["src", "alt"],
CodeType::Style => &["style"],
CodeType::Placeholder => &["name"],
_ => &[],
}
}
}
impl std::fmt::Display for CodeType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
pub type Codes = SmallMap<CodeData>;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[non_exhaustive]
pub enum SegState {
#[default]
#[serde(rename = "new")]
New,
#[serde(rename = "draft")]
Draft,
#[serde(rename = "translated")]
Translated,
#[serde(rename = "confirmed")]
Confirmed,
#[serde(rename = "reviewed")]
Reviewed,
#[serde(rename = "signed-off")]
SignedOff,
#[serde(rename = "rejected")]
Rejected,
#[serde(rename = "locked")]
Locked,
}
impl SegState {
pub fn rank(self) -> u8 {
match self {
SegState::New => 0,
SegState::Rejected => 1,
SegState::Draft => 2,
SegState::Translated => 3,
SegState::Confirmed => 4,
SegState::Reviewed => 5,
SegState::SignedOff => 6,
SegState::Locked => 7,
}
}
pub fn from_rank(r: u8) -> SegState {
match r {
0 => SegState::New,
1 => SegState::Rejected,
2 => SegState::Draft,
3 => SegState::Translated,
4 => SegState::Confirmed,
5 => SegState::Reviewed,
6 => SegState::SignedOff,
_ => SegState::Locked,
}
}
pub fn is_accepted(self) -> bool {
self.rank() >= SegState::Translated.rank()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum OriginKind {
Tm,
Mt,
Ai,
Human,
#[default]
#[serde(other)]
Other,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Origin {
pub kind: OriginKind,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub match_pct: Option<u8>,
}
impl Origin {
pub fn new(kind: OriginKind) -> Origin {
Origin { kind, name: None, match_pct: None }
}
pub fn with_match(mut self, pct: u8) -> Origin {
self.match_pct = Some(pct);
self
}
pub fn with_match_pct(mut self, pct: Option<u8>) -> Origin {
self.match_pct = pct;
self
}
pub fn with_name(mut self, name: impl IntoOptionString) -> Origin {
self.name = name.into_option_string();
self
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Segment {
pub id: String,
pub source: Vec<Inline>,
#[serde(default)]
pub target: Vec<Inline>,
#[serde(default)]
pub state: SegState,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub origin: Option<Origin>,
#[serde(default, skip_serializing_if = "is_false")]
pub empty_target: bool,
}
impl Segment {
pub fn new(id: impl Into<String>, source: Vec<Inline>) -> Segment {
Segment { id: id.into(), source, target: vec![], state: SegState::New, origin: None, empty_target: false }
}
pub fn has_target(&self) -> bool {
!self.target.is_empty() || self.empty_target
}
pub fn output(&self) -> &[Inline] {
if self.has_target() {
&self.target
} else {
&self.source
}
}
pub fn with_empty_target(mut self, empty_target: bool) -> Segment {
self.empty_target = empty_target;
if empty_target {
self.target.clear();
}
self
}
pub fn with_target(mut self, target: Vec<Inline>) -> Segment {
self.target = target;
self
}
pub fn with_state(mut self, state: SegState) -> Segment {
self.state = state;
self
}
pub fn with_origin(mut self, origin: impl Into<Option<Origin>>) -> Segment {
self.origin = origin.into();
self
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Note {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub author: Option<String>,
pub text: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub kind: Option<String>,
}
impl Note {
pub fn new(text: impl Into<String>) -> Note {
Note { author: None, text: text.into(), kind: None }
}
pub fn with_author(mut self, author: impl IntoOptionString) -> Note {
self.author = author.into_option_string();
self
}
pub fn with_kind(mut self, kind: impl IntoOptionString) -> Note {
self.kind = kind.into_option_string();
self
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct UnitContext {
pub kind: Option<String>,
pub style: Option<String>,
pub key: Option<String>,
pub heading: Option<String>,
pub location: Option<String>,
pub max_len: Option<usize>,
#[serde(default)]
pub notes: Vec<String>,
#[serde(default)]
pub extra: TextMap,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub role: Option<Role>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub level: Option<u8>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum Role {
Heading,
Title,
Subtitle,
SlideTitle,
Header,
Footer,
Footnote,
Endnote,
Notes,
Comment,
Caption,
SheetName,
#[serde(other)]
Other,
}
impl Role {
pub fn as_str(self) -> &'static str {
match self {
Role::Heading => "heading",
Role::Title => "title",
Role::Subtitle => "subtitle",
Role::SlideTitle => "slidetitle",
Role::Header => "header",
Role::Footer => "footer",
Role::Footnote => "footnote",
Role::Endnote => "endnote",
Role::Notes => "notes",
Role::Comment => "comment",
Role::Caption => "caption",
Role::SheetName => "sheetname",
Role::Other => "other",
}
}
}
impl std::fmt::Display for Role {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
impl UnitContext {
pub fn with_role(mut self, role: impl Into<Option<Role>>) -> UnitContext {
self.role = role.into();
self
}
pub fn with_level(mut self, level: impl Into<Option<u8>>) -> UnitContext {
self.level = level.into();
self
}
pub fn role(&self) -> Option<Role> {
self.role
}
pub fn level(&self) -> Option<u8> {
self.level
}
pub fn set_role(&mut self, role: impl Into<Option<Role>>) {
self.role = role.into();
}
pub fn set_level(&mut self, level: impl Into<Option<u8>>) {
self.level = level.into();
}
pub fn set_heading_role(&mut self, level: u8) {
self.role = Some(Role::Heading);
self.level = (level > 0).then_some(level);
}
}
impl UnitContext {
pub fn new() -> UnitContext {
UnitContext::default()
}
pub fn with_kind(mut self, kind: impl IntoOptionString) -> UnitContext {
self.kind = kind.into_option_string();
self
}
pub fn with_style(mut self, style: impl IntoOptionString) -> UnitContext {
self.style = style.into_option_string();
self
}
pub fn with_key(mut self, key: impl IntoOptionString) -> UnitContext {
self.key = key.into_option_string();
self
}
pub fn with_heading(mut self, heading: impl IntoOptionString) -> UnitContext {
self.heading = heading.into_option_string();
self
}
pub fn with_location(mut self, location: impl IntoOptionString) -> UnitContext {
self.location = location.into_option_string();
self
}
pub fn with_max_len(mut self, max_len: Option<usize>) -> UnitContext {
self.max_len = max_len;
self
}
pub fn with_notes(mut self, notes: Vec<String>) -> UnitContext {
self.notes = notes;
self
}
pub fn with_extra(mut self, extra: impl Into<TextMap>) -> UnitContext {
self.set_extra(extra);
self
}
pub fn kind(&self) -> Option<&str> {
self.kind.as_deref()
}
pub fn style(&self) -> Option<&str> {
self.style.as_deref()
}
pub fn key(&self) -> Option<&str> {
self.key.as_deref()
}
pub fn heading(&self) -> Option<&str> {
self.heading.as_deref()
}
pub fn location(&self) -> Option<&str> {
self.location.as_deref()
}
pub fn set_kind(&mut self, kind: impl IntoOptionString) {
self.kind = kind.into_option_string();
}
pub fn set_style(&mut self, style: impl IntoOptionString) {
self.style = style.into_option_string();
}
pub fn set_key(&mut self, key: impl IntoOptionString) {
self.key = key.into_option_string();
}
pub fn set_heading(&mut self, heading: impl IntoOptionString) {
self.heading = heading.into_option_string();
}
pub fn set_location(&mut self, location: impl IntoOptionString) {
self.location = location.into_option_string();
}
pub fn extra(&self) -> &TextMap {
&self.extra
}
pub fn extra_mut(&mut self) -> &mut TextMap {
&mut self.extra
}
pub fn set_extra(&mut self, extra: impl Into<TextMap>) {
self.extra = extra.into();
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(from = "UnitRepr")]
#[non_exhaustive]
pub struct Unit {
pub id: String,
pub segments: Vec<Segment>,
#[serde(default)]
pub separators: Vec<String>,
#[serde(default)]
pub codes: Codes,
#[serde(default)]
pub context: UnitContext,
#[serde(default = "yes")]
pub translate: bool,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub notes: Vec<Note>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub lock_reason: Option<String>,
#[serde(default, skip_serializing_if = "TextMap::is_empty")]
pub hidden: TextMap,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub plural: Option<Box<PluralSlot>>,
}
fn yes() -> bool {
true
}
#[derive(Deserialize)]
struct UnitRepr {
id: String,
segments: Vec<Segment>,
#[serde(default)]
separators: Vec<String>,
#[serde(default)]
codes: Codes,
#[serde(default)]
context: UnitContext,
#[serde(default = "yes")]
translate: bool,
#[serde(default)]
notes: Vec<Note>,
#[serde(default)]
lock_reason: Option<String>,
#[serde(default)]
hidden: TextMap,
#[serde(default)]
plural: Option<Box<PluralSlot>>,
}
impl From<UnitRepr> for Unit {
fn from(r: UnitRepr) -> Unit {
let mut hidden = r.hidden;
let mut codes = r.codes;
let old = |k: &str, c: &CodeData| k.starts_with('~') && c.open.is_none() && c.close.is_none();
if codes.iter().any(|(k, c)| old(k, c)) {
let mut kept = Vec::with_capacity(codes.len());
for (k, c) in codes {
if old(&k, &c) {
let name = &k[1..];
if !hidden.contains_key(name) {
hidden.insert(name, c.standalone.or(c.label).unwrap_or_default());
}
} else {
kept.push((k, c));
}
}
codes = kept.into_iter().collect();
}
Unit {
id: r.id,
segments: r.segments,
separators: r.separators,
codes,
context: r.context,
translate: r.translate,
notes: r.notes,
lock_reason: r.lock_reason,
hidden,
plural: r.plural,
}
}
}
impl Unit {
pub fn new(id: impl Into<String>, source: Vec<Inline>) -> Unit {
let id = id.into();
let seg = Segment::new(id.clone(), source);
Unit::from_segments(id, vec![seg])
}
pub fn from_segments(id: impl Into<String>, segments: Vec<Segment>) -> Unit {
Unit {
separators: vec![String::new(); segments.len().saturating_sub(1)],
segments,
id: id.into(),
codes: Codes::new(),
context: UnitContext::default(),
translate: true,
notes: vec![],
lock_reason: None,
hidden: TextMap::new(),
plural: None,
}
}
pub fn hidden(&self, key: &str) -> Option<&str> {
self.hidden.get(key)
}
pub fn set_hidden(&mut self, key: impl Into<String>, value: impl Into<String>) {
self.hidden.insert(key.into(), value.into());
}
pub fn has_hidden(&self, key: &str) -> bool {
self.hidden.contains_key(key)
}
pub fn with_hidden(mut self, key: impl Into<String>, value: impl Into<String>) -> Unit {
self.set_hidden(key, value);
self
}
pub fn hidden_map(&self) -> &TextMap {
&self.hidden
}
pub fn hidden_map_mut(&mut self) -> &mut TextMap {
&mut self.hidden
}
pub fn set_hidden_map(&mut self, hidden: impl Into<TextMap>) {
self.hidden = hidden.into();
}
pub fn codes(&self) -> &Codes {
&self.codes
}
pub fn codes_mut(&mut self) -> &mut Codes {
&mut self.codes
}
pub fn set_codes(&mut self, codes: impl Into<Codes>) {
self.codes = codes.into();
}
pub fn with_separators(mut self, separators: Vec<String>) -> Unit {
self.separators = separators;
self
}
pub fn with_codes(mut self, codes: impl Into<Codes>) -> Unit {
self.set_codes(codes);
self
}
pub fn with_code(mut self, id: impl Into<String>, code: CodeData) -> Unit {
self.codes.insert(id.into(), code);
self
}
pub fn with_context(mut self, context: UnitContext) -> Unit {
self.context = context;
self
}
pub fn with_translate(mut self, translate: bool) -> Unit {
self.translate = translate;
self
}
pub fn with_notes(mut self, notes: Vec<Note>) -> Unit {
self.notes = notes;
self
}
pub fn with_lock_reason(mut self, reason: impl IntoOptionString) -> Unit {
self.lock_reason = reason.into_option_string();
self
}
pub fn source(&self) -> Vec<Inline> {
self.join(|s| &s.source)
}
pub fn output(&self) -> Vec<Inline> {
self.join(|s| if s.has_target() { &s.target } else { &s.source })
}
pub fn is_translated(&self) -> bool {
self.translate && self.segments.iter().any(Segment::has_target)
}
fn join<'a>(&'a self, pick: impl Fn(&'a Segment) -> &'a Vec<Inline>) -> Vec<Inline> {
let mut out = Vec::new();
for (i, seg) in self.segments.iter().enumerate() {
if i > 0 {
if let Some(sep) = self.separators.get(i - 1) {
if !sep.is_empty() {
out.push(Inline::Text(sep.clone()));
}
}
}
out.extend(pick(seg).iter().cloned());
}
merge_text(out)
}
}
impl Unit {
pub fn plural(&self) -> Option<&PluralSlot> {
self.plural.as_deref()
}
pub fn plural_mut(&mut self) -> Option<&mut PluralSlot> {
self.plural.as_deref_mut()
}
pub fn set_plural(&mut self, plural: impl Into<Option<PluralSlot>>) {
self.plural = plural.into().map(Box::new);
}
pub fn with_plural(mut self, plural: impl Into<Option<PluralSlot>>) -> Unit {
self.set_plural(plural);
self
}
}
pub fn merge_text(v: Vec<Inline>) -> Vec<Inline> {
let mut out: Vec<Inline> = Vec::with_capacity(v.len());
for i in v {
match (out.last_mut(), i) {
(Some(Inline::Text(a)), Inline::Text(b)) => a.push_str(&b),
(_, Inline::Text(t)) if t.is_empty() => {}
(_, x) => out.push(x),
}
}
out
}
pub fn plain_text(v: &[Inline]) -> String {
v.iter()
.filter_map(|i| match i {
Inline::Text(t) => Some(t.as_str()),
_ => None,
})
.collect()
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SkelPart {
Raw(String),
Unit(usize),
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ZipData {
Raw(#[serde(with = "b64")] Vec<u8>),
Parts(Vec<SkelPart>),
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ZipEntry {
pub name: String,
pub data: ZipData,
}
impl ZipEntry {
pub fn new(name: impl Into<String>, data: ZipData) -> ZipEntry {
ZipEntry { name: name.into(), data }
}
pub fn raw(name: impl Into<String>, bytes: Vec<u8>) -> ZipEntry {
ZipEntry::new(name, ZipData::Raw(bytes))
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ParserInfo {
pub name: String,
pub version: String,
#[serde(default = "legacy_schema")]
pub schema: u32,
}
fn legacy_schema() -> u32 {
1
}
impl ParserInfo {
pub fn new(name: impl Into<String>, version: impl Into<String>, schema: u32) -> ParserInfo {
ParserInfo { name: name.into(), version: version.into(), schema }
}
pub fn compatible_with(&self, current: &ParserInfo) -> bool {
self.name == current.name && self.schema <= current.schema
}
}
#[allow(clippy::crate_in_macro_def)]
#[macro_export]
macro_rules! parser_info {
() => {
$crate::parser_info!(crate::SKELETON_SCHEMA)
};
($schema:expr) => {
$crate::ParserInfo::new(env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"), $schema)
};
}
pub fn check_parser(doc: &Document, current: &ParserInfo) -> Result<(), Error> {
check_parser_min(doc, current, 1)
}
pub fn check_parser_min(doc: &Document, current: &ParserInfo, oldest: u32) -> Result<(), Error> {
match doc.skeleton.parser() {
Some(found) if !found.compatible_with(current) || found.schema < oldest => Err(Error::ParserVersion {
found: format!("{} {} (skeleton schema {})", found.name, found.version, found.schema),
expected: if found.name != current.name {
current.name.clone()
} else if found.schema > current.schema {
format!("{} {} (reads skeleton schema {} and older)", current.name, current.version, current.schema)
} else {
format!("{} {} (reads skeleton schema {} to {})", current.name, current.version, oldest, current.schema)
},
}),
_ => Ok(()),
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum Skeleton {
Text {
parts: Vec<SkelPart>,
encoding: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
parser: Option<ParserInfo>,
},
Zip {
entries: Vec<ZipEntry>,
#[serde(default, skip_serializing_if = "Option::is_none")]
parser: Option<ParserInfo>,
},
Binary {
#[serde(with = "b64")]
data: Vec<u8>,
#[serde(default, skip_serializing_if = "Option::is_none")]
parser: Option<ParserInfo>,
},
}
impl Default for Skeleton {
fn default() -> Self {
Skeleton::Text { parts: Vec::new(), encoding: "utf-8".into(), parser: None }
}
}
impl Skeleton {
pub fn text(parts: Vec<SkelPart>, encoding: impl Into<String>, parser: ParserInfo) -> Skeleton {
Skeleton::Text { parts, encoding: encoding.into(), parser: Some(parser) }
}
pub fn zip(entries: Vec<ZipEntry>, parser: ParserInfo) -> Skeleton {
Skeleton::Zip { entries, parser: Some(parser) }
}
pub fn binary(data: Vec<u8>, parser: ParserInfo) -> Skeleton {
Skeleton::Binary { data, parser: Some(parser) }
}
pub fn parser(&self) -> Option<&ParserInfo> {
match self {
Skeleton::Text { parser, .. } | Skeleton::Zip { parser, .. } | Skeleton::Binary { parser, .. } => parser.as_ref(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum Granularity {
#[default]
Sentence,
Paragraph,
Document,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Document {
pub format: String,
pub name: Option<String>,
pub source_lang: Option<String>,
pub target_lang: Option<String>,
pub granularity: Granularity,
pub units: Vec<Unit>,
pub skeleton: Skeleton,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub warnings: Vec<Warning>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub source_encoding: Option<String>,
#[serde(skip)]
seg_index: SegIndex,
}
#[derive(Default)]
struct SegIndex(Option<std::collections::HashMap<String, (usize, usize)>>);
impl Clone for SegIndex {
fn clone(&self) -> SegIndex {
SegIndex(None)
}
}
impl std::fmt::Debug for SegIndex {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("SegIndex")
}
}
impl PartialEq for SegIndex {
fn eq(&self, _: &SegIndex) -> bool {
true
}
}
impl Eq for SegIndex {}
impl Document {
pub fn plural_categories(&self, kind: PluralKind) -> Option<Vec<&'static str>> {
plural::categories(self.target_lang.as_deref(), kind)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Warning {
pub kind: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub part: String,
pub message: String,
}
impl Warning {
pub fn new(kind: impl Into<String>, part: impl Into<String>, message: impl Into<String>) -> Warning {
Warning { kind: kind.into(), part: part.into(), message: message.into() }
}
}
impl Document {
pub fn new(format: impl Into<String>, units: Vec<Unit>, skeleton: Skeleton) -> Document {
Document { format: format.into(), name: None, source_lang: None, target_lang: None, granularity: Granularity::default(), units, skeleton, warnings: vec![], source_encoding: None, seg_index: SegIndex::default() }
}
pub fn with_options(mut self, opts: &ExtractOptions) -> Document {
self.source_lang = opts.source_lang.clone();
self.target_lang = opts.target_lang.clone();
self.granularity = opts.granularity;
self
}
pub fn with_name(mut self, name: impl IntoOptionString) -> Document {
self.name = name.into_option_string();
self
}
pub fn with_source_lang(mut self, lang: impl IntoOptionString) -> Document {
self.source_lang = lang.into_option_string();
self
}
pub fn with_target_lang(mut self, lang: impl IntoOptionString) -> Document {
self.target_lang = lang.into_option_string();
self
}
pub fn with_granularity(mut self, granularity: Granularity) -> Document {
self.granularity = granularity;
self
}
pub fn detected_source_encoding(&self) -> Option<String> {
let encoding = match &self.skeleton {
Skeleton::Text { encoding, .. } => encoding.as_str(),
Skeleton::Binary { data, .. } if matches!(self.format.as_str(), "markdown" | "po" | "srt" | "vtt") => enc::locos_skeleton_parts(data)?.0,
_ => return None,
};
let base = encoding.split(';').next().unwrap_or("").to_ascii_lowercase();
let base = base.strip_suffix("-bom").or_else(|| base.strip_suffix("-nobom")).unwrap_or(&base).to_string();
(!matches!(base.as_str(), "" | "utf-8" | "utf8" | "bplist")).then_some(base)
}
pub fn with_warnings(mut self, warnings: Vec<Warning>) -> Document {
self.warnings = warnings;
self
}
pub fn segments(&self) -> impl Iterator<Item = (&Unit, &Segment)> {
self.units.iter().flat_map(|u| u.segments.iter().map(move |s| (u, s)))
}
pub fn segment_count(&self) -> usize {
self.units.iter().map(|u| u.segments.len()).sum()
}
pub fn find(&self, seg_id: &str) -> Option<(&Unit, &Segment)> {
self.segments().find(|(_, s)| s.id == seg_id)
}
pub fn set_target(&mut self, seg_id: &str, target: Vec<Inline>) -> Result<(), Error> {
let at = self.locate(seg_id).ok_or_else(|| Error::UnknownSegment(seg_id.to_string()))?;
self.apply_target(at, seg_id, target, false)
}
pub fn set_target_repeating(&mut self, seg_id: &str, target: Vec<Inline>) -> Result<(), Error> {
let at = self.locate(seg_id).ok_or_else(|| Error::UnknownSegment(seg_id.to_string()))?;
self.apply_target(at, seg_id, target, true)
}
pub(crate) fn locate(&mut self, seg_id: &str) -> Option<(usize, usize)> {
let valid = |units: &[Unit], (ui, si): (usize, usize)| units.get(ui).and_then(|u| u.segments.get(si)).is_some_and(|s| s.id == seg_id);
if let Some(at) = self.seg_index.0.as_ref().and_then(|m| m.get(seg_id)).copied() {
if valid(&self.units, at) {
return Some(at);
}
}
let fresh = self.segment_index();
let at = fresh.get(seg_id).copied();
self.seg_index = SegIndex(Some(fresh));
at
}
pub fn set_targets<I, S>(&mut self, items: I) -> Result<(), Error>
where
I: IntoIterator<Item = (S, Vec<Inline>)>,
S: AsRef<str>,
{
let index = self.segment_index();
for (id, target) in items {
let id = id.as_ref();
let at = *index.get(id).ok_or_else(|| Error::UnknownSegment(id.to_string()))?;
self.apply_target(at, id, target, false)?;
}
Ok(())
}
pub fn set_states<I, S>(&mut self, items: I) -> Result<(), Error>
where
I: IntoIterator<Item = (S, SegState)>,
S: AsRef<str>,
{
let index = self.segment_index();
for (id, state) in items {
let id = id.as_ref();
let (ui, si) = *index.get(id).ok_or_else(|| Error::UnknownSegment(id.to_string()))?;
self.units[ui].segments[si].state = state;
}
Ok(())
}
fn segment_index(&self) -> std::collections::HashMap<String, (usize, usize)> {
let mut m = std::collections::HashMap::with_capacity(self.segment_count());
for (ui, u) in self.units.iter().enumerate() {
for (si, s) in u.segments.iter().enumerate() {
m.entry(s.id.clone()).or_insert((ui, si));
}
}
m
}
fn apply_target(&mut self, (ui, si): (usize, usize), seg_id: &str, target: Vec<Inline>, repeat_standalone: bool) -> Result<(), Error> {
let unit = &mut self.units[ui];
if !unit.translate {
return Err(Error::Locked(seg_id.to_string()));
}
let seg = &mut unit.segments[si];
if seg.state == SegState::Locked {
return Err(Error::Locked(seg_id.to_string()));
}
check_tags(&seg.source, &target, repeat_standalone)?;
let target = merge_text(
target
.into_iter()
.map(|i| match i {
Inline::Tag { id, kind, display, .. } => {
let free = kind == TagKind::Standalone
&& seg.source.iter().any(|s| matches!(s, Inline::Tag { id: sid, kind: TagKind::Standalone, free: true, .. } if *sid == id));
Inline::Tag { id, kind, display, free }
}
t => t,
})
.collect(),
);
let empty = plain_text(&target).trim().is_empty() && !target.iter().any(|i| matches!(i, Inline::Tag { .. }));
seg.target = if empty { vec![] } else { target };
seg.empty_target = false;
seg.state = if seg.target.is_empty() { SegState::New } else { SegState::Draft };
Ok(())
}
pub fn set_target_empty(&mut self, seg_id: &str) -> Result<(), Error> {
let (ui, si) = self.locate(seg_id).ok_or_else(|| Error::UnknownSegment(seg_id.to_string()))?;
let unit = &mut self.units[ui];
if !unit.translate {
return Err(Error::Locked(seg_id.to_string()));
}
let seg = &mut unit.segments[si];
if seg.state == SegState::Locked {
return Err(Error::Locked(seg_id.to_string()));
}
seg.target.clear();
seg.empty_target = true;
seg.state = SegState::Draft;
Ok(())
}
pub fn set_state(&mut self, seg_id: &str, state: SegState) -> Result<(), Error> {
let (ui, si) = self.locate(seg_id).ok_or_else(|| Error::UnknownSegment(seg_id.to_string()))?;
self.units[ui].segments[si].state = state;
Ok(())
}
}
pub(crate) fn check_target_tags(source: &[Inline], target: &[Inline], codes: &Codes, counts: bool) -> Result<(), Error> {
let mut allowed: BTreeMap<(&str, TagKind), usize> = BTreeMap::new();
for i in source {
if let Inline::Tag { id, kind, .. } = i {
*allowed.entry((id.as_str(), *kind)).or_default() += 1;
}
}
let mut used: BTreeMap<(&str, TagKind), usize> = BTreeMap::new();
for i in target {
if let Inline::Tag { id, kind, .. } = i {
match allowed.get(&(id.as_str(), *kind)) {
Some(max) => {
let n = used.entry((id.as_str(), *kind)).or_default();
*n += 1;
if counts && *n > *max && *kind != TagKind::Standalone {
return Err(Error::DuplicatedTag(id.clone()));
}
}
None if codes.contains_key(id) => {}
None => return Err(Error::InventedTag(id.clone())),
}
}
}
Ok(())
}
fn check_tags(source: &[Inline], target: &[Inline], repeat_standalone: bool) -> Result<(), Error> {
let mut allowed: BTreeMap<(&str, TagKind), usize> = BTreeMap::new();
for i in source {
if let Inline::Tag { id, kind, .. } = i {
*allowed.entry((id.as_str(), *kind)).or_default() += 1;
}
}
let mut used: BTreeMap<(&str, TagKind), usize> = BTreeMap::new();
for i in target {
if let Inline::Tag { id, kind, .. } = i {
let n = used.entry((id.as_str(), *kind)).or_default();
*n += 1;
match allowed.get(&(id.as_str(), *kind)) {
None => return Err(Error::InventedTag(id.clone())),
Some(max) if *n > *max && !(repeat_standalone && *kind == TagKind::Standalone) => return Err(Error::DuplicatedTag(id.clone())),
_ => {}
}
}
}
Ok(())
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ExtractOptions {
pub source_lang: Option<String>,
pub target_lang: Option<String>,
pub granularity: Granularity,
pub include_locked: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub limits: Option<Limits>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub format_options: BTreeMap<String, String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub profile: Option<String>,
}
impl ExtractOptions {
pub fn with_profile(mut self, profile: impl IntoOptionString) -> ExtractOptions {
self.profile = profile.into_option_string();
self
}
pub fn is_profile(&self, name: &str) -> bool {
self.profile.as_deref() == Some(name)
}
pub fn new() -> ExtractOptions {
ExtractOptions::default()
}
pub fn with_source_lang(mut self, lang: impl IntoOptionString) -> ExtractOptions {
self.source_lang = lang.into_option_string();
self
}
pub fn with_target_lang(mut self, lang: impl IntoOptionString) -> ExtractOptions {
self.target_lang = lang.into_option_string();
self
}
pub fn with_granularity(mut self, granularity: Granularity) -> ExtractOptions {
self.granularity = granularity;
self
}
pub fn with_include_locked(mut self, include_locked: bool) -> ExtractOptions {
self.include_locked = include_locked;
self
}
pub fn with_limits(mut self, limits: impl Into<Option<Limits>>) -> ExtractOptions {
self.limits = limits.into();
self
}
pub fn with_format_option(mut self, key: impl Into<String>, value: impl ToString) -> ExtractOptions {
self.format_options.insert(key.into(), value.to_string());
self
}
pub fn with_format_options(mut self, options: BTreeMap<String, String>) -> ExtractOptions {
self.format_options = options;
self
}
pub fn format_option(&self, key: &str) -> Option<&str> {
self.format_options.get(key).map(String::as_str)
}
pub fn format_flag(&self, key: &str) -> Option<bool> {
match self.format_option(key)?.trim().to_ascii_lowercase().as_str() {
"true" | "1" | "yes" | "on" => Some(true),
"false" | "0" | "no" | "off" => Some(false),
_ => None,
}
}
pub fn format_int(&self, key: &str) -> Option<i64> {
self.format_option(key)?.trim().parse().ok()
}
pub fn limits(&self) -> Limits {
self.limits.unwrap_or_default().clamped()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum OptionKind {
Bool,
Int,
Text,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct FormatOptionKey {
pub key: &'static str,
pub kind: OptionKind,
pub help: &'static str,
}
impl FormatOptionKey {
pub const fn new(key: &'static str, kind: OptionKind, help: &'static str) -> FormatOptionKey {
FormatOptionKey { key, kind, help }
}
pub const fn bool(key: &'static str, help: &'static str) -> FormatOptionKey {
FormatOptionKey::new(key, OptionKind::Bool, help)
}
pub const fn int(key: &'static str, help: &'static str) -> FormatOptionKey {
FormatOptionKey::new(key, OptionKind::Int, help)
}
pub const fn text(key: &'static str, help: &'static str) -> FormatOptionKey {
FormatOptionKey::new(key, OptionKind::Text, help)
}
pub fn check(&self, value: &str) -> Result<(), Error> {
let v = value.trim();
let ok = match self.kind {
OptionKind::Bool => matches!(v.to_ascii_lowercase().as_str(), "true" | "1" | "yes" | "on" | "false" | "0" | "no" | "off"),
OptionKind::Int => v.parse::<i64>().is_ok(),
OptionKind::Text => true,
};
if ok {
Ok(())
} else {
let want = match self.kind {
OptionKind::Bool => "true or false",
OptionKind::Int => "an integer",
OptionKind::Text => "text",
};
Err(Error::FormatOption { key: self.key.to_string(), msg: format!("the value {value:?} is not {want}") })
}
}
}
pub fn check_format_options(opts: &ExtractOptions, known: &[FormatOptionKey]) -> Result<(), Error> {
check_option_map(&opts.format_options, known)
}
pub fn check_option_map(options: &BTreeMap<String, String>, known: &[FormatOptionKey]) -> Result<(), Error> {
for (k, v) in options {
match known.iter().find(|f| f.key == k) {
Some(f) => f.check(v)?,
None => {
let family = k.split('.').next().unwrap_or("");
let same: Vec<&str> = known.iter().filter(|f| f.key.split('.').next() == Some(family)).map(|f| f.key).collect();
let msg = if same.is_empty() { "no format has this option".to_string() } else { format!("unknown option; {family} knows {}", same.join(", ")) };
return Err(Error::FormatOption { key: k.clone(), msg });
}
}
}
Ok(())
}
pub fn check_own_options<F: Filter + ?Sized>(filter: &F, options: &BTreeMap<String, String>) -> Result<(), Error> {
if options.is_empty() {
return Ok(());
}
let keys = filter.format_option_keys();
let id = filter.id();
let family = |k: &str| k.split('.').next().unwrap_or("").to_string();
for (k, v) in options {
let fam = family(k);
if fam != id && !keys.iter().any(|f| family(f.key) == fam) {
continue;
}
match keys.iter().find(|f| f.key == k) {
Some(f) => f.check(v)?,
None => {
let mine: Vec<&str> = keys.iter().map(|f| f.key).collect();
let msg = if mine.is_empty() { format!("{id} has no options") } else { format!("unknown option; {id} knows {}", mine.join(", ")) };
return Err(Error::FormatOption { key: k.clone(), msg });
}
}
}
Ok(())
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum OutputEncoding {
#[default]
#[serde(rename = "keep")]
Keep,
#[serde(rename = "utf-8", alias = "utf8")]
Utf8,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct MergeOptions {
pub output_encoding: OutputEncoding,
pub stamp_target_always: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub profile: Option<String>,
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
pub format_options: BTreeMap<String, String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub limits: Option<Limits>,
}
impl MergeOptions {
pub fn new() -> MergeOptions {
MergeOptions::default()
}
pub fn with_output_encoding(mut self, output_encoding: OutputEncoding) -> MergeOptions {
self.output_encoding = output_encoding;
self
}
pub fn with_stamp_target_always(mut self, stamp_target_always: bool) -> MergeOptions {
self.stamp_target_always = stamp_target_always;
self
}
pub fn with_profile(mut self, profile: impl IntoOptionString) -> MergeOptions {
self.profile = profile.into_option_string();
self
}
pub fn is_profile(&self, name: &str) -> bool {
self.profile.as_deref() == Some(name)
}
pub fn with_limits(mut self, limits: impl Into<Option<Limits>>) -> MergeOptions {
self.limits = limits.into();
self
}
pub fn limits(&self) -> Limits {
self.limits.unwrap_or_default().clamped()
}
pub fn with_format_option(mut self, key: impl Into<String>, value: impl ToString) -> MergeOptions {
self.format_options.insert(key.into(), value.to_string());
self
}
pub fn with_format_options(mut self, options: BTreeMap<String, String>) -> MergeOptions {
self.format_options = options;
self
}
pub fn any_translated(doc: &Document) -> bool {
doc.segments().any(|(_, s)| s.has_target())
}
pub fn should_stamp(&self, doc: &Document) -> bool {
self.stamp_lang(doc, Self::any_translated(doc)).is_some()
}
pub fn plausible_lang(code: &str) -> bool {
!code.is_empty() && code.len() <= 64 && code.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'@' | b'.'))
}
pub fn stamp_lang<'a>(&self, doc: &'a Document, translated: bool) -> Option<&'a str> {
doc.target_lang.as_deref().map(str::trim).filter(|t| Self::plausible_lang(t)).filter(|_| translated || self.stamp_target_always)
}
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
#[error("not a {format} file: {msg}")]
Parse {
format: String,
msg: String,
},
#[error("unsupported: {0}")]
Unsupported(String),
#[error("unknown segment {0}")]
UnknownSegment(String),
#[error("segment {0} is locked")]
Locked(String),
#[error("tag {0} is not in the source")]
InventedTag(String),
#[error("tag {0} appears more often than in the source")]
DuplicatedTag(String),
#[error("this skeleton was made by {found}, but this is {expected}; open the file again with the current parser")]
ParserVersion {
found: String,
expected: String,
},
#[error("cannot write: {0}")]
Write(String),
#[error("{reason}")]
Unwritable {
unit: Option<String>,
reason: String,
},
#[error("unit {unit} is a plural form added for another target language; extract the file again for this target")]
TargetChanged {
unit: String,
},
#[error("{0}")]
Limit(LimitError),
#[error("{0}")]
Encoding(String),
#[error("format option {key}: {msg}")]
FormatOption {
key: String,
msg: String,
},
#[error("unknown profile {0:?}")]
UnknownProfile(String),
#[error(transparent)]
Io(#[from] std::io::Error),
}
pub trait Filter: Send + Sync {
fn id(&self) -> &'static str;
fn extensions(&self) -> &'static [&'static str];
fn sniff(&self, bytes: &[u8]) -> bool;
fn bilingual(&self) -> bool {
false
}
fn format_option_keys(&self) -> &'static [FormatOptionKey] {
&[]
}
fn extract(&self, bytes: &[u8], opts: &ExtractOptions) -> Result<Document, Error>;
fn merge_with(&self, doc: &Document, opts: &MergeOptions) -> Result<Vec<u8>, Error>;
fn merge(&self, doc: &Document) -> Result<Vec<u8>, Error> {
self.merge_with(doc, &MergeOptions::default())
}
fn preview(&self, _doc: &Document) -> Option<String> {
None
}
fn render_segment(&self, _doc: &Document, _seg_id: &str) -> Option<String> {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn json_shape_matches_catcore() {
let v = vec![Inline::text("Hi "), Inline::tag("1", TagKind::Open, "<b>")];
let j = serde_json::to_string(&v).unwrap();
assert_eq!(j, r#"[{"text":"Hi "},{"tag":{"id":"1","kind":"open","display":"<b>"}}]"#);
}
#[test]
fn output_joins_segments_and_falls_back_to_source() {
let mut u = Unit::new("p1", vec![]);
u.segments = vec![
Segment { id: "p1#1".into(), source: vec![Inline::text("One.")], target: vec![Inline::text("Uno.")], state: SegState::Draft, origin: None, empty_target: false },
Segment { id: "p1#2".into(), source: vec![Inline::text("Two.")], target: vec![], state: SegState::New, origin: None, empty_target: false },
];
u.separators = vec![" ".into()];
assert_eq!(u.output(), vec![Inline::text("Uno. Two.")]);
assert_eq!(plain_text(&u.source()), "One. Two.");
}
#[test]
fn set_target_takes_the_free_flag_from_the_source() {
let mut d = Document {
format: "test".into(),
name: None,
source_lang: None,
target_lang: None,
granularity: Granularity::Paragraph,
units: vec![Unit::new("u1", vec![Inline::text("Hi "), Inline::free_tag("1", "{name}"), Inline::tag("2", TagKind::Standalone, "%s")])],
skeleton: Skeleton::Text { parts: vec![SkelPart::Unit(0)], encoding: "utf-8".into(), parser: None },
warnings: vec![],
source_encoding: None,
seg_index: SegIndex::default(),
};
let t = vec![
Inline::Tag { id: "2".into(), kind: TagKind::Standalone, display: "%s".into(), free: true },
Inline::text(" hola "),
Inline::tag("1", TagKind::Standalone, "{name}"),
];
d.set_target("u1", t).unwrap();
let got: Vec<bool> = d.units[0].segments[0].target.iter().filter(|i| matches!(i, Inline::Tag { .. })).map(Inline::is_free).collect();
assert_eq!(got, vec![false, true]);
}
#[test]
fn set_target_checks_tags() {
let mut d = Document {
format: "test".into(),
name: None,
source_lang: None,
target_lang: None,
granularity: Granularity::Paragraph,
units: vec![Unit::new("u1", vec![Inline::tag("1", TagKind::Open, "<b>"), Inline::text("x"), Inline::tag("1", TagKind::Close, "</b>")])],
skeleton: Skeleton::Text { parts: vec![SkelPart::Unit(0)], encoding: "utf-8".into(), parser: None },
warnings: vec![],
source_encoding: None,
seg_index: SegIndex::default(),
};
assert!(d.set_target("u1", vec![Inline::text("y")]).is_ok());
assert!(matches!(d.set_target("u1", vec![Inline::tag("2", TagKind::Open, "<i>")]), Err(Error::InventedTag(_))));
assert!(matches!(
d.set_target("u1", vec![Inline::tag("1", TagKind::Open, ""), Inline::tag("1", TagKind::Open, "")]),
Err(Error::DuplicatedTag(_))
));
assert_eq!(d.find("u1").unwrap().1.state, SegState::Draft);
}
fn big_doc(n: usize) -> Document {
Document {
format: "test".into(),
units: (0..n).map(|i| Unit::new(format!("u{i}"), vec![Inline::text(format!("Source {i}"))])).collect(),
skeleton: Skeleton::Text { parts: vec![], encoding: "utf-8".into(), parser: None },
..Default::default()
}
}
#[test]
fn set_targets_sets_many_and_matches_set_target() {
let mut a = big_doc(50);
let mut b = big_doc(50);
a.units[7].translate = false;
b.units[7].translate = false;
for i in (0..50).filter(|i| *i != 7) {
a.set_target(&format!("u{i}"), vec![Inline::text(format!("T{i}"))]).unwrap();
}
b.set_targets((0..50).filter(|i| *i != 7).map(|i| (format!("u{i}"), vec![Inline::text(format!("T{i}"))]))).unwrap();
assert_eq!(a, b);
assert_eq!(b.find("u49").unwrap().1.state, SegState::Draft);
}
#[test]
fn set_target_index_follows_edits_and_stays_out_of_equality() {
let mut d = big_doc(20);
d.set_target("u5", vec![Inline::text("a")]).unwrap();
let e: Document = serde_json::from_str(&serde_json::to_string(&d).unwrap()).unwrap();
assert_eq!(d, e);
assert!(!serde_json::to_string(&d).unwrap().contains("seg_index"));
let moved = d.units.remove(2);
d.set_target("u6", vec![Inline::text("b")]).unwrap();
assert_eq!(d.find("u6").unwrap().1.target, vec![Inline::text("b")]);
assert!(matches!(d.set_target("u2", vec![]), Err(Error::UnknownSegment(_))));
d.units.insert(0, moved);
d.set_target("u2", vec![Inline::text("c")]).unwrap();
assert_eq!(d.units[0].segments[0].target, vec![Inline::text("c")]);
d.units[3].segments[0].id = "renamed".into();
d.set_target("renamed", vec![Inline::text("d")]).unwrap();
assert!(d.find("renamed").unwrap().1.has_target());
let mut c: Document = serde_json::from_str(&serde_json::to_string(&d).unwrap()).unwrap();
c.set_target("u9", vec![Inline::text("x")]).unwrap();
assert_eq!(c.find("u9").unwrap().1.target, vec![Inline::text("x")]);
}
#[test]
fn set_target_index_keeps_first_duplicate_send_sync_and_debug() {
fn send_sync<T: Send + Sync>() {}
send_sync::<Document>();
let mut d = big_doc(6);
d.units[4].segments[0].id = "u1".into();
let before = format!("{d:?}");
d.set_target("u1", vec![Inline::text("a")]).unwrap();
d.set_target("u1", vec![Inline::text("b")]).unwrap();
assert_eq!(d.units[1].segments[0].target, vec![Inline::text("b")]);
assert!(!d.units[4].segments[0].has_target());
let mut fresh = big_doc(6);
fresh.units[4].segments[0].id = "u1".into();
assert_eq!(before, format!("{fresh:?}"));
let mut c = d.clone();
c.set_target("u3", vec![Inline::text("z")]).unwrap();
assert_eq!(c.find("u3").unwrap().1.target, vec![Inline::text("z")]);
assert_eq!(format!("{:?}", d.clone()), format!("{d:?}"));
}
#[test]
fn set_targets_errors_like_set_target_and_keeps_earlier_items() {
let mut d = big_doc(3);
d.units[1].translate = false;
let r = d.set_targets(vec![("u0", vec![Inline::text("a")]), ("u1", vec![Inline::text("b")]), ("u2", vec![Inline::text("c")])]);
assert!(matches!(r, Err(Error::Locked(_))));
assert_eq!(d.units[0].segments[0].target, vec![Inline::text("a")]);
assert!(d.units[2].segments[0].target.is_empty());
assert!(matches!(d.set_targets(vec![("nope", vec![])]), Err(Error::UnknownSegment(_))));
let r = d.set_targets(vec![("u0", vec![Inline::tag("9", TagKind::Open, "<i>")])]);
assert!(matches!(r, Err(Error::InventedTag(_))));
d.set_targets(vec![("u0", vec![Inline::text(" ")])]).unwrap();
assert_eq!(d.units[0].segments[0].state, SegState::New);
}
#[test]
fn set_states_batch() {
let mut d = big_doc(4);
d.set_states((0..4).map(|i| (format!("u{i}"), SegState::Confirmed))).unwrap();
assert!(d.segments().all(|(_, s)| s.state == SegState::Confirmed));
assert!(matches!(d.set_states(vec![("zzz", SegState::New)]), Err(Error::UnknownSegment(_))));
}
#[test]
fn set_targets_100k_is_fast() {
let n = 100_000;
let mut d = big_doc(n);
let t = std::time::Instant::now();
d.set_targets((0..n).map(|i| (format!("u{i}"), vec![Inline::text("x")]))).unwrap();
d.set_states((0..n).map(|i| (format!("u{i}"), SegState::Translated))).unwrap();
let took = t.elapsed();
let limit = if cfg!(debug_assertions) { 10_000 } else { 1_000 };
assert!(took.as_millis() < limit, "100k targets took {took:?}");
assert_eq!(d.units[n - 1].segments[0].state, SegState::Translated);
}
}