1use std::path::Path;
6
7use serde_json::{Map as JMap, Value as JValue};
8use toml_edit::{DocumentMut, Item, Table};
9
10use crate::error::{Error, Issue, Result, code};
11use crate::util;
12
13pub const TOP_BARE_KEYS: &[&str] = &[
17 "str",
18 "spec",
19 "kind",
20 "id",
21 "name",
22 "type",
23 "title",
24 "summary",
25 "tags",
26 "revision",
27 "created_at",
28 "updated_at",
29 "schema",
30];
31
32pub const TABLE_ORDER: &[&str] = &["policies", "authors", "refs", "entries", "ext"];
34
35pub const POLICIES_KEYS: &[&str] = &[
37 "id_version",
38 "max_depth",
39 "manifest",
40 "sha256",
41 "ignore",
42 "gitignore",
43 "large_asset_bytes",
44 "deep_tree_warn",
45];
46
47pub const AUTHOR_KEYS: &[&str] = &["id", "name", "role", "at"];
49
50pub const REF_KEYS: &[&str] = &["id", "target", "rel", "title", "order", "note"];
52
53pub const ENTRY_KEYS: &[&str] = &[
55 "path",
56 "role",
57 "id",
58 "target",
60 "mode",
62 "type",
63 "title",
64 "summary",
65 "order",
66 "media_type",
67 "size",
68 "sha256",
69 "count",
70 "schema",
71 "optional",
72 "note",
73];
74
75pub const ROOT_ALLOWED: &[&str] = &[
77 "str", "spec", "kind", "id", "name", "type", "title", "summary", "tags", "revision",
78 "created_at", "updated_at", "schema", "policies", "authors", "refs", "entries", "ext",
79];
80
81pub const BRANCH_ALLOWED: &[&str] = &[
83 "str", "spec", "kind", "id", "name", "type", "title", "summary", "tags", "revision",
84 "created_at", "updated_at", "schema", "authors", "refs", "entries", "ext",
85];
86
87#[derive(Debug, Clone, Copy, PartialEq, Eq)]
91pub enum Kind {
92 Root,
94 Node,
96 Branch,
98}
99
100impl Kind {
101 pub fn as_str(self) -> &'static str {
103 match self {
104 Kind::Root => "root",
105 Kind::Node => "node",
106 Kind::Branch => "branch",
107 }
108 }
109
110 pub fn parse(s: &str) -> Option<Kind> {
112 match s {
113 "root" => Some(Kind::Root),
114 "node" => Some(Kind::Node),
115 "branch" => Some(Kind::Branch),
116 _ => None,
117 }
118 }
119
120 pub fn allowed_top_keys(self) -> &'static [&'static str] {
122 match self {
123 Kind::Root => ROOT_ALLOWED,
124 _ => BRANCH_ALLOWED,
125 }
126 }
127}
128
129#[derive(Debug, Clone, Copy, PartialEq, Eq)]
131pub enum ManifestPolicy {
132 Strict,
134 Advisory,
136}
137
138#[derive(Debug, Clone, Copy, PartialEq, Eq)]
140pub enum ShaPolicy {
141 Required,
143 Optional,
145 Off,
147}
148
149#[derive(Debug, Clone, PartialEq, Eq)]
151pub struct Policies {
152 pub id_version: usize,
154 pub max_depth: usize,
156 pub manifest: ManifestPolicy,
158 pub sha256: ShaPolicy,
160 pub ignore: Vec<String>,
162 pub gitignore: bool,
164 pub large_asset_bytes: u64,
166 pub deep_tree_warn: usize,
168}
169
170impl Default for Policies {
171 fn default() -> Self {
172 Self {
173 id_version: 7,
174 max_depth: 32,
175 manifest: ManifestPolicy::Strict,
176 sha256: ShaPolicy::Required,
177 ignore: Vec::new(),
178 gitignore: true,
179 large_asset_bytes: 10 * 1024 * 1024,
180 deep_tree_warn: 16,
181 }
182 }
183}
184
185#[derive(Debug, Clone, Default, PartialEq, Eq)]
187pub struct Author {
188 pub id: String,
190 pub name: Option<String>,
192 pub role: String,
194 pub at: Option<String>,
196}
197
198#[derive(Debug, Clone, Default, PartialEq, Eq)]
200pub struct RefItem {
201 pub id: String,
203 pub target: String,
205 pub rel: String,
207 pub title: Option<String>,
209 pub order: Option<i64>,
211 pub note: Option<String>,
213}
214
215#[derive(Debug, Clone, Default, PartialEq, Eq)]
217pub struct Entry {
218 pub path: String,
220 pub role: String,
222 pub id: Option<String>,
224 pub target: Option<String>,
226 pub mode: Option<String>,
229 pub r#type: Option<String>,
231 pub title: Option<String>,
233 pub summary: Option<String>,
235 pub order: Option<i64>,
237 pub media_type: Option<String>,
239 pub size: Option<i64>,
241 pub sha256: Option<String>,
243 pub count: Option<i64>,
245 pub schema: Option<String>,
247 pub optional: bool,
249 pub note: Option<String>,
251}
252
253impl Entry {
254 pub fn is_branch(&self) -> bool {
256 self.role == "node" || self.role == "branch"
257 }
258
259 pub fn is_link(&self) -> bool {
261 self.role == "link"
262 }
263
264 pub fn is_file_like(&self) -> bool {
266 self.role == "payload" || self.role == "asset"
267 }
268}
269
270#[derive(Debug)]
272pub struct Meta {
273 pub doc: DocumentMut,
275 pub str_version: Option<i64>,
277 pub spec: Option<String>,
279 pub kind_raw: Option<String>,
281 pub kind: Option<Kind>,
283 pub id: Option<String>,
285 pub name: Option<String>,
287 pub r#type: Option<String>,
289 pub title: Option<String>,
291 pub summary: Option<String>,
293 pub tags: Vec<String>,
295 pub revision: Option<i64>,
297 pub created_at: Option<String>,
299 pub updated_at: Option<String>,
301 pub schema: Option<String>,
303 pub policies: Policies,
305 pub authors: Vec<Author>,
307 pub refs: Vec<RefItem>,
309 pub entries: Vec<Entry>,
311}
312
313pub enum MetaLoad {
315 Ok(Box<Meta>, Vec<Issue>),
317 Failed(Vec<Issue>),
319}
320
321pub fn load(path: &Path, rel: &str) -> Result<MetaLoad> {
323 let bytes = std::fs::read(path).map_err(|e| Error::io(path, e))?;
324 let mut issues = Vec::new();
325
326 if bytes.starts_with(&[0xEF, 0xBB, 0xBF]) {
328 issues.push(Issue::error(
329 code::PARSE,
330 rel,
331 "文件含 UTF-8 BOM,规范要求 UTF-8 无 BOM",
332 ));
333 return Ok(MetaLoad::Failed(issues));
334 }
335 let text = match std::str::from_utf8(&bytes) {
336 Ok(t) => t,
337 Err(e) => {
338 issues.push(Issue::error(
339 code::PARSE,
340 rel,
341 format!("编码非 UTF-8:{e}"),
342 ));
343 return Ok(MetaLoad::Failed(issues));
344 }
345 };
346
347 let doc: DocumentMut = match text.parse() {
348 Ok(d) => d,
349 Err(e) => {
350 issues.push(Issue::error(code::PARSE, rel, format!("TOML 解析失败:{e}")));
351 return Ok(MetaLoad::Failed(issues));
352 }
353 };
354
355 let (meta, mut field_issues) = extract(doc, rel);
356 issues.append(&mut field_issues);
357 Ok(MetaLoad::Ok(Box::new(meta), issues))
358}
359
360pub fn extract(doc: DocumentMut, rel: &str) -> (Meta, Vec<Issue>) {
362 let mut cx = Ctx {
363 rel: rel.to_string(),
364 issues: Vec::new(),
365 };
366 let table = doc.as_table().clone();
367
368 let str_version = cx.opt_int(&table, "str");
369 let spec = cx.opt_str(&table, "spec");
370 let kind_raw = cx.opt_str(&table, "kind");
371 let kind = match kind_raw.as_deref() {
372 Some(s) => match Kind::parse(s) {
373 Some(k) => Some(k),
374 None => {
375 cx.err(
376 code::KIND_INVALID,
377 format!("`kind` = {s:?} 非法(应为 root / node / branch)"),
378 );
379 None
380 }
381 },
382 None => {
383 cx.err(code::SCHEMA_FIELD, "缺少必填字段 `kind`");
384 None
385 }
386 };
387
388 let allowed = kind.map(|k| k.allowed_top_keys()).unwrap_or(BRANCH_ALLOWED);
389 cx.check_unknown(&table, allowed);
390
391 for key in ["id", "revision", "created_at", "updated_at"] {
394 if table.get(key).is_none() {
395 cx.err(code::SCHEMA_FIELD, format!("缺少必填字段 `{key}`"));
396 }
397 }
398
399 let id = cx.opt_str(&table, "id");
400 let name = cx.opt_str(&table, "name");
401 let r#type = cx.opt_str(&table, "type");
402 let title = cx.opt_str(&table, "title");
403 let summary = cx.opt_str(&table, "summary");
404 let tags = cx.opt_str_array(&table, "tags").unwrap_or_default();
405 let revision = cx.opt_int(&table, "revision");
406 let created_at = cx.opt_dt(&table, "created_at");
407 let updated_at = cx.opt_dt(&table, "updated_at");
408 let schema = cx.opt_str(&table, "schema");
409
410 let mut policies = Policies::default();
412 if let Some(item) = table.get("policies") {
413 match item.as_table() {
414 Some(pt) => {
415 if kind != Some(Kind::Root) {
416 cx.err(
417 code::SCHEMA_FIELD,
418 "`[policies]` 只能出现在 root 的 `.str.toml` 中",
419 );
420 }
421 cx.check_unknown(pt, POLICIES_KEYS);
422 if let Some(v) = cx.opt_int(pt, "id_version") {
423 policies.id_version = v.max(0) as usize;
424 }
425 if let Some(v) = cx.opt_int(pt, "max_depth") {
426 policies.max_depth = v.max(1) as usize;
427 }
428 if let Some(v) = cx.opt_str(pt, "manifest") {
429 policies.manifest = match v.as_str() {
430 "strict" => ManifestPolicy::Strict,
431 "advisory" => ManifestPolicy::Advisory,
432 _ => {
433 cx.err(
434 code::SCHEMA_FIELD,
435 format!("`policies.manifest` = {v:?} 非法(strict / advisory)"),
436 );
437 policies.manifest
438 }
439 };
440 }
441 if let Some(v) = cx.opt_str(pt, "sha256") {
442 policies.sha256 = match v.as_str() {
443 "required" => ShaPolicy::Required,
444 "optional" => ShaPolicy::Optional,
445 "off" => ShaPolicy::Off,
446 _ => {
447 cx.err(
448 code::SCHEMA_FIELD,
449 format!("`policies.sha256` = {v:?} 非法(required / optional / off)"),
450 );
451 policies.sha256
452 }
453 };
454 }
455 if let Some(v) = cx.opt_str_array(pt, "ignore") {
456 policies.ignore = v.into_iter().filter(|s| !s.trim().is_empty()).collect();
457 }
458 if let Some(item) = pt.get("gitignore") {
459 match item.as_bool() {
460 Some(b) => policies.gitignore = b,
461 None => cx.err(
462 code::SCHEMA_FIELD,
463 "`policies.gitignore` 必须是布尔值",
464 ),
465 }
466 }
467 if let Some(v) = cx.opt_int(pt, "large_asset_bytes") {
468 policies.large_asset_bytes = v.max(0) as u64;
469 }
470 if let Some(v) = cx.opt_int(pt, "deep_tree_warn") {
471 policies.deep_tree_warn = v.max(1) as usize;
472 }
473 }
474 None => cx.err(code::SCHEMA_FIELD, "`policies` 必须是表 `[policies]`"),
475 }
476 }
477
478 let mut authors = Vec::new();
480 if let Some(aot) = table.get("authors").and_then(|i| i.as_array_of_tables()) {
481 for (i, t) in aot.iter().enumerate() {
482 cx.set_rel(&format!("{rel} #authors[{i}]"));
483 cx.check_unknown(t, AUTHOR_KEYS);
484 let aid = cx.req_str(t, "id").unwrap_or_default();
485 let role = cx.req_str(t, "role").unwrap_or_default();
486 let aname = cx.opt_str(t, "name");
487 let at = cx.opt_dt(t, "at");
488 authors.push(Author {
489 id: aid,
490 name: aname,
491 role,
492 at,
493 });
494 }
495 cx.set_rel(rel);
496 } else if table.get("authors").is_some() {
497 cx.err(code::SCHEMA_FIELD, "`authors` 必须是数组表 `[[authors]]`");
498 }
499
500 let mut refs = Vec::new();
502 if let Some(aot) = table.get("refs").and_then(|i| i.as_array_of_tables()) {
503 for (i, t) in aot.iter().enumerate() {
504 cx.set_rel(&format!("{rel} #refs[{i}]"));
505 cx.check_unknown(t, REF_KEYS);
506 refs.push(RefItem {
507 id: cx.req_str(t, "id").unwrap_or_default(),
508 target: cx.req_str(t, "target").unwrap_or_default(),
509 rel: cx.req_str(t, "rel").unwrap_or_default(),
510 title: cx.opt_str(t, "title"),
511 order: cx.opt_int(t, "order"),
512 note: cx.opt_str(t, "note"),
513 });
514 }
515 cx.set_rel(rel);
516 } else if table.get("refs").is_some() {
517 cx.err(code::SCHEMA_FIELD, "`refs` 必须是数组表 `[[refs]]`");
518 }
519
520 let mut entries = Vec::new();
522 if let Some(aot) = table.get("entries").and_then(|i| i.as_array_of_tables()) {
523 for (i, t) in aot.iter().enumerate() {
524 cx.set_rel(&format!("{rel} #entries[{i}]"));
525 cx.check_unknown(t, ENTRY_KEYS);
526 let path = cx.req_str(t, "path").unwrap_or_default();
527 let role = cx.req_str(t, "role").unwrap_or_default();
528 if path.contains('/') {
529 cx.err(
530 code::SCHEMA_FIELD,
531 format!("`entries[].path` = {path:?} 必须是单段路径(不含 `/`)"),
532 );
533 }
534 let e = Entry {
535 path,
536 role,
537 id: cx.opt_str(t, "id"),
538 target: cx.opt_str(t, "target"),
539 mode: cx.opt_str(t, "mode"),
540 r#type: cx.opt_str(t, "type"),
541 title: cx.opt_str(t, "title"),
542 summary: cx.opt_str(t, "summary"),
543 order: cx.opt_int(t, "order"),
544 media_type: cx.opt_str(t, "media_type"),
545 size: cx.opt_int(t, "size"),
546 sha256: cx.opt_str(t, "sha256"),
547 count: cx.opt_int(t, "count"),
548 schema: cx.opt_str(t, "schema"),
549 optional: cx.opt_bool(t, "optional").unwrap_or(false),
550 note: cx.opt_str(t, "note"),
551 };
552 entries.push(e);
553 }
554 cx.set_rel(rel);
555 } else if table.get("entries").is_some() {
556 cx.err(code::SCHEMA_FIELD, "`entries` 必须是数组表 `[[entries]]`");
557 }
558
559 let meta = Meta {
560 doc,
561 str_version,
562 spec,
563 kind_raw,
564 kind,
565 id,
566 name,
567 r#type,
568 title,
569 summary,
570 tags,
571 revision,
572 created_at,
573 updated_at,
574 schema,
575 policies,
576 authors,
577 refs,
578 entries,
579 };
580 (meta, cx.issues)
581}
582
583pub fn canonicalize_doc(doc: &mut DocumentMut) {
591 let top_rank = |k: &str, it: &Item| -> usize {
594 match it {
595 Item::Table(_) | Item::ArrayOfTables(_) => {
596 TOP_BARE_KEYS.len()
597 + 1
598 + TABLE_ORDER
599 .iter()
600 .position(|x| *x == k)
601 .unwrap_or(TABLE_ORDER.len())
602 }
603 _ => TOP_BARE_KEYS
604 .iter()
605 .position(|x| *x == k)
606 .unwrap_or(TOP_BARE_KEYS.len()),
607 }
608 };
609 doc.as_table_mut()
610 .sort_values_by(|k1, i1, k2, i2| top_rank(k1.get(), i1).cmp(&top_rank(k2.get(), i2)));
611
612 for (key, order) in [
614 ("policies", POLICIES_KEYS),
615 ("authors", AUTHOR_KEYS),
616 ("refs", REF_KEYS),
617 ("entries", ENTRY_KEYS),
618 ] {
619 let rank = |k: &str| order.iter().position(|x| *x == k).unwrap_or(usize::MAX);
620 match doc.as_table_mut().get_mut(key) {
621 Some(Item::Table(t)) => {
622 t.sort_values_by(|k1, _, k2, _| rank(k1.get()).cmp(&rank(k2.get())));
623 }
624 Some(Item::ArrayOfTables(a)) => {
625 for t in a.iter_mut() {
626 t.sort_values_by(|k1, _, k2, _| rank(k1.get()).cmp(&rank(k2.get())));
627 }
628 }
629 _ => {}
630 }
631 }
632
633 sort_collections_in(doc);
635
636 renumber_positions_in(doc);
638}
639
640fn collection_sort_key(t: &Table) -> (i64, String) {
642 let order = t
643 .get("order")
644 .and_then(Item::as_integer)
645 .unwrap_or(i64::MAX);
646 let id = t
647 .get("path")
648 .or_else(|| t.get("id"))
649 .and_then(Item::as_str)
650 .unwrap_or("")
651 .to_string();
652 (order, id)
653}
654
655fn sort_collections_in(doc: &mut DocumentMut) {
657 for key in ["entries", "refs"] {
658 let Some(aot) = doc
659 .as_table_mut()
660 .get_mut(key)
661 .and_then(Item::as_array_of_tables_mut)
662 else {
663 continue;
664 };
665 let mut items: Vec<Table> = aot.iter().cloned().collect();
666 items.sort_by_key(collection_sort_key);
667 for (slot, table) in aot.iter_mut().zip(items) {
668 *slot = table;
669 }
670 }
671}
672
673fn renumber_positions_in(doc: &mut DocumentMut) {
679 fn walk(t: &mut Table, pos: &mut isize) {
680 *pos += 1;
681 t.set_position(Some(*pos));
682 for (_, item) in t.iter_mut() {
683 match item {
684 Item::Table(child) => walk(child, pos),
685 Item::ArrayOfTables(a) => {
686 for child in a.iter_mut() {
687 walk(child, pos);
688 }
689 }
690 _ => {}
691 }
692 }
693 }
694 let mut pos = 0isize;
695 walk(doc.as_table_mut(), &mut pos);
696}
697
698impl Meta {
701 pub fn to_json(&self) -> JValue {
704 let table = self.doc.as_table();
705 let mut map = JMap::new();
706
707 for key in TOP_BARE_KEYS {
708 if let Some(item) = table.get(key) {
709 map.insert((*key).to_string(), item_to_json(item));
710 }
711 }
712 if let Some(item) = table.get("policies") {
713 match item.as_table() {
714 Some(t) => {
715 map.insert("policies".into(), table_to_json(t, POLICIES_KEYS));
716 }
717 None => {
718 map.insert("policies".into(), item_to_json(item));
719 }
720 }
721 }
722 if let Some(aot) = table.get("authors").and_then(|i| i.as_array_of_tables()) {
723 map.insert(
724 "authors".into(),
725 JValue::Array(
726 aot.iter()
727 .map(|t| table_to_json(t, AUTHOR_KEYS))
728 .collect(),
729 ),
730 );
731 }
732 map.insert(
734 "refs".into(),
735 match table.get("refs").and_then(|i| i.as_array_of_tables()) {
736 Some(aot) => JValue::Array(
737 aot.iter()
738 .map(|t| table_to_json(t, REF_KEYS))
739 .collect(),
740 ),
741 None => JValue::Array(Vec::new()),
742 },
743 );
744 map.insert(
745 "entries".into(),
746 match table.get("entries").and_then(|i| i.as_array_of_tables()) {
747 Some(aot) => JValue::Array(
748 aot.iter()
749 .map(|t| table_to_json(t, ENTRY_KEYS))
750 .collect(),
751 ),
752 None => JValue::Array(Vec::new()),
753 },
754 );
755 if let Some(item) = table.get("ext") {
756 map.insert("ext".into(), item_to_json(item));
757 }
758 for (k, v) in table.iter() {
760 if !map.contains_key(k) {
761 map.insert(k.to_string(), item_to_json(v));
762 }
763 }
764 JValue::Object(map)
765 }
766
767 pub fn sort_collections(&mut self) {
769 sort_collections_in(&mut self.doc);
770 renumber_positions_in(&mut self.doc);
771 }
772
773 pub fn canonicalize(&mut self) {
775 canonicalize_doc(&mut self.doc);
776 }
777
778 pub fn revision_issues(&self, rel: &str) -> Vec<Issue> {
780 let mut out = Vec::new();
781 match self.revision {
782 None => {}
783 Some(r) if r < 1 => out.push(Issue::error(
784 code::REVISION_STALE,
785 rel,
786 format!("`revision` = {r},必须为 ≥ 1 的整数"),
787 )),
788 Some(_) => {}
789 }
790 if let (Some(c), Some(u)) = (self.created_at.as_deref(), self.updated_at.as_deref()) {
791 match (util::parse_rfc3339(c), util::parse_rfc3339(u)) {
792 (Some(cd), Some(ud)) if ud < cd => out.push(Issue::error(
793 code::REVISION_STALE,
794 rel,
795 format!("`updated_at`({u})早于 `created_at`({c})"),
796 )),
797 _ => {}
798 }
799 }
800 out
801 }
802}
803
804fn item_to_json(item: &Item) -> JValue {
806 match item {
807 Item::None => JValue::Null,
808 Item::Value(v) => value_to_json(v),
809 Item::Table(t) => {
810 let mut m = JMap::new();
811 for (k, v) in t.iter() {
812 m.insert(k.to_string(), item_to_json(v));
813 }
814 JValue::Object(m)
815 }
816 Item::ArrayOfTables(aot) => JValue::Array(
817 aot.iter()
818 .map(|t| {
819 let mut m = JMap::new();
820 for (k, v) in t.iter() {
821 m.insert(k.to_string(), item_to_json(v));
822 }
823 JValue::Object(m)
824 })
825 .collect(),
826 ),
827 }
828}
829
830fn value_to_json(v: &toml_edit::Value) -> JValue {
832 if let Some(s) = v.as_str() {
833 return JValue::String(s.to_string());
834 }
835 if let Some(i) = v.as_integer() {
836 return JValue::from(i);
837 }
838 if let Some(f) = v.as_float() {
839 return serde_json::Number::from_f64(f)
840 .map(JValue::Number)
841 .unwrap_or(JValue::Null);
842 }
843 if let Some(b) = v.as_bool() {
844 return JValue::Bool(b);
845 }
846 if let Some(d) = v.as_datetime() {
847 return JValue::String(d.to_string());
848 }
849 if let Some(a) = v.as_array() {
850 return JValue::Array(a.iter().map(value_to_json).collect());
851 }
852 if let Some(t) = v.as_inline_table() {
853 let mut m = JMap::new();
854 for (k, val) in t.iter() {
855 m.insert(k.to_string(), value_to_json(val));
856 }
857 return JValue::Object(m);
858 }
859 JValue::Null
860}
861
862fn table_to_json(table: &Table, order: &[&str]) -> JValue {
864 let mut m = JMap::new();
865 for k in order {
866 if let Some(v) = table.get(k) {
867 m.insert((*k).to_string(), item_to_json(v));
868 }
869 }
870 for (k, v) in table.iter() {
871 if !m.contains_key(k) {
872 m.insert(k.to_string(), item_to_json(v));
873 }
874 }
875 JValue::Object(m)
876}
877
878struct Ctx {
882 rel: String,
883 issues: Vec<Issue>,
884}
885
886impl Ctx {
887 fn set_rel(&mut self, rel: &str) {
888 self.rel = rel.to_string();
889 }
890
891 fn err(&mut self, code: &'static str, message: impl Into<String>) {
892 self.issues
893 .push(Issue::error(code, self.rel.clone(), message));
894 }
895
896 fn check_unknown(&mut self, t: &Table, allowed: &[&str]) {
897 for (k, _) in t.iter() {
898 if !allowed.contains(&k) {
899 self.err(
900 code::SCHEMA_FIELD,
901 format!("未知字段 `{k}`(扩展请放入 `[ext]`)"),
902 );
903 }
904 }
905 }
906
907 fn req_str(&mut self, t: &Table, key: &str) -> Option<String> {
908 match t.get(key) {
909 None => {
910 self.err(code::SCHEMA_FIELD, format!("缺少必填字段 `{key}`"));
911 None
912 }
913 Some(item) => match item.as_str() {
914 Some(s) => Some(s.to_string()),
915 None => {
916 self.err(code::SCHEMA_FIELD, format!("`{key}` 必须是字符串"));
917 None
918 }
919 },
920 }
921 }
922
923 fn opt_str(&mut self, t: &Table, key: &str) -> Option<String> {
924 match t.get(key) {
925 None => None,
926 Some(item) => match item.as_str() {
927 Some(s) => Some(s.to_string()),
928 None => {
929 self.err(code::SCHEMA_FIELD, format!("`{key}` 必须是字符串"));
930 None
931 }
932 },
933 }
934 }
935
936 fn opt_int(&mut self, t: &Table, key: &str) -> Option<i64> {
937 match t.get(key) {
938 None => None,
939 Some(item) => match item.as_integer() {
940 Some(i) => Some(i),
941 None => {
942 self.err(code::SCHEMA_FIELD, format!("`{key}` 必须是整数"));
943 None
944 }
945 },
946 }
947 }
948
949 fn opt_bool(&mut self, t: &Table, key: &str) -> Option<bool> {
950 match t.get(key) {
951 None => None,
952 Some(item) => match item.as_bool() {
953 Some(b) => Some(b),
954 None => {
955 self.err(code::SCHEMA_FIELD, format!("`{key}` 必须是布尔值"));
956 None
957 }
958 },
959 }
960 }
961
962 fn opt_dt(&mut self, t: &Table, key: &str) -> Option<String> {
964 let Some(item) = t.get(key) else {
965 return None;
966 };
967 if item.as_str().is_some() {
968 self.err(
969 code::PARSE,
970 format!("`{key}` 必须使用 TOML 原生 offset date-time,不得写成字符串"),
971 );
972 return None;
973 }
974 match item.as_datetime() {
975 Some(d) => {
976 if d.date.is_none() || d.time.is_none() || d.offset.is_none() {
977 self.err(
978 code::PARSE,
979 format!("`{key}` 必须是带时区偏移的 offset date-time(如 2026-09-14T10:03:11+08:00)"),
980 );
981 return None;
982 }
983 Some(d.to_string())
984 }
985 None => {
986 self.err(
987 code::PARSE,
988 format!("`{key}` 必须是 offset date-time"),
989 );
990 None
991 }
992 }
993 }
994
995 fn opt_str_array(&mut self, t: &Table, key: &str) -> Option<Vec<String>> {
996 let Some(item) = t.get(key) else {
997 return None;
998 };
999 let Some(arr) = item.as_array() else {
1000 self.err(code::SCHEMA_FIELD, format!("`{key}` 必须是字符串数组"));
1001 return None;
1002 };
1003 let mut out = Vec::new();
1004 for v in arr.iter() {
1005 match v.as_str() {
1006 Some(s) => out.push(s.to_string()),
1007 None => {
1008 self.err(code::SCHEMA_FIELD, format!("`{key}` 的元素必须是字符串"));
1009 }
1010 }
1011 }
1012 Some(out)
1013 }
1014}