1#![warn(missing_docs)]
22
23use serde::{Deserialize, Serialize};
24use std::collections::BTreeMap;
25
26pub mod b64;
27#[doc(hidden)]
29pub mod cldr;
30pub mod codepage;
31pub mod enc;
32pub mod garble;
33pub mod guard;
34#[doc(hidden)]
36pub mod plural_table;
37pub mod profile;
38mod pytables;
39pub mod pytext;
40#[doc(hidden)]
42pub mod work;
43
44pub use encoding_rs;
45pub use guard::{LimitError, LimitKind, Limits};
46pub 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};
47
48pub trait IntoOptionString: sealed::Sealed {
54 fn into_option_string(self) -> Option<String>;
56}
57
58mod sealed {
59 pub trait Sealed {}
60 impl Sealed for &str {}
61 impl Sealed for String {}
62 impl Sealed for &String {}
63 impl Sealed for Option<String> {}
64 impl Sealed for Option<&str> {}
65 impl Sealed for Option<&String> {}
66}
67
68impl IntoOptionString for &str {
69 fn into_option_string(self) -> Option<String> {
70 Some(self.to_string())
71 }
72}
73impl IntoOptionString for String {
74 fn into_option_string(self) -> Option<String> {
75 Some(self)
76 }
77}
78impl IntoOptionString for &String {
79 fn into_option_string(self) -> Option<String> {
80 Some(self.clone())
81 }
82}
83impl IntoOptionString for Option<String> {
84 fn into_option_string(self) -> Option<String> {
85 self
86 }
87}
88impl IntoOptionString for Option<&str> {
89 fn into_option_string(self) -> Option<String> {
90 self.map(str::to_string)
91 }
92}
93impl IntoOptionString for Option<&String> {
94 fn into_option_string(self) -> Option<String> {
95 self.cloned()
96 }
97}
98
99#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
105#[serde(rename_all = "lowercase")]
106pub enum Inline {
107 Text(String),
109 #[non_exhaustive]
114 Tag {
115 id: String,
117 kind: TagKind,
119 display: String,
121 #[serde(default, skip_serializing_if = "is_false")]
123 free: bool,
124 },
125}
126
127fn is_false(b: &bool) -> bool {
128 !*b
129}
130
131impl Inline {
132 pub fn text(s: impl Into<String>) -> Inline {
134 Inline::Text(s.into())
135 }
136 pub fn tag(id: impl Into<String>, kind: TagKind, display: impl Into<String>) -> Inline {
138 Inline::Tag { id: id.into(), kind, display: display.into(), free: false }
139 }
140 pub fn free_tag(id: impl Into<String>, display: impl Into<String>) -> Inline {
142 Inline::Tag { id: id.into(), kind: TagKind::Standalone, display: display.into(), free: true }
143 }
144 pub fn is_free(&self) -> bool {
146 matches!(self, Inline::Tag { free: true, .. })
147 }
148 pub fn with_free(mut self, value: bool) -> Inline {
151 if let Inline::Tag { kind, free, .. } = &mut self {
152 *free = value && *kind == TagKind::Standalone;
153 }
154 self
155 }
156}
157
158#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
160#[serde(rename_all = "lowercase")]
161pub enum TagKind {
162 Open,
164 Close,
166 Standalone,
168}
169
170#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
174#[non_exhaustive]
175pub struct CodeData {
176 pub open: Option<String>,
178 pub close: Option<String>,
180 pub standalone: Option<String>,
182 pub label: Option<String>,
184}
185
186impl CodeData {
187 pub fn new() -> CodeData {
189 CodeData::default()
190 }
191 pub fn paired(open: impl Into<String>, close: impl Into<String>) -> CodeData {
193 let (open, close): (String, String) = (open.into(), close.into());
194 CodeData::new().with_open(open).with_close(close)
195 }
196 pub fn standalone(markup: impl Into<String>) -> CodeData {
198 let markup: String = markup.into();
199 CodeData::new().with_standalone(markup)
200 }
201 pub fn with_open(mut self, open: impl IntoOptionString) -> CodeData {
203 self.open = open.into_option_string();
204 self
205 }
206 pub fn with_close(mut self, close: impl IntoOptionString) -> CodeData {
208 self.close = close.into_option_string();
209 self
210 }
211 pub fn with_standalone(mut self, standalone: impl IntoOptionString) -> CodeData {
213 self.standalone = standalone.into_option_string();
214 self
215 }
216 pub fn with_label(mut self, label: impl IntoOptionString) -> CodeData {
218 self.label = label.into_option_string();
219 self
220 }
221}
222
223#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
226#[non_exhaustive]
227pub enum SegState {
228 #[default]
230 #[serde(rename = "new")]
231 New,
232 #[serde(rename = "draft")]
234 Draft,
235 #[serde(rename = "translated")]
237 Translated,
238 #[serde(rename = "confirmed")]
240 Confirmed,
241 #[serde(rename = "reviewed")]
243 Reviewed,
244 #[serde(rename = "signed-off")]
246 SignedOff,
247 #[serde(rename = "rejected")]
249 Rejected,
250 #[serde(rename = "locked")]
252 Locked,
253}
254
255impl SegState {
256 pub fn rank(self) -> u8 {
259 match self {
260 SegState::New => 0,
261 SegState::Rejected => 1,
262 SegState::Draft => 2,
263 SegState::Translated => 3,
264 SegState::Confirmed => 4,
265 SegState::Reviewed => 5,
266 SegState::SignedOff => 6,
267 SegState::Locked => 7,
268 }
269 }
270
271 pub fn from_rank(r: u8) -> SegState {
273 match r {
274 0 => SegState::New,
275 1 => SegState::Rejected,
276 2 => SegState::Draft,
277 3 => SegState::Translated,
278 4 => SegState::Confirmed,
279 5 => SegState::Reviewed,
280 6 => SegState::SignedOff,
281 _ => SegState::Locked,
282 }
283 }
284
285 pub fn is_accepted(self) -> bool {
287 self.rank() >= SegState::Translated.rank()
288 }
289}
290
291#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
294#[serde(rename_all = "lowercase")]
295#[non_exhaustive]
296pub enum OriginKind {
297 Tm,
299 Mt,
301 Ai,
303 Human,
305 #[default]
307 #[serde(other)]
308 Other,
309}
310
311#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
313#[non_exhaustive]
314pub struct Origin {
315 pub kind: OriginKind,
317 #[serde(default, skip_serializing_if = "Option::is_none")]
319 pub name: Option<String>,
320 #[serde(default, skip_serializing_if = "Option::is_none")]
322 pub match_pct: Option<u8>,
323}
324
325impl Origin {
326 pub fn new(kind: OriginKind) -> Origin {
328 Origin { kind, name: None, match_pct: None }
329 }
330 pub fn with_match(mut self, pct: u8) -> Origin {
332 self.match_pct = Some(pct);
333 self
334 }
335 pub fn with_match_pct(mut self, pct: Option<u8>) -> Origin {
337 self.match_pct = pct;
338 self
339 }
340 pub fn with_name(mut self, name: impl IntoOptionString) -> Origin {
342 self.name = name.into_option_string();
343 self
344 }
345}
346
347#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
350#[non_exhaustive]
351pub struct Segment {
352 pub id: String,
354 pub source: Vec<Inline>,
356 #[serde(default)]
358 pub target: Vec<Inline>,
359 #[serde(default)]
361 pub state: SegState,
362 #[serde(default, skip_serializing_if = "Option::is_none")]
364 pub origin: Option<Origin>,
365 #[serde(default, skip_serializing_if = "is_false")]
372 pub empty_target: bool,
373}
374
375impl Segment {
376 pub fn new(id: impl Into<String>, source: Vec<Inline>) -> Segment {
378 Segment { id: id.into(), source, target: vec![], state: SegState::New, origin: None, empty_target: false }
379 }
380 pub fn has_target(&self) -> bool {
382 !self.target.is_empty() || self.empty_target
383 }
384 pub fn output(&self) -> &[Inline] {
386 if self.has_target() {
387 &self.target
388 } else {
389 &self.source
390 }
391 }
392 pub fn with_empty_target(mut self, empty_target: bool) -> Segment {
394 self.empty_target = empty_target;
395 if empty_target {
396 self.target.clear();
397 }
398 self
399 }
400 pub fn with_target(mut self, target: Vec<Inline>) -> Segment {
402 self.target = target;
403 self
404 }
405 pub fn with_state(mut self, state: SegState) -> Segment {
407 self.state = state;
408 self
409 }
410 pub fn with_origin(mut self, origin: impl Into<Option<Origin>>) -> Segment {
412 self.origin = origin.into();
413 self
414 }
415}
416
417#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
420#[non_exhaustive]
421pub struct Note {
422 #[serde(default, skip_serializing_if = "Option::is_none")]
424 pub author: Option<String>,
425 pub text: String,
427 #[serde(default, skip_serializing_if = "Option::is_none")]
429 pub kind: Option<String>,
430}
431
432impl Note {
433 pub fn new(text: impl Into<String>) -> Note {
435 Note { author: None, text: text.into(), kind: None }
436 }
437 pub fn with_author(mut self, author: impl IntoOptionString) -> Note {
439 self.author = author.into_option_string();
440 self
441 }
442 pub fn with_kind(mut self, kind: impl IntoOptionString) -> Note {
444 self.kind = kind.into_option_string();
445 self
446 }
447}
448
449#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
452#[non_exhaustive]
453pub struct UnitContext {
454 pub kind: Option<String>,
457 pub style: Option<String>,
459 pub key: Option<String>,
461 pub heading: Option<String>,
463 pub location: Option<String>,
465 pub max_len: Option<usize>,
467 #[serde(default)]
469 pub notes: Vec<String>,
470 #[serde(default)]
472 pub extra: BTreeMap<String, String>,
473}
474
475impl UnitContext {
476 pub fn new() -> UnitContext {
478 UnitContext::default()
479 }
480 pub fn with_kind(mut self, kind: impl IntoOptionString) -> UnitContext {
482 self.kind = kind.into_option_string();
483 self
484 }
485 pub fn with_style(mut self, style: impl IntoOptionString) -> UnitContext {
487 self.style = style.into_option_string();
488 self
489 }
490 pub fn with_key(mut self, key: impl IntoOptionString) -> UnitContext {
492 self.key = key.into_option_string();
493 self
494 }
495 pub fn with_heading(mut self, heading: impl IntoOptionString) -> UnitContext {
497 self.heading = heading.into_option_string();
498 self
499 }
500 pub fn with_location(mut self, location: impl IntoOptionString) -> UnitContext {
502 self.location = location.into_option_string();
503 self
504 }
505 pub fn with_max_len(mut self, max_len: Option<usize>) -> UnitContext {
507 self.max_len = max_len;
508 self
509 }
510 pub fn with_notes(mut self, notes: Vec<String>) -> UnitContext {
512 self.notes = notes;
513 self
514 }
515 pub fn with_extra(mut self, extra: BTreeMap<String, String>) -> UnitContext {
517 self.extra = extra;
518 self
519 }
520}
521
522#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
525#[serde(from = "UnitRepr")]
526#[non_exhaustive]
527pub struct Unit {
528 pub id: String,
530 pub segments: Vec<Segment>,
532 #[serde(default)]
535 pub separators: Vec<String>,
536 #[serde(default)]
538 pub codes: BTreeMap<String, CodeData>,
539 #[serde(default)]
541 pub context: UnitContext,
542 #[serde(default = "yes")]
544 pub translate: bool,
545 #[serde(default, skip_serializing_if = "Vec::is_empty")]
547 pub notes: Vec<Note>,
548 #[serde(default, skip_serializing_if = "Option::is_none")]
551 pub lock_reason: Option<String>,
552 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
557 pub hidden: BTreeMap<String, String>,
558}
559
560fn yes() -> bool {
561 true
562}
563
564#[derive(Deserialize)]
566struct UnitRepr {
567 id: String,
568 segments: Vec<Segment>,
569 #[serde(default)]
570 separators: Vec<String>,
571 #[serde(default)]
572 codes: BTreeMap<String, CodeData>,
573 #[serde(default)]
574 context: UnitContext,
575 #[serde(default = "yes")]
576 translate: bool,
577 #[serde(default)]
578 notes: Vec<Note>,
579 #[serde(default)]
580 lock_reason: Option<String>,
581 #[serde(default)]
582 hidden: BTreeMap<String, String>,
583}
584
585impl From<UnitRepr> for Unit {
586 fn from(r: UnitRepr) -> Unit {
587 let mut hidden = r.hidden;
588 let mut codes = BTreeMap::new();
589 for (k, c) in r.codes {
590 match k.strip_prefix('~') {
591 Some(name) if c.open.is_none() && c.close.is_none() => {
593 hidden.entry(name.to_string()).or_insert_with(|| c.standalone.or(c.label).unwrap_or_default());
594 }
595 _ => {
596 codes.insert(k, c);
597 }
598 }
599 }
600 Unit {
601 id: r.id,
602 segments: r.segments,
603 separators: r.separators,
604 codes,
605 context: r.context,
606 translate: r.translate,
607 notes: r.notes,
608 lock_reason: r.lock_reason,
609 hidden,
610 }
611 }
612}
613
614impl Unit {
615 pub fn new(id: impl Into<String>, source: Vec<Inline>) -> Unit {
617 let id = id.into();
618 let seg = Segment::new(id.clone(), source);
619 Unit::from_segments(id, vec![seg])
620 }
621
622 pub fn from_segments(id: impl Into<String>, segments: Vec<Segment>) -> Unit {
624 Unit {
625 separators: vec![String::new(); segments.len().saturating_sub(1)],
626 segments,
627 id: id.into(),
628 codes: BTreeMap::new(),
629 context: UnitContext::default(),
630 translate: true,
631 notes: vec![],
632 lock_reason: None,
633 hidden: BTreeMap::new(),
634 }
635 }
636 pub fn hidden(&self, key: &str) -> Option<&str> {
638 self.hidden.get(key).map(String::as_str)
639 }
640 pub fn set_hidden(&mut self, key: impl Into<String>, value: impl Into<String>) {
642 self.hidden.insert(key.into(), value.into());
643 }
644 pub fn has_hidden(&self, key: &str) -> bool {
646 self.hidden.contains_key(key)
647 }
648 pub fn with_hidden(mut self, key: impl Into<String>, value: impl Into<String>) -> Unit {
650 self.set_hidden(key, value);
651 self
652 }
653 pub fn with_separators(mut self, separators: Vec<String>) -> Unit {
655 self.separators = separators;
656 self
657 }
658 pub fn with_codes(mut self, codes: BTreeMap<String, CodeData>) -> Unit {
660 self.codes = codes;
661 self
662 }
663 pub fn with_code(mut self, id: impl Into<String>, code: CodeData) -> Unit {
665 self.codes.insert(id.into(), code);
666 self
667 }
668 pub fn with_context(mut self, context: UnitContext) -> Unit {
670 self.context = context;
671 self
672 }
673 pub fn with_translate(mut self, translate: bool) -> Unit {
675 self.translate = translate;
676 self
677 }
678 pub fn with_notes(mut self, notes: Vec<Note>) -> Unit {
680 self.notes = notes;
681 self
682 }
683 pub fn with_lock_reason(mut self, reason: impl IntoOptionString) -> Unit {
685 self.lock_reason = reason.into_option_string();
686 self
687 }
688
689 pub fn source(&self) -> Vec<Inline> {
691 self.join(|s| &s.source)
692 }
693
694 pub fn output(&self) -> Vec<Inline> {
697 self.join(|s| if s.has_target() { &s.target } else { &s.source })
698 }
699
700 pub fn is_translated(&self) -> bool {
702 self.translate && self.segments.iter().any(Segment::has_target)
703 }
704
705 fn join<'a>(&'a self, pick: impl Fn(&'a Segment) -> &'a Vec<Inline>) -> Vec<Inline> {
706 let mut out = Vec::new();
707 for (i, seg) in self.segments.iter().enumerate() {
708 if i > 0 {
709 if let Some(sep) = self.separators.get(i - 1) {
710 if !sep.is_empty() {
711 out.push(Inline::Text(sep.clone()));
712 }
713 }
714 }
715 out.extend(pick(seg).iter().cloned());
716 }
717 merge_text(out)
718 }
719}
720
721pub fn merge_text(v: Vec<Inline>) -> Vec<Inline> {
723 let mut out: Vec<Inline> = Vec::with_capacity(v.len());
724 for i in v {
725 match (out.last_mut(), i) {
726 (Some(Inline::Text(a)), Inline::Text(b)) => a.push_str(&b),
727 (_, Inline::Text(t)) if t.is_empty() => {}
728 (_, x) => out.push(x),
729 }
730 }
731 out
732}
733
734pub fn plain_text(v: &[Inline]) -> String {
736 v.iter()
737 .filter_map(|i| match i {
738 Inline::Text(t) => Some(t.as_str()),
739 _ => None,
740 })
741 .collect()
742}
743
744#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
747#[serde(rename_all = "lowercase")]
748pub enum SkelPart {
749 Raw(String),
751 Unit(usize),
753}
754
755#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
757#[serde(rename_all = "lowercase")]
758pub enum ZipData {
759 Raw(#[serde(with = "b64")] Vec<u8>),
761 Parts(Vec<SkelPart>),
763}
764
765#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
767#[non_exhaustive]
768pub struct ZipEntry {
769 pub name: String,
771 pub data: ZipData,
773}
774
775impl ZipEntry {
776 pub fn new(name: impl Into<String>, data: ZipData) -> ZipEntry {
778 ZipEntry { name: name.into(), data }
779 }
780 pub fn raw(name: impl Into<String>, bytes: Vec<u8>) -> ZipEntry {
782 ZipEntry::new(name, ZipData::Raw(bytes))
783 }
784}
785
786#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
790#[non_exhaustive]
791pub struct ParserInfo {
792 pub name: String,
794 pub version: String,
796 #[serde(default = "legacy_schema")]
798 pub schema: u32,
799}
800
801fn legacy_schema() -> u32 {
802 1
803}
804
805impl ParserInfo {
806 pub fn new(name: impl Into<String>, version: impl Into<String>, schema: u32) -> ParserInfo {
808 ParserInfo { name: name.into(), version: version.into(), schema }
809 }
810
811 pub fn compatible_with(&self, current: &ParserInfo) -> bool {
814 self.name == current.name && self.schema <= current.schema
815 }
816}
817
818#[allow(clippy::crate_in_macro_def)]
824#[macro_export]
825macro_rules! parser_info {
826 () => {
827 $crate::parser_info!(crate::SKELETON_SCHEMA)
828 };
829 ($schema:expr) => {
830 $crate::ParserInfo::new(env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"), $schema)
831 };
832}
833
834pub fn check_parser(doc: &Document, current: &ParserInfo) -> Result<(), Error> {
838 check_parser_min(doc, current, 1)
839}
840
841pub fn check_parser_min(doc: &Document, current: &ParserInfo, oldest: u32) -> Result<(), Error> {
843 match doc.skeleton.parser() {
844 Some(found) if !found.compatible_with(current) || found.schema < oldest => Err(Error::ParserVersion {
845 found: format!("{} {} (skeleton schema {})", found.name, found.version, found.schema),
846 expected: if found.name != current.name {
847 current.name.clone()
848 } else if found.schema > current.schema {
849 format!("{} {} (reads skeleton schema {} and older)", current.name, current.version, current.schema)
850 } else {
851 format!("{} {} (reads skeleton schema {} to {})", current.name, current.version, oldest, current.schema)
852 },
853 }),
854 _ => Ok(()),
855 }
856}
857
858#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
862#[serde(rename_all = "lowercase")]
863#[non_exhaustive]
864pub enum Skeleton {
865 Text {
867 parts: Vec<SkelPart>,
869 encoding: String,
871 #[serde(default, skip_serializing_if = "Option::is_none")]
873 parser: Option<ParserInfo>,
874 },
875 Zip {
877 entries: Vec<ZipEntry>,
879 #[serde(default, skip_serializing_if = "Option::is_none")]
881 parser: Option<ParserInfo>,
882 },
883 Binary {
886 #[serde(with = "b64")]
888 data: Vec<u8>,
889 #[serde(default, skip_serializing_if = "Option::is_none")]
891 parser: Option<ParserInfo>,
892 },
893}
894
895impl Default for Skeleton {
896 fn default() -> Self {
898 Skeleton::Text { parts: Vec::new(), encoding: "utf-8".into(), parser: None }
899 }
900}
901
902impl Skeleton {
903 pub fn text(parts: Vec<SkelPart>, encoding: impl Into<String>, parser: ParserInfo) -> Skeleton {
905 Skeleton::Text { parts, encoding: encoding.into(), parser: Some(parser) }
906 }
907 pub fn zip(entries: Vec<ZipEntry>, parser: ParserInfo) -> Skeleton {
909 Skeleton::Zip { entries, parser: Some(parser) }
910 }
911 pub fn binary(data: Vec<u8>, parser: ParserInfo) -> Skeleton {
913 Skeleton::Binary { data, parser: Some(parser) }
914 }
915 pub fn parser(&self) -> Option<&ParserInfo> {
917 match self {
918 Skeleton::Text { parser, .. } | Skeleton::Zip { parser, .. } | Skeleton::Binary { parser, .. } => parser.as_ref(),
919 }
920 }
921}
922
923#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
925#[serde(rename_all = "lowercase")]
926#[non_exhaustive]
927pub enum Granularity {
928 #[default]
930 Sentence,
931 Paragraph,
933 Document,
936}
937
938#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
942#[non_exhaustive]
943pub struct Document {
944 pub format: String,
946 pub name: Option<String>,
948 pub source_lang: Option<String>,
950 pub target_lang: Option<String>,
952 pub granularity: Granularity,
954 pub units: Vec<Unit>,
956 pub skeleton: Skeleton,
958 #[serde(default, skip_serializing_if = "Vec::is_empty")]
961 pub warnings: Vec<Warning>,
962 #[serde(default, skip_serializing_if = "Option::is_none")]
966 pub source_encoding: Option<String>,
967 #[serde(skip)]
969 seg_index: SegIndex,
970}
971
972#[derive(Default)]
975struct SegIndex(Option<std::collections::HashMap<String, (usize, usize)>>);
976
977impl Clone for SegIndex {
980 fn clone(&self) -> SegIndex {
981 SegIndex(None)
982 }
983}
984
985impl std::fmt::Debug for SegIndex {
987 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
988 f.write_str("SegIndex")
989 }
990}
991
992impl PartialEq for SegIndex {
993 fn eq(&self, _: &SegIndex) -> bool {
994 true
995 }
996}
997
998impl Eq for SegIndex {}
999
1000#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1003#[non_exhaustive]
1004pub struct Warning {
1005 pub kind: String,
1007 #[serde(default, skip_serializing_if = "String::is_empty")]
1009 pub part: String,
1010 pub message: String,
1012}
1013
1014impl Warning {
1015 pub fn new(kind: impl Into<String>, part: impl Into<String>, message: impl Into<String>) -> Warning {
1017 Warning { kind: kind.into(), part: part.into(), message: message.into() }
1018 }
1019}
1020
1021impl Document {
1022 pub fn new(format: impl Into<String>, units: Vec<Unit>, skeleton: Skeleton) -> Document {
1025 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() }
1026 }
1027 pub fn with_options(mut self, opts: &ExtractOptions) -> Document {
1029 self.source_lang = opts.source_lang.clone();
1030 self.target_lang = opts.target_lang.clone();
1031 self.granularity = opts.granularity;
1032 self
1033 }
1034 pub fn with_name(mut self, name: impl IntoOptionString) -> Document {
1036 self.name = name.into_option_string();
1037 self
1038 }
1039 pub fn with_source_lang(mut self, lang: impl IntoOptionString) -> Document {
1041 self.source_lang = lang.into_option_string();
1042 self
1043 }
1044 pub fn with_target_lang(mut self, lang: impl IntoOptionString) -> Document {
1046 self.target_lang = lang.into_option_string();
1047 self
1048 }
1049 pub fn with_granularity(mut self, granularity: Granularity) -> Document {
1051 self.granularity = granularity;
1052 self
1053 }
1054 pub fn detected_source_encoding(&self) -> Option<String> {
1058 let encoding = match &self.skeleton {
1059 Skeleton::Text { encoding, .. } => encoding.as_str(),
1060 Skeleton::Binary { data, .. } if matches!(self.format.as_str(), "markdown" | "po" | "srt" | "vtt") => enc::locos_skeleton_parts(data)?.0,
1062 _ => return None,
1063 };
1064 let base = encoding.split(';').next().unwrap_or("").to_ascii_lowercase();
1065 let base = base.strip_suffix("-bom").or_else(|| base.strip_suffix("-nobom")).unwrap_or(&base).to_string();
1066 (!matches!(base.as_str(), "" | "utf-8" | "utf8" | "bplist")).then_some(base)
1067 }
1068 pub fn with_warnings(mut self, warnings: Vec<Warning>) -> Document {
1070 self.warnings = warnings;
1071 self
1072 }
1073
1074 pub fn segments(&self) -> impl Iterator<Item = (&Unit, &Segment)> {
1076 self.units.iter().flat_map(|u| u.segments.iter().map(move |s| (u, s)))
1077 }
1078
1079 pub fn segment_count(&self) -> usize {
1081 self.units.iter().map(|u| u.segments.len()).sum()
1082 }
1083
1084 pub fn find(&self, seg_id: &str) -> Option<(&Unit, &Segment)> {
1086 self.segments().find(|(_, s)| s.id == seg_id)
1087 }
1088
1089 pub fn set_target(&mut self, seg_id: &str, target: Vec<Inline>) -> Result<(), Error> {
1099 let at = self.locate(seg_id).ok_or_else(|| Error::UnknownSegment(seg_id.to_string()))?;
1100 self.apply_target(at, seg_id, target, false)
1101 }
1102
1103 pub fn set_target_repeating(&mut self, seg_id: &str, target: Vec<Inline>) -> Result<(), Error> {
1106 let at = self.locate(seg_id).ok_or_else(|| Error::UnknownSegment(seg_id.to_string()))?;
1107 self.apply_target(at, seg_id, target, true)
1108 }
1109
1110 pub(crate) fn locate(&mut self, seg_id: &str) -> Option<(usize, usize)> {
1112 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);
1113 if let Some(at) = self.seg_index.0.as_ref().and_then(|m| m.get(seg_id)).copied() {
1114 if valid(&self.units, at) {
1115 return Some(at);
1116 }
1117 }
1118 let fresh = self.segment_index();
1120 let at = fresh.get(seg_id).copied();
1121 self.seg_index = SegIndex(Some(fresh));
1122 at
1123 }
1124
1125 pub fn set_targets<I, S>(&mut self, items: I) -> Result<(), Error>
1130 where
1131 I: IntoIterator<Item = (S, Vec<Inline>)>,
1132 S: AsRef<str>,
1133 {
1134 let index = self.segment_index();
1135 for (id, target) in items {
1136 let id = id.as_ref();
1137 let at = *index.get(id).ok_or_else(|| Error::UnknownSegment(id.to_string()))?;
1138 self.apply_target(at, id, target, false)?;
1139 }
1140 Ok(())
1141 }
1142
1143 pub fn set_states<I, S>(&mut self, items: I) -> Result<(), Error>
1145 where
1146 I: IntoIterator<Item = (S, SegState)>,
1147 S: AsRef<str>,
1148 {
1149 let index = self.segment_index();
1150 for (id, state) in items {
1151 let id = id.as_ref();
1152 let (ui, si) = *index.get(id).ok_or_else(|| Error::UnknownSegment(id.to_string()))?;
1153 self.units[ui].segments[si].state = state;
1154 }
1155 Ok(())
1156 }
1157
1158 fn segment_index(&self) -> std::collections::HashMap<String, (usize, usize)> {
1160 let mut m = std::collections::HashMap::with_capacity(self.segment_count());
1161 for (ui, u) in self.units.iter().enumerate() {
1162 for (si, s) in u.segments.iter().enumerate() {
1163 m.entry(s.id.clone()).or_insert((ui, si));
1164 }
1165 }
1166 m
1167 }
1168
1169 fn apply_target(&mut self, (ui, si): (usize, usize), seg_id: &str, target: Vec<Inline>, repeat_standalone: bool) -> Result<(), Error> {
1170 let unit = &mut self.units[ui];
1171 if !unit.translate {
1172 return Err(Error::Locked(seg_id.to_string()));
1173 }
1174 let seg = &mut unit.segments[si];
1175 if seg.state == SegState::Locked {
1176 return Err(Error::Locked(seg_id.to_string()));
1177 }
1178 check_tags(&seg.source, &target, repeat_standalone)?;
1179 let target = merge_text(
1182 target
1183 .into_iter()
1184 .map(|i| match i {
1185 Inline::Tag { id, kind, display, .. } => {
1186 let free = kind == TagKind::Standalone
1187 && seg.source.iter().any(|s| matches!(s, Inline::Tag { id: sid, kind: TagKind::Standalone, free: true, .. } if *sid == id));
1188 Inline::Tag { id, kind, display, free }
1189 }
1190 t => t,
1191 })
1192 .collect(),
1193 );
1194 let empty = plain_text(&target).trim().is_empty() && !target.iter().any(|i| matches!(i, Inline::Tag { .. }));
1195 seg.target = if empty { vec![] } else { target };
1196 seg.empty_target = false;
1197 seg.state = if seg.target.is_empty() { SegState::New } else { SegState::Draft };
1198 Ok(())
1199 }
1200
1201 pub fn set_target_empty(&mut self, seg_id: &str) -> Result<(), Error> {
1205 let (ui, si) = self
1206 .units
1207 .iter()
1208 .enumerate()
1209 .find_map(|(ui, u)| u.segments.iter().position(|s| s.id == seg_id).map(|si| (ui, si)))
1210 .ok_or_else(|| Error::UnknownSegment(seg_id.to_string()))?;
1211 let unit = &mut self.units[ui];
1212 if !unit.translate {
1213 return Err(Error::Locked(seg_id.to_string()));
1214 }
1215 let seg = &mut unit.segments[si];
1216 if seg.state == SegState::Locked {
1217 return Err(Error::Locked(seg_id.to_string()));
1218 }
1219 seg.target.clear();
1220 seg.empty_target = true;
1221 seg.state = SegState::Draft;
1222 Ok(())
1223 }
1224
1225 pub fn set_state(&mut self, seg_id: &str, state: SegState) -> Result<(), Error> {
1227 let seg = self
1228 .units
1229 .iter_mut()
1230 .flat_map(|u| u.segments.iter_mut())
1231 .find(|s| s.id == seg_id)
1232 .ok_or_else(|| Error::UnknownSegment(seg_id.to_string()))?;
1233 seg.state = state;
1234 Ok(())
1235 }
1236}
1237
1238fn check_tags(source: &[Inline], target: &[Inline], repeat_standalone: bool) -> Result<(), Error> {
1239 let mut allowed: BTreeMap<(&str, TagKind), usize> = BTreeMap::new();
1240 for i in source {
1241 if let Inline::Tag { id, kind, .. } = i {
1242 *allowed.entry((id.as_str(), *kind)).or_default() += 1;
1243 }
1244 }
1245 let mut used: BTreeMap<(&str, TagKind), usize> = BTreeMap::new();
1246 for i in target {
1247 if let Inline::Tag { id, kind, .. } = i {
1248 let n = used.entry((id.as_str(), *kind)).or_default();
1249 *n += 1;
1250 match allowed.get(&(id.as_str(), *kind)) {
1251 None => return Err(Error::InventedTag(id.clone())),
1252 Some(max) if *n > *max && !(repeat_standalone && *kind == TagKind::Standalone) => return Err(Error::DuplicatedTag(id.clone())),
1253 _ => {}
1254 }
1255 }
1256 }
1257 Ok(())
1258}
1259
1260#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1263#[non_exhaustive]
1264pub struct ExtractOptions {
1265 pub source_lang: Option<String>,
1267 pub target_lang: Option<String>,
1269 pub granularity: Granularity,
1271 pub include_locked: bool,
1273 #[serde(default, skip_serializing_if = "Option::is_none")]
1275 pub limits: Option<Limits>,
1276 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1281 pub format_options: BTreeMap<String, String>,
1282 #[serde(default, skip_serializing_if = "Option::is_none")]
1285 pub profile: Option<String>,
1286}
1287
1288impl ExtractOptions {
1289 pub fn with_profile(mut self, profile: impl IntoOptionString) -> ExtractOptions {
1291 self.profile = profile.into_option_string();
1292 self
1293 }
1294 pub fn is_profile(&self, name: &str) -> bool {
1296 self.profile.as_deref() == Some(name)
1297 }
1298 pub fn new() -> ExtractOptions {
1300 ExtractOptions::default()
1301 }
1302 pub fn with_source_lang(mut self, lang: impl IntoOptionString) -> ExtractOptions {
1304 self.source_lang = lang.into_option_string();
1305 self
1306 }
1307 pub fn with_target_lang(mut self, lang: impl IntoOptionString) -> ExtractOptions {
1309 self.target_lang = lang.into_option_string();
1310 self
1311 }
1312 pub fn with_granularity(mut self, granularity: Granularity) -> ExtractOptions {
1314 self.granularity = granularity;
1315 self
1316 }
1317 pub fn with_include_locked(mut self, include_locked: bool) -> ExtractOptions {
1319 self.include_locked = include_locked;
1320 self
1321 }
1322 pub fn with_limits(mut self, limits: impl Into<Option<Limits>>) -> ExtractOptions {
1324 self.limits = limits.into();
1325 self
1326 }
1327 pub fn with_format_option(mut self, key: impl Into<String>, value: impl ToString) -> ExtractOptions {
1329 self.format_options.insert(key.into(), value.to_string());
1330 self
1331 }
1332 pub fn with_format_options(mut self, options: BTreeMap<String, String>) -> ExtractOptions {
1334 self.format_options = options;
1335 self
1336 }
1337
1338 pub fn format_option(&self, key: &str) -> Option<&str> {
1340 self.format_options.get(key).map(String::as_str)
1341 }
1342
1343 pub fn format_flag(&self, key: &str) -> Option<bool> {
1346 match self.format_option(key)?.trim().to_ascii_lowercase().as_str() {
1347 "true" | "1" | "yes" | "on" => Some(true),
1348 "false" | "0" | "no" | "off" => Some(false),
1349 _ => None,
1350 }
1351 }
1352
1353 pub fn format_int(&self, key: &str) -> Option<i64> {
1355 self.format_option(key)?.trim().parse().ok()
1356 }
1357
1358 pub fn limits(&self) -> Limits {
1360 self.limits.unwrap_or_default()
1361 }
1362}
1363
1364#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1366#[non_exhaustive]
1367pub enum OptionKind {
1368 Bool,
1370 Int,
1372 Text,
1374}
1375
1376#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1379#[non_exhaustive]
1380pub struct FormatOptionKey {
1381 pub key: &'static str,
1383 pub kind: OptionKind,
1385 pub help: &'static str,
1387}
1388
1389impl FormatOptionKey {
1390 pub const fn new(key: &'static str, kind: OptionKind, help: &'static str) -> FormatOptionKey {
1392 FormatOptionKey { key, kind, help }
1393 }
1394 pub const fn bool(key: &'static str, help: &'static str) -> FormatOptionKey {
1396 FormatOptionKey::new(key, OptionKind::Bool, help)
1397 }
1398 pub const fn int(key: &'static str, help: &'static str) -> FormatOptionKey {
1400 FormatOptionKey::new(key, OptionKind::Int, help)
1401 }
1402 pub const fn text(key: &'static str, help: &'static str) -> FormatOptionKey {
1404 FormatOptionKey::new(key, OptionKind::Text, help)
1405 }
1406
1407 pub fn check(&self, value: &str) -> Result<(), Error> {
1409 let v = value.trim();
1410 let ok = match self.kind {
1411 OptionKind::Bool => matches!(v.to_ascii_lowercase().as_str(), "true" | "1" | "yes" | "on" | "false" | "0" | "no" | "off"),
1412 OptionKind::Int => v.parse::<i64>().is_ok(),
1413 OptionKind::Text => true,
1414 };
1415 if ok {
1416 Ok(())
1417 } else {
1418 let want = match self.kind {
1419 OptionKind::Bool => "true or false",
1420 OptionKind::Int => "an integer",
1421 OptionKind::Text => "text",
1422 };
1423 Err(Error::FormatOption { key: self.key.to_string(), msg: format!("the value {value:?} is not {want}") })
1424 }
1425 }
1426}
1427
1428pub fn check_format_options(opts: &ExtractOptions, known: &[FormatOptionKey]) -> Result<(), Error> {
1432 check_option_map(&opts.format_options, known)
1433}
1434
1435pub fn check_option_map(options: &BTreeMap<String, String>, known: &[FormatOptionKey]) -> Result<(), Error> {
1437 for (k, v) in options {
1438 match known.iter().find(|f| f.key == k) {
1439 Some(f) => f.check(v)?,
1440 None => {
1441 let family = k.split('.').next().unwrap_or("");
1442 let same: Vec<&str> = known.iter().filter(|f| f.key.split('.').next() == Some(family)).map(|f| f.key).collect();
1443 let msg = if same.is_empty() { "no format has this option".to_string() } else { format!("unknown option; {family} knows {}", same.join(", ")) };
1444 return Err(Error::FormatOption { key: k.clone(), msg });
1445 }
1446 }
1447 }
1448 Ok(())
1449}
1450
1451pub fn check_own_options<F: Filter + ?Sized>(filter: &F, options: &BTreeMap<String, String>) -> Result<(), Error> {
1458 if options.is_empty() {
1459 return Ok(());
1460 }
1461 let keys = filter.format_option_keys();
1462 let id = filter.id();
1463 let family = |k: &str| k.split('.').next().unwrap_or("").to_string();
1464 for (k, v) in options {
1465 let fam = family(k);
1466 if fam != id && !keys.iter().any(|f| family(f.key) == fam) {
1467 continue;
1468 }
1469 match keys.iter().find(|f| f.key == k) {
1470 Some(f) => f.check(v)?,
1471 None => {
1472 let mine: Vec<&str> = keys.iter().map(|f| f.key).collect();
1473 let msg = if mine.is_empty() { format!("{id} has no options") } else { format!("unknown option; {id} knows {}", mine.join(", ")) };
1474 return Err(Error::FormatOption { key: k.clone(), msg });
1475 }
1476 }
1477 }
1478 Ok(())
1479}
1480
1481#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
1483#[non_exhaustive]
1484pub enum OutputEncoding {
1485 #[default]
1487 #[serde(rename = "keep")]
1488 Keep,
1489 #[serde(rename = "utf-8", alias = "utf8")]
1492 Utf8,
1493}
1494
1495#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1505#[serde(default, deny_unknown_fields)]
1506#[non_exhaustive]
1507pub struct MergeOptions {
1508 pub output_encoding: OutputEncoding,
1510 pub stamp_target_always: bool,
1512 #[serde(skip_serializing_if = "Option::is_none")]
1514 pub profile: Option<String>,
1515 #[serde(skip_serializing_if = "BTreeMap::is_empty")]
1517 pub format_options: BTreeMap<String, String>,
1518}
1519
1520impl MergeOptions {
1521 pub fn new() -> MergeOptions {
1523 MergeOptions::default()
1524 }
1525 pub fn with_output_encoding(mut self, output_encoding: OutputEncoding) -> MergeOptions {
1527 self.output_encoding = output_encoding;
1528 self
1529 }
1530 pub fn with_stamp_target_always(mut self, stamp_target_always: bool) -> MergeOptions {
1532 self.stamp_target_always = stamp_target_always;
1533 self
1534 }
1535 pub fn with_profile(mut self, profile: impl IntoOptionString) -> MergeOptions {
1537 self.profile = profile.into_option_string();
1538 self
1539 }
1540 pub fn is_profile(&self, name: &str) -> bool {
1542 self.profile.as_deref() == Some(name)
1543 }
1544 pub fn with_format_option(mut self, key: impl Into<String>, value: impl ToString) -> MergeOptions {
1546 self.format_options.insert(key.into(), value.to_string());
1547 self
1548 }
1549 pub fn with_format_options(mut self, options: BTreeMap<String, String>) -> MergeOptions {
1551 self.format_options = options;
1552 self
1553 }
1554
1555 pub fn any_translated(doc: &Document) -> bool {
1557 doc.segments().any(|(_, s)| s.has_target())
1558 }
1559
1560 pub fn should_stamp(&self, doc: &Document) -> bool {
1564 self.stamp_lang(doc, Self::any_translated(doc)).is_some()
1565 }
1566
1567 pub fn stamp_lang<'a>(&self, doc: &'a Document, translated: bool) -> Option<&'a str> {
1570 doc.target_lang.as_deref().filter(|t| !t.trim().is_empty()).filter(|_| translated || self.stamp_target_always)
1571 }
1572}
1573
1574#[derive(Debug, thiserror::Error)]
1575#[non_exhaustive]
1576pub enum Error {
1578 #[error("not a {format} file: {msg}")]
1579 Parse {
1581 format: String,
1583 msg: String,
1585 },
1586 #[error("unsupported: {0}")]
1587 Unsupported(String),
1589 #[error("unknown segment {0}")]
1590 UnknownSegment(String),
1592 #[error("segment {0} is locked")]
1593 Locked(String),
1595 #[error("tag {0} is not in the source")]
1596 InventedTag(String),
1598 #[error("tag {0} appears more often than in the source")]
1599 DuplicatedTag(String),
1601 #[error("this skeleton was made by {found}, but this is {expected}; open the file again with the current parser")]
1602 ParserVersion {
1604 found: String,
1606 expected: String,
1608 },
1609 #[error("cannot write: {0}")]
1610 Write(String),
1612 #[error("{reason}")]
1619 Unwritable {
1620 unit: Option<String>,
1622 reason: String,
1624 },
1625 #[error("{0}")]
1628 Limit(LimitError),
1629 #[error("{0}")]
1631 Encoding(String),
1632 #[error("format option {key}: {msg}")]
1634 FormatOption {
1635 key: String,
1637 msg: String,
1639 },
1640 #[error("unknown profile {0:?}")]
1642 UnknownProfile(String),
1643 #[error(transparent)]
1644 Io(#[from] std::io::Error),
1646}
1647
1648pub trait Filter: Send + Sync {
1657 fn id(&self) -> &'static str;
1659 fn extensions(&self) -> &'static [&'static str];
1661 fn sniff(&self, bytes: &[u8]) -> bool;
1663 fn bilingual(&self) -> bool {
1666 false
1667 }
1668 fn format_option_keys(&self) -> &'static [FormatOptionKey] {
1672 &[]
1673 }
1674 fn extract(&self, bytes: &[u8], opts: &ExtractOptions) -> Result<Document, Error>;
1676 fn merge_with(&self, doc: &Document, opts: &MergeOptions) -> Result<Vec<u8>, Error>;
1681 fn merge(&self, doc: &Document) -> Result<Vec<u8>, Error> {
1684 self.merge_with(doc, &MergeOptions::default())
1685 }
1686 fn preview(&self, _doc: &Document) -> Option<String> {
1690 None
1691 }
1692 fn render_segment(&self, _doc: &Document, _seg_id: &str) -> Option<String> {
1695 None
1696 }
1697}
1698
1699#[cfg(test)]
1700mod tests {
1701 use super::*;
1702
1703 #[test]
1704 fn json_shape_matches_catcore() {
1705 let v = vec![Inline::text("Hi "), Inline::tag("1", TagKind::Open, "<b>")];
1706 let j = serde_json::to_string(&v).unwrap();
1707 assert_eq!(j, r#"[{"text":"Hi "},{"tag":{"id":"1","kind":"open","display":"<b>"}}]"#);
1708 }
1709
1710 #[test]
1711 fn output_joins_segments_and_falls_back_to_source() {
1712 let mut u = Unit::new("p1", vec![]);
1713 u.segments = vec![
1714 Segment { id: "p1#1".into(), source: vec![Inline::text("One.")], target: vec![Inline::text("Uno.")], state: SegState::Draft, origin: None, empty_target: false },
1715 Segment { id: "p1#2".into(), source: vec![Inline::text("Two.")], target: vec![], state: SegState::New, origin: None, empty_target: false },
1716 ];
1717 u.separators = vec![" ".into()];
1718 assert_eq!(u.output(), vec![Inline::text("Uno. Two.")]);
1719 assert_eq!(plain_text(&u.source()), "One. Two.");
1720 }
1721
1722 #[test]
1723 fn set_target_takes_the_free_flag_from_the_source() {
1724 let mut d = Document {
1725 format: "test".into(),
1726 name: None,
1727 source_lang: None,
1728 target_lang: None,
1729 granularity: Granularity::Paragraph,
1730 units: vec![Unit::new("u1", vec![Inline::text("Hi "), Inline::free_tag("1", "{name}"), Inline::tag("2", TagKind::Standalone, "%s")])],
1731 skeleton: Skeleton::Text { parts: vec![SkelPart::Unit(0)], encoding: "utf-8".into(), parser: None },
1732 warnings: vec![],
1733 source_encoding: None,
1734 seg_index: SegIndex::default(),
1735 };
1736 let t = vec![
1738 Inline::Tag { id: "2".into(), kind: TagKind::Standalone, display: "%s".into(), free: true },
1739 Inline::text(" hola "),
1740 Inline::tag("1", TagKind::Standalone, "{name}"),
1741 ];
1742 d.set_target("u1", t).unwrap();
1743 let got: Vec<bool> = d.units[0].segments[0].target.iter().filter(|i| matches!(i, Inline::Tag { .. })).map(Inline::is_free).collect();
1744 assert_eq!(got, vec![false, true]);
1745 }
1746
1747 #[test]
1748 fn set_target_checks_tags() {
1749 let mut d = Document {
1750 format: "test".into(),
1751 name: None,
1752 source_lang: None,
1753 target_lang: None,
1754 granularity: Granularity::Paragraph,
1755 units: vec![Unit::new("u1", vec![Inline::tag("1", TagKind::Open, "<b>"), Inline::text("x"), Inline::tag("1", TagKind::Close, "</b>")])],
1756 skeleton: Skeleton::Text { parts: vec![SkelPart::Unit(0)], encoding: "utf-8".into(), parser: None },
1757 warnings: vec![],
1758 source_encoding: None,
1759 seg_index: SegIndex::default(),
1760 };
1761 assert!(d.set_target("u1", vec![Inline::text("y")]).is_ok());
1762 assert!(matches!(d.set_target("u1", vec![Inline::tag("2", TagKind::Open, "<i>")]), Err(Error::InventedTag(_))));
1763 assert!(matches!(
1764 d.set_target("u1", vec![Inline::tag("1", TagKind::Open, ""), Inline::tag("1", TagKind::Open, "")]),
1765 Err(Error::DuplicatedTag(_))
1766 ));
1767 assert_eq!(d.find("u1").unwrap().1.state, SegState::Draft);
1768 }
1769
1770 fn big_doc(n: usize) -> Document {
1771 Document {
1772 format: "test".into(),
1773 units: (0..n).map(|i| Unit::new(format!("u{i}"), vec![Inline::text(format!("Source {i}"))])).collect(),
1774 skeleton: Skeleton::Text { parts: vec![], encoding: "utf-8".into(), parser: None },
1775 ..Default::default()
1776 }
1777 }
1778
1779 #[test]
1780 fn set_targets_sets_many_and_matches_set_target() {
1781 let mut a = big_doc(50);
1782 let mut b = big_doc(50);
1783 a.units[7].translate = false;
1784 b.units[7].translate = false;
1785 for i in (0..50).filter(|i| *i != 7) {
1786 a.set_target(&format!("u{i}"), vec![Inline::text(format!("T{i}"))]).unwrap();
1787 }
1788 b.set_targets((0..50).filter(|i| *i != 7).map(|i| (format!("u{i}"), vec![Inline::text(format!("T{i}"))]))).unwrap();
1789 assert_eq!(a, b);
1790 assert_eq!(b.find("u49").unwrap().1.state, SegState::Draft);
1791 }
1792
1793 #[test]
1794 fn set_target_index_follows_edits_and_stays_out_of_equality() {
1795 let mut d = big_doc(20);
1796 d.set_target("u5", vec![Inline::text("a")]).unwrap();
1797 let e: Document = serde_json::from_str(&serde_json::to_string(&d).unwrap()).unwrap();
1799 assert_eq!(d, e);
1800 assert!(!serde_json::to_string(&d).unwrap().contains("seg_index"));
1801 let moved = d.units.remove(2);
1803 d.set_target("u6", vec![Inline::text("b")]).unwrap();
1804 assert_eq!(d.find("u6").unwrap().1.target, vec![Inline::text("b")]);
1805 assert!(matches!(d.set_target("u2", vec![]), Err(Error::UnknownSegment(_))));
1806 d.units.insert(0, moved);
1807 d.set_target("u2", vec![Inline::text("c")]).unwrap();
1808 assert_eq!(d.units[0].segments[0].target, vec![Inline::text("c")]);
1809 d.units[3].segments[0].id = "renamed".into();
1810 d.set_target("renamed", vec![Inline::text("d")]).unwrap();
1811 assert!(d.find("renamed").unwrap().1.has_target());
1812 let mut c: Document = serde_json::from_str(&serde_json::to_string(&d).unwrap()).unwrap();
1814 c.set_target("u9", vec![Inline::text("x")]).unwrap();
1815 assert_eq!(c.find("u9").unwrap().1.target, vec![Inline::text("x")]);
1816 }
1817
1818 #[test]
1819 fn set_target_index_keeps_first_duplicate_send_sync_and_debug() {
1820 fn send_sync<T: Send + Sync>() {}
1821 send_sync::<Document>();
1822 let mut d = big_doc(6);
1823 d.units[4].segments[0].id = "u1".into();
1824 let before = format!("{d:?}");
1825 d.set_target("u1", vec![Inline::text("a")]).unwrap();
1826 d.set_target("u1", vec![Inline::text("b")]).unwrap();
1827 assert_eq!(d.units[1].segments[0].target, vec![Inline::text("b")]);
1829 assert!(!d.units[4].segments[0].has_target());
1830 let mut fresh = big_doc(6);
1832 fresh.units[4].segments[0].id = "u1".into();
1833 assert_eq!(before, format!("{fresh:?}"));
1834 let mut c = d.clone();
1835 c.set_target("u3", vec![Inline::text("z")]).unwrap();
1836 assert_eq!(c.find("u3").unwrap().1.target, vec![Inline::text("z")]);
1837 assert_eq!(format!("{:?}", d.clone()), format!("{d:?}"));
1838 }
1839
1840 #[test]
1841 fn set_targets_errors_like_set_target_and_keeps_earlier_items() {
1842 let mut d = big_doc(3);
1843 d.units[1].translate = false;
1844 let r = d.set_targets(vec![("u0", vec![Inline::text("a")]), ("u1", vec![Inline::text("b")]), ("u2", vec![Inline::text("c")])]);
1845 assert!(matches!(r, Err(Error::Locked(_))));
1846 assert_eq!(d.units[0].segments[0].target, vec![Inline::text("a")]);
1847 assert!(d.units[2].segments[0].target.is_empty());
1848 assert!(matches!(d.set_targets(vec![("nope", vec![])]), Err(Error::UnknownSegment(_))));
1849 let r = d.set_targets(vec![("u0", vec![Inline::tag("9", TagKind::Open, "<i>")])]);
1850 assert!(matches!(r, Err(Error::InventedTag(_))));
1851 d.set_targets(vec![("u0", vec![Inline::text(" ")])]).unwrap();
1853 assert_eq!(d.units[0].segments[0].state, SegState::New);
1854 }
1855
1856 #[test]
1857 fn set_states_batch() {
1858 let mut d = big_doc(4);
1859 d.set_states((0..4).map(|i| (format!("u{i}"), SegState::Confirmed))).unwrap();
1860 assert!(d.segments().all(|(_, s)| s.state == SegState::Confirmed));
1861 assert!(matches!(d.set_states(vec![("zzz", SegState::New)]), Err(Error::UnknownSegment(_))));
1862 }
1863
1864 #[test]
1865 fn set_targets_100k_is_fast() {
1866 let n = 100_000;
1867 let mut d = big_doc(n);
1868 let t = std::time::Instant::now();
1869 d.set_targets((0..n).map(|i| (format!("u{i}"), vec![Inline::text("x")]))).unwrap();
1870 d.set_states((0..n).map(|i| (format!("u{i}"), SegState::Translated))).unwrap();
1871 let took = t.elapsed();
1872 let limit = if cfg!(debug_assertions) { 10_000 } else { 1_000 };
1874 assert!(took.as_millis() < limit, "100k targets took {took:?}");
1875 assert_eq!(d.units[n - 1].segments[0].state, SegState::Translated);
1876 }
1877}