imprimatur 0.8.1 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 20a7d3843214018bf15d889668ad1d33ba8dfee183b86e041d56b5cc2db88832
4
- data.tar.gz: 6699fc743a0a04fffbaf67d68551ca680c416cdc56f1fd71984ec2f7cba8e5b1
3
+ metadata.gz: 4efc9644ebf7bdc67f504b7b3c9f4ea046f3ac772b88656151f6a2179bcc4a56
4
+ data.tar.gz: e8096235512724a060c501c8c8019cc6dc256f53eee585aafd66435b10c48325
5
5
  SHA512:
6
- metadata.gz: ef0a7f9c8d545aa513881626e798702095c66a42a5665b663a56b4c6205e5a0c09596366d9dae05c6ac6539f46ba242744feb2ab99080e906b418c0af2550625
7
- data.tar.gz: 38ccdff0d6b4d2bfcb516660de96f1274ac0d1cef01b9d97f2790b0223b041ec2fd5b747be21a053a368c0bf58e33e2f8b9c608ed1bd5d5ea2e1da7bfd218615
6
+ metadata.gz: 2f374493b4da1a649b8bee42d6052733b62ff486e96eeaccbf9b85cc9e5a98cdfbc5e10b465807704a1775cd917887e93346333aa2cd9ffe7f94f419cccee0cd
7
+ data.tar.gz: a7731b05b0da31c47acdc2754bd8760d6f65547d918dd2e2d217be712eb8b4d3c09d2611c5d939761d912d29d9bdcfd73f91dae96dfbaba3ce02400845b75570
data/CHANGELOG.md CHANGED
@@ -1,15 +1,23 @@
1
1
  # Changelog
2
2
 
3
- ## Unreleased
4
-
5
- - Isolate PDF metadata and text reads in the bundled resource-limited Rust
6
- worker, as rendering already is; all three accept `memory_bytes:`.
7
- - On Linux/FreeBSD, re-exec the worker under its address-space limit before
8
- reading the PDF, including tiny metadata-only reads.
9
- - Preserve completed pages on worker termination and recover healthy neighbors
10
- after page-local stream limits without renewing the overall deadline.
11
- - Allow a bounded exit grace when macOS cannot inspect an exiting worker;
12
- persistent monitor failures still terminate and reap a live worker.
3
+ ## [0.9.1](https://github.com/seuros/imprimatur/compare/v0.9.0...v0.9.1) (2026-11-19)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * **pdf:** refuse a recovery step after the pages were returned ([6723e3e](https://github.com/seuros/imprimatur/commit/6723e3ecd0009dc10b4136cfcb15b7bdd65022cb))
9
+
10
+
11
+ ### Performance Improvements
12
+
13
+ * **ruby:** resolve the binding's classes once at load ([6271c0e](https://github.com/seuros/imprimatur/commit/6271c0e5ef5d39dcc1047e818d4c6cccd7d3c2b4))
14
+
15
+ ## [0.9.0](https://github.com/seuros/imprimatur/compare/v0.8.1...v0.9.0) (2026-11-18)
16
+
17
+
18
+ ### Features
19
+
20
+ * **read:** to_markdown_outline reports each page's and sheet's lines ([#18](https://github.com/seuros/imprimatur/issues/18)) ([f0b262a](https://github.com/seuros/imprimatur/commit/f0b262acde3f248ca0b10c11ba85e6e1f39a6a3a))
13
21
 
14
22
  ## [0.8.1](https://github.com/seuros/imprimatur/compare/v0.8.0...v0.8.1) (2026-10-29)
15
23
 
data/Cargo.lock CHANGED
@@ -135,6 +135,12 @@ version = "0.1.0"
135
135
  source = "registry+https://github.com/rust-lang/crates.io-index"
136
136
  checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"
137
137
 
138
+ [[package]]
139
+ name = "bytes"
140
+ version = "1.12.2"
141
+ source = "registry+https://github.com/rust-lang/crates.io-index"
142
+ checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c"
143
+
138
144
  [[package]]
139
145
  name = "cexpr"
140
146
  version = "0.6.0"
@@ -513,7 +519,7 @@ dependencies = [
513
519
 
514
520
  [[package]]
515
521
  name = "imprimatur"
516
- version = "0.8.1"
522
+ version = "0.9.1"
517
523
  dependencies = [
518
524
  "aes",
519
525
  "crc32fast",
@@ -536,7 +542,7 @@ dependencies = [
536
542
 
537
543
  [[package]]
538
544
  name = "imprimatur-cli"
539
- version = "0.8.1"
545
+ version = "0.9.1"
540
546
  dependencies = [
541
547
  "imprimatur",
542
548
  "regex",
@@ -548,10 +554,11 @@ dependencies = [
548
554
 
549
555
  [[package]]
550
556
  name = "imprimatur_native"
551
- version = "0.8.1"
557
+ version = "0.9.1"
552
558
  dependencies = [
553
559
  "imprimatur",
554
560
  "magnus",
561
+ "matryona-machines",
555
562
  "rb-sys",
556
563
  "serde_json",
557
564
  ]
@@ -666,10 +673,11 @@ checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
666
673
 
667
674
  [[package]]
668
675
  name = "magnus"
669
- version = "0.9.2"
676
+ version = "0.9.4"
670
677
  source = "registry+https://github.com/rust-lang/crates.io-index"
671
- checksum = "b9068710e00d21be762edca59b9c4c8946dbdb29820d4f76ad559afea07982c9"
678
+ checksum = "3c5f2dd2017d172e2fde9969a35f10f1374a4dd79b37a17f1847f83201883de7"
672
679
  dependencies = [
680
+ "bytes",
673
681
  "magnus-macros",
674
682
  "rb-sys",
675
683
  "rb-sys-env",
@@ -687,6 +695,15 @@ dependencies = [
687
695
  "syn 2.0.119",
688
696
  ]
689
697
 
698
+ [[package]]
699
+ name = "matryona-machines"
700
+ version = "0.6.0"
701
+ source = "registry+https://github.com/rust-lang/crates.io-index"
702
+ checksum = "cf8a06ab02efd767270815a1f515a40bbf3bfc77038e9360676ebe8d47833b07"
703
+ dependencies = [
704
+ "magnus",
705
+ ]
706
+
690
707
  [[package]]
691
708
  name = "md-5"
692
709
  version = "0.11.0"
data/Cargo.toml CHANGED
@@ -15,9 +15,10 @@ crc32fast = "1.5.2"
15
15
  datamatrix = "0.3.3"
16
16
  font-test-data = "0.10.0"
17
17
  hayro = { version = "0.8.0", default-features = false, features = ["embed-fonts", "embed-cmaps"] }
18
- imprimatur = { path = "ext/imprimatur_native/core", version = "0.8.1" }
18
+ imprimatur = { path = "ext/imprimatur_native/core", version = "0.9.1" }
19
19
  libproc = "0.14.11"
20
- magnus = { version = "0.9.2", default-features = false }
20
+ magnus = { version = "0.9.3", default-features = false }
21
+ matryona-machines = { version = ">=0.6", default-features = false }
21
22
  md-5 = "0.11.0"
22
23
  miniz_oxide = "0.9.1"
23
24
  nix = { version = "0.31.3", features = ["resource", "process", "signal"] }
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "imprimatur-cli"
3
- version = "0.8.1"
3
+ version = "0.9.1"
4
4
  description = "Read PDF, XLSX, XLS, ODS and DOCX documents as Markdown or JSON, search them, extract their images."
5
5
  keywords = ["pdf", "xlsx", "docx", "markdown", "cli"]
6
6
  categories = ["command-line-utilities", "text-processing"]
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "imprimatur"
3
- version = "0.8.1"
3
+ version = "0.9.1"
4
4
  description = "XLSX, PDF and DOCX authoring, and PDF, XLSX, XLS, ODS and DOCX reading, with its own XML, zip and PDF code."
5
5
  keywords = ["xlsx", "excel", "pdf", "docx", "spreadsheet"]
6
6
  categories = ["encoding", "text-processing"]
@@ -8,29 +8,94 @@
8
8
  mod tests;
9
9
 
10
10
  use std::fmt::Write as _;
11
+ use std::ops::RangeInclusive;
11
12
 
12
13
  use super::content::{Block, Cell, Content, Grid, Page, Sheet, Text, push_reference};
13
14
 
14
15
  /// The deepest Markdown heading.
15
16
  const MAX_HEADING: u8 = 6;
16
17
 
18
+ /// A page or sheet of [`Content::to_markdown_outline`]'s Markdown, by line:
19
+ /// 1-based and inclusive. A page that writes nothing (the first, left blank)
20
+ /// has an empty range.
21
+ #[derive(Debug, Clone, PartialEq, Eq)]
22
+ pub struct Section {
23
+ pub kind: SectionKind,
24
+ pub lines: RangeInclusive<usize>,
25
+ }
26
+
27
+ #[derive(Debug, Clone, PartialEq, Eq)]
28
+ pub enum SectionKind {
29
+ Page { number: u32, label: Option<String> },
30
+ Sheet { name: String, hidden: bool, table: Option<TableLines> },
31
+ }
32
+
33
+ /// Where a sheet's table sits. Every row is one line, so data row `n` is
34
+ /// line `rows.start() + n - 1`; `header` is the header row and the
35
+ /// separator under it, what a slice of rows needs to stay a table.
36
+ #[derive(Debug, Clone, PartialEq, Eq)]
37
+ pub struct TableLines {
38
+ pub header: RangeInclusive<usize>,
39
+ /// Empty when the table is a header alone.
40
+ pub rows: RangeInclusive<usize>,
41
+ }
42
+
43
+ impl TableLines {
44
+ /// Data rows below the header.
45
+ #[must_use]
46
+ pub fn row_count(&self) -> usize {
47
+ self.rows.clone().count()
48
+ }
49
+ }
50
+
17
51
  impl Content {
18
52
  /// The content as Markdown: a PDF's pages (from the second, marked
19
53
  /// `<!-- page N -->`), each sheet of a workbook under its name, a Word
20
54
  /// document's blocks.
21
55
  #[must_use]
22
56
  pub fn to_markdown(&self) -> String {
57
+ self.to_markdown_outline().0
58
+ }
59
+
60
+ /// [`Content::to_markdown`], and where each page or sheet landed in it,
61
+ /// so a caller can hand out part of a long document without parsing the
62
+ /// Markdown back. A Word document has no sections.
63
+ #[must_use]
64
+ pub fn to_markdown_outline(&self) -> (String, Vec<Section>) {
23
65
  let mut out = String::new();
66
+ let mut lines = Lines::default();
67
+ let mut sections = Vec::new();
24
68
  match self {
25
- Self::Pdf(pages) => pdf(&mut out, pages),
69
+ Self::Pdf(pages) => pdf(&mut out, pages, &mut lines, &mut sections),
26
70
  Self::Xlsx(sheets) | Self::Ods(sheets) | Self::Xls(sheets) => {
27
71
  for sheet in sheets {
28
- write_sheet(&mut out, sheet);
72
+ sections.push(write_sheet(&mut out, sheet, &mut lines));
29
73
  }
30
74
  }
31
75
  Self::Docx(blocks) => write_blocks(&mut out, blocks.iter(), Mode::Body),
32
76
  }
33
- out
77
+ (out, sections)
78
+ }
79
+ }
80
+
81
+ /// Counts lines of the output as it grows, each byte once.
82
+ #[derive(Default)]
83
+ struct Lines {
84
+ counted: usize,
85
+ newlines: usize,
86
+ }
87
+
88
+ impl Lines {
89
+ /// The line the next write to `out` starts on.
90
+ fn next(&mut self, out: &str) -> usize {
91
+ self.newlines += out[self.counted..].matches('\n').count();
92
+ self.counted = out.len();
93
+ self.newlines + 1
94
+ }
95
+
96
+ /// The last line written, when `out` ends with its newline.
97
+ fn last(&mut self, out: &str) -> usize {
98
+ self.next(out) - 1
34
99
  }
35
100
  }
36
101
 
@@ -43,13 +108,16 @@ pub enum Mode {
43
108
  Cell,
44
109
  }
45
110
 
46
- fn pdf(out: &mut String, pages: &[Page]) {
111
+ fn pdf(out: &mut String, pages: &[Page], lines: &mut Lines, sections: &mut Vec<Section>) {
47
112
  // Every page past the first gets its marker, blocks or none: an empty
48
113
  // page (left bare by `--drop-repeated`, or genuinely blank) still needs
49
114
  // one, so the markers stay a reliable page count and index.
50
115
  for page in pages {
51
116
  if page.number > 1 {
52
117
  end_block(out);
118
+ }
119
+ let first = lines.next(out);
120
+ if page.number > 1 {
53
121
  // Writing to a String cannot fail.
54
122
  match &page.label {
55
123
  Some(label) => {
@@ -61,21 +129,35 @@ fn pdf(out: &mut String, pages: &[Page]) {
61
129
  }
62
130
  }
63
131
  write_blocks(out, page.blocks.iter().map(|placed| &placed.block), Mode::Body);
132
+ sections.push(Section {
133
+ kind: SectionKind::Page { number: page.number, label: page.label.clone() },
134
+ lines: first..=lines.last(out),
135
+ });
64
136
  }
65
137
  }
66
138
 
67
- fn write_sheet(out: &mut String, sheet: &Sheet) {
139
+ fn write_sheet(out: &mut String, sheet: &Sheet, lines: &mut Lines) -> Section {
68
140
  end_block(out);
141
+ let first = lines.next(out);
69
142
  out.push_str("## ");
70
143
  out.push_str(&sheet.name);
71
144
  if sheet.hidden {
72
145
  out.push_str(" (hidden)");
73
146
  }
74
147
  out.push_str("\n\n");
148
+ let mut table = None;
75
149
  if sheet.cells.is_empty() {
76
150
  out.push_str("_Empty._\n");
77
151
  } else {
152
+ let before = out.len();
153
+ let header = lines.next(out);
78
154
  write_table(out, &sheet.cells);
155
+ if out.len() > before {
156
+ table = Some(TableLines {
157
+ header: header..=header + 1,
158
+ rows: header + 2..=lines.last(out),
159
+ });
160
+ }
79
161
  }
80
162
  for (index, note) in sheet.comments.iter().enumerate() {
81
163
  if index == 0 {
@@ -98,6 +180,10 @@ fn write_sheet(out: &mut String, sheet: &Sheet) {
98
180
  }
99
181
  out.push('\n');
100
182
  }
183
+ Section {
184
+ kind: SectionKind::Sheet { name: sheet.name.clone(), hidden: sheet.hidden, table },
185
+ lines: first..=lines.last(out),
186
+ }
101
187
  }
102
188
 
103
189
  /// Blocks in order: consecutive list items form one list; everything else
@@ -1,6 +1,7 @@
1
1
  //! Optional timeout-neighbour recovery under one overall supervisor deadline.
2
2
 
3
3
  use std::iter;
4
+ use std::mem;
4
5
  use std::path::Path;
5
6
  use std::time::{Duration, Instant};
6
7
 
@@ -47,9 +48,18 @@ pub struct Recovery {
47
48
  options: ReadOptions,
48
49
  attempt_timeout: Duration,
49
50
  deadline: Option<Instant>,
50
- result: Option<Pages>,
51
- pending: Vec<usize>,
52
- remaining: usize,
51
+ phase: Phase,
52
+ }
53
+
54
+ enum Phase {
55
+ Batch,
56
+ /// `pending` pages are retried alone, last first.
57
+ Singles {
58
+ result: Pages,
59
+ pending: Vec<usize>,
60
+ remaining: usize,
61
+ },
62
+ Done,
53
63
  }
54
64
 
55
65
  impl Recovery {
@@ -59,20 +69,13 @@ impl Recovery {
59
69
  if attempt_timeout.is_zero() {
60
70
  return Err(Error::InvalidPdfOption("batch timeout must be positive"));
61
71
  }
62
- Ok(Self {
63
- options: options.clone(),
64
- attempt_timeout,
65
- deadline: None,
66
- result: None,
67
- pending: Vec::new(),
68
- remaining: options.max_output_bytes,
69
- })
72
+ Ok(Self { options: options.clone(), attempt_timeout, deadline: None, phase: Phase::Batch })
70
73
  }
71
74
 
72
75
  /// Runs the next worker attempt; the pages once recovery is over.
73
76
  ///
74
77
  /// # Errors
75
- /// As [`pages_isolated_recovering`].
78
+ /// As [`pages_isolated_recovering`], or a step after the pages were returned.
76
79
  pub fn step(
77
80
  &mut self,
78
81
  worker: &Path,
@@ -80,6 +83,9 @@ impl Recovery {
80
83
  limits: &Limits,
81
84
  process: &ProcessLimits,
82
85
  ) -> Result<Option<Pages>> {
86
+ if matches!(self.phase, Phase::Done) {
87
+ return Err(Error::InvalidPdfOption("recovery has already returned its pages"));
88
+ }
83
89
  let deadline = self.deadline(limits, process)?;
84
90
  let attempt_timeout = self.attempt_timeout;
85
91
  let attempt = |selection: &ReadOptions| {
@@ -94,26 +100,30 @@ impl Recovery {
94
100
  selection,
95
101
  )
96
102
  };
97
- let Some(result) = &mut self.result else {
103
+ let Phase::Singles { result, pending, remaining } = &mut self.phase else {
98
104
  let (pages, first_missing) = attempt(&self.options)?;
99
- let Some(first_missing) = first_missing else { return Ok(Some(pages)) };
105
+ let Some(first_missing) = first_missing else {
106
+ self.phase = Phase::Done;
107
+ return Ok(Some(pages));
108
+ };
100
109
  let count = pages.pages.len();
101
- self.pending = (first_missing + 1..count)
110
+ let pending = (first_missing + 1..count)
102
111
  .chain(iter::once(first_missing))
103
112
  .filter(|&index| index < count)
104
113
  .rev()
105
114
  .collect();
106
- self.remaining -= pages.pages.iter().map(|page| page.text.len()).sum::<usize>();
107
- self.result = Some(pages);
115
+ let read: usize = pages.pages.iter().map(|page| page.text.len()).sum();
116
+ let remaining = self.options.max_output_bytes.saturating_sub(read);
117
+ self.phase = Phase::Singles { result: pages, pending, remaining };
108
118
  return Ok(self.settle());
109
119
  };
110
- let Some(&index) = self.pending.last() else { return Ok(self.result.take()) };
120
+ let Some(&index) = pending.last() else { return Ok(self.finish()) };
111
121
  let number = result.pages[index].number;
112
122
  let selection = ReadOptions {
113
123
  first_page: number,
114
124
  last_page: number,
115
125
  max_pages: 1,
116
- max_output_bytes: self.remaining,
126
+ max_output_bytes: *remaining,
117
127
  ..self.options.clone()
118
128
  };
119
129
  match attempt(&selection) {
@@ -122,14 +132,14 @@ impl Recovery {
122
132
  return Err(Error::malformed("PDF worker", "inconsistent recovery metadata"));
123
133
  }
124
134
  let page = single.pages.remove(0);
125
- self.remaining -= page.text.len();
135
+ *remaining = remaining.saturating_sub(page.text.len());
126
136
  result.pages[index] = page;
127
137
  }
128
138
  Err(error @ Error::LimitExceeded(reason)) if reason != "PDF worker output" => {
129
139
  // A retry can expire while spooling, before metadata exists.
130
140
  // Keep the prefix even then; no attempt renews the outer clock.
131
141
  if Instant::now() >= deadline {
132
- return Ok(self.result.take());
142
+ return Ok(self.finish());
133
143
  }
134
144
  let status = if stream::expired(&error) { Status::Skipped } else { Status::Failed };
135
145
  result.pages[index] = bounded::unread(number, status, error.to_string());
@@ -138,7 +148,7 @@ impl Recovery {
138
148
  // records. Infrastructure/protocol errors are not page damage.
139
149
  Err(error) => return Err(error),
140
150
  }
141
- self.pending.pop();
151
+ pending.pop();
142
152
  Ok(self.settle())
143
153
  }
144
154
 
@@ -152,7 +162,19 @@ impl Recovery {
152
162
  Ok(*self.deadline.insert(deadline))
153
163
  }
154
164
 
155
- const fn settle(&mut self) -> Option<Pages> {
156
- if self.pending.is_empty() || self.remaining == 0 { self.result.take() } else { None }
165
+ fn settle(&mut self) -> Option<Pages> {
166
+ match &self.phase {
167
+ Phase::Singles { pending, remaining, .. } if pending.is_empty() || *remaining == 0 => {
168
+ self.finish()
169
+ }
170
+ _ => None,
171
+ }
172
+ }
173
+
174
+ fn finish(&mut self) -> Option<Pages> {
175
+ match mem::replace(&mut self.phase, Phase::Done) {
176
+ Phase::Singles { result, .. } => Some(result),
177
+ Phase::Batch | Phase::Done => None,
178
+ }
157
179
  }
158
180
  }
@@ -42,6 +42,7 @@ pub use content::{
42
42
  pub(crate) use image::png;
43
43
  pub use image::{Image, ImageFormat, ImageLocation};
44
44
  pub(crate) use image::{PngColor, png_with_transparency};
45
+ pub use markdown::{Section, SectionKind, TableLines};
45
46
 
46
47
  use crate::zip::reader::ZipReader;
47
48
  use crate::{Error, Result};
@@ -123,6 +124,17 @@ pub fn markdown(document: &[u8], limits: &Limits) -> Result<String> {
123
124
  Ok(content.to_markdown())
124
125
  }
125
126
 
127
+ /// Reads a document as Markdown with its outline: [`content`], then
128
+ /// [`Content::to_markdown_outline`].
129
+ ///
130
+ /// # Errors
131
+ /// As [`markdown`].
132
+ pub fn markdown_outline(document: &[u8], limits: &Limits) -> Result<(String, Vec<Section>)> {
133
+ let content = content(document, limits)?;
134
+ content.ensure_text_layer()?;
135
+ Ok(content.to_markdown_outline())
136
+ }
137
+
126
138
  /// Calls `each` with every image in a document, as a file.
127
139
  ///
128
140
  /// A PDF's images come once each, from the first page that draws them; a
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "imprimatur_native"
3
- version = "0.8.1"
3
+ version = "0.9.1"
4
4
  description = "Ruby bindings for the imprimatur crate"
5
5
  publish = false
6
6
  edition.workspace = true
@@ -19,4 +19,5 @@ workspace = true
19
19
  imprimatur = { workspace = true, features = ["archive", "fonts", "json", "isolation"] }
20
20
  serde_json.workspace = true
21
21
  magnus.workspace = true
22
+ matryona-machines = { workspace = true, features = ["ruby"] }
22
23
  rb-sys.workspace = true
@@ -143,5 +143,5 @@ pub fn define(ruby: &Ruby, imprimatur: magnus::RModule) -> Result<(), Error> {
143
143
  class.define_method("width", method!(Barcode::width, 0))?;
144
144
  class.define_method("height", method!(Barcode::height, 0))?;
145
145
  class.define_method("modules", method!(Barcode::modules, 0))?;
146
- Ok(())
146
+ matryona_machines::ruby::Class::pin_wrapped::<Barcode>(ruby, class).map(drop)
147
147
  }
@@ -0,0 +1,52 @@
1
+ //! Classes resolved once at load and pinned.
2
+
3
+ use std::sync::OnceLock;
4
+
5
+ use magnus::{Error, ExceptionClass, RClass, RModule, Ruby, prelude::*};
6
+ use matryona_machines::ruby::Class;
7
+
8
+ pub struct Classes {
9
+ pub formula: Class,
10
+ pub error: Class,
11
+ pub no_text_layer: Class,
12
+ pub password_required: Class,
13
+ pub unsupported_document: Class,
14
+ pub limit_exceeded: Class,
15
+ }
16
+
17
+ matryona_machines::registry! {
18
+ static CLASSES: Classes = "imprimatur";
19
+ pub fn classes;
20
+ }
21
+
22
+ pub fn resolve(ruby: &Ruby, imprimatur: RModule) -> Result<(), Error> {
23
+ let class = |name| Class::resolve(ruby, imprimatur, name);
24
+ let classes = Classes {
25
+ formula: class("Formula")?,
26
+ error: class("Error")?,
27
+ no_text_layer: class("NoTextLayer")?,
28
+ password_required: class("PasswordRequired")?,
29
+ unsupported_document: class("UnsupportedDocument")?,
30
+ limit_exceeded: class("LimitExceeded")?,
31
+ };
32
+ CLASSES.set(ruby, classes).map(drop)
33
+ }
34
+
35
+ pub fn exception(ruby: &Ruby, class: Class) -> ExceptionClass {
36
+ ExceptionClass::from_value(class.get(ruby).as_value())
37
+ .unwrap_or_else(|| ruby.exception_standard_error())
38
+ }
39
+
40
+ /// `Date` is only there once something has required 'date'.
41
+ pub fn date(ruby: &Ruby) -> Result<Option<RClass>, Error> {
42
+ static DATE: OnceLock<Class> = OnceLock::new();
43
+ if let Some(class) = DATE.get() {
44
+ return Ok(Some(class.get(ruby)));
45
+ }
46
+ let object = ruby.class_object();
47
+ if !object.funcall::<_, _, bool>("const_defined?", ("Date",))? {
48
+ return Ok(None);
49
+ }
50
+ let class: RClass = object.const_get("Date")?;
51
+ Ok(Some(DATE.get_or_init(|| Class::pin(ruby, class)).get(ruby)))
52
+ }
@@ -2,32 +2,17 @@
2
2
 
3
3
  use imprimatur::xlsx::{Cell, DateTime};
4
4
  use magnus::prelude::*;
5
- use magnus::{Error, Float, Integer, RClass, RString, Ruby, Value};
5
+ use magnus::{Error, Float, Integer, RString, Ruby, Value};
6
6
 
7
+ use crate::classes::{self, classes};
7
8
  use crate::{OrRaise, domain_error};
8
9
 
9
10
  /// The largest integer every `f64` neighbour of which is also an integer:
10
11
  /// beyond it, Excel would silently store a different number.
11
12
  const MAX_EXACT_INTEGER: u64 = 1 << 53;
12
13
 
13
- /// Ruby classes looked up once per call, not once per cell.
14
- pub struct Classes {
15
- formula: RClass,
16
- date: Option<RClass>,
17
- }
18
-
19
- impl Classes {
20
- pub fn load(ruby: &Ruby) -> Result<Self, Error> {
21
- let imprimatur: magnus::RModule = ruby.class_object().const_get("Imprimatur")?;
22
- // Date is only there once something has required 'date'.
23
- let date_defined: bool = ruby.class_object().funcall("const_defined?", ("Date",))?;
24
- let date = if date_defined { Some(ruby.class_object().const_get("Date")?) } else { None };
25
- Ok(Self { formula: imprimatur.const_get("Formula")?, date })
26
- }
27
- }
28
-
29
14
  /// `nil` is no cell.
30
- pub fn to_cell(ruby: &Ruby, value: Value, classes: &Classes) -> Result<Option<Cell>, Error> {
15
+ pub fn to_cell(ruby: &Ruby, value: Value) -> Result<Option<Cell>, Error> {
31
16
  if value.is_nil() {
32
17
  return Ok(None);
33
18
  }
@@ -46,14 +31,14 @@ pub fn to_cell(ruby: &Ruby, value: Value, classes: &Classes) -> Result<Option<Ce
46
31
  if value.is_kind_of(ruby.class_false_class()) {
47
32
  return Ok(Some(Cell::Bool(false)));
48
33
  }
49
- if value.is_kind_of(classes.formula) {
34
+ if value.is_kind_of(classes(ruby)?.formula.get(ruby)) {
50
35
  let expression: String = value.funcall("expression", ())?;
51
36
  return Ok(Some(Cell::formula(expression)));
52
37
  }
53
38
  if value.is_kind_of(ruby.class_time()) {
54
39
  return time_cell(ruby, value).map(Some);
55
40
  }
56
- if let Some(date) = classes.date
41
+ if let Some(date) = classes::date(ruby)?
57
42
  && value.is_kind_of(date)
58
43
  {
59
44
  // DateTime is a Date with a time of day; a plain Date has none.
@@ -215,5 +215,5 @@ pub fn define(ruby: &Ruby, native: RModule) -> Result<(), Error> {
215
215
  class.define_method("page_break", method!(NativeDocument::page_break, 0))?;
216
216
  class.define_method("render", method!(NativeDocument::render, 1))?;
217
217
  class.define_method("save", method!(NativeDocument::save, 2))?;
218
- Ok(())
218
+ matryona_machines::ruby::Class::pin_wrapped::<NativeDocument>(ruby, class).map(drop)
219
219
  }
@@ -6,6 +6,7 @@
6
6
  mod archive;
7
7
  mod barcode;
8
8
  mod blocking;
9
+ mod classes;
9
10
  mod convert;
10
11
  mod document;
11
12
  mod pdf;
@@ -18,12 +19,11 @@ use std::cell::{RefCell, RefMut};
18
19
 
19
20
  use imprimatur::style::{Align, TextDirection};
20
21
  use imprimatur::xlsx::{CellRange, Comment, Workbook, Worksheet, parse_cell_reference};
21
- use magnus::{
22
- Error, ExceptionClass, RArray, RModule, RString, Ruby, TryConvert, Value, function, method,
23
- prelude::*,
24
- };
22
+ use magnus::{Error, RArray, RString, Ruby, TryConvert, Value, function, method, prelude::*};
25
23
 
26
- use convert::{Classes, to_cell};
24
+ use classes::classes;
25
+ use convert::to_cell;
26
+ use matryona_machines::ruby::Class;
27
27
  use style::Style;
28
28
  use validation::Validation;
29
29
 
@@ -53,10 +53,9 @@ impl NativeWorkbook {
53
53
  ) -> Result<(), Error> {
54
54
  // Convert before borrowing: a Formula's #expression or a Date's
55
55
  // #year is Ruby code that could call back into this workbook.
56
- let classes = Classes::load(ruby)?;
57
56
  let mut row = Vec::with_capacity(cells.len());
58
57
  for value in cells {
59
- row.push(to_cell(ruby, value, &classes)?);
58
+ row.push(to_cell(ruby, value)?);
60
59
  }
61
60
  let styles = row_styles(ruby, style, row.len())?;
62
61
  let mut book = borrow(ruby, &rb_self.0, "workbook")?;
@@ -75,7 +74,7 @@ impl NativeWorkbook {
75
74
  style: Option<&Style>,
76
75
  ) -> Result<(), Error> {
77
76
  let (sheet, row, column) = position;
78
- let cell = to_cell(ruby, value, &Classes::load(ruby)?)?
77
+ let cell = to_cell(ruby, value)?
79
78
  .ok_or_else(|| argument_error(ruby, "a cell cannot be set to nil"))?;
80
79
  let mut book = borrow(ruby, &rb_self.0, "workbook")?;
81
80
  let sheet = sheet_mut(ruby, &mut book, sheet)?;
@@ -281,21 +280,20 @@ fn domain_error(ruby: &Ruby, error: &imprimatur::Error) -> Error {
281
280
  if let imprimatur::Error::InvalidPdfOption(message) = error {
282
281
  return argument_error(ruby, *message);
283
282
  }
284
- let name = match error {
285
- imprimatur::Error::NoTextLayer => "NoTextLayer",
286
- imprimatur::Error::PasswordRequired => "PasswordRequired",
287
- imprimatur::Error::UnsupportedDocument(_) => "UnsupportedDocument",
288
- imprimatur::Error::LimitExceeded(_) | imprimatur::Error::Cancelled => "LimitExceeded",
289
- _ => "Error",
283
+ let classes = match classes(ruby) {
284
+ Ok(classes) => classes,
285
+ Err(unloaded) => return unloaded,
290
286
  };
291
- let class = ruby
292
- .class_object()
293
- .const_get::<_, RModule>("Imprimatur")
294
- .and_then(|module| module.const_get::<_, ExceptionClass>(name));
295
- match class {
296
- Ok(class) => Error::new(class, error.to_string()),
297
- Err(lookup) => lookup,
298
- }
287
+ let class = match error {
288
+ imprimatur::Error::NoTextLayer => classes.no_text_layer,
289
+ imprimatur::Error::PasswordRequired => classes.password_required,
290
+ imprimatur::Error::UnsupportedDocument(_) => classes.unsupported_document,
291
+ imprimatur::Error::LimitExceeded(_) | imprimatur::Error::Cancelled => {
292
+ classes.limit_exceeded
293
+ }
294
+ _ => classes.error,
295
+ };
296
+ Error::new(classes::exception(ruby, class), error.to_string())
299
297
  }
300
298
 
301
299
  /// The value for a symbol among `choices`, or an `ArgumentError` naming them.
@@ -316,10 +314,13 @@ fn keyword<T: Copy>(
316
314
  #[magnus::init]
317
315
  fn init(ruby: &Ruby) -> Result<(), Error> {
318
316
  let imprimatur = ruby.define_module("Imprimatur")?;
317
+ classes::resolve(ruby, imprimatur)?;
319
318
  let style = imprimatur.define_class("Style", ruby.class_object())?;
320
319
  style.define_singleton_method("__build", function!(Style::build, 13))?;
320
+ Class::pin_wrapped::<Style>(ruby, style)?;
321
321
  let validation = imprimatur.define_class("Validation", ruby.class_object())?;
322
322
  validation.define_singleton_method("__build", function!(Validation::build, 8))?;
323
+ Class::pin_wrapped::<Validation>(ruby, validation)?;
323
324
  barcode::define(ruby, imprimatur)?;
324
325
 
325
326
  let native = imprimatur.define_module("Native")?;
@@ -336,12 +337,14 @@ fn init(ruby: &Ruby) -> Result<(), Error> {
336
337
  zip_writer.define_method("add", method!(archive::ZipWriter::add, 3))?;
337
338
  zip_writer.define_method("comment=", method!(archive::ZipWriter::set_comment, 1))?;
338
339
  zip_writer.define_method("finish", method!(archive::ZipWriter::finish, 0))?;
340
+ Class::pin_wrapped::<archive::ZipWriter>(ruby, zip_writer)?;
339
341
  let zip_reader = native.define_class("ZipReader", ruby.class_object())?;
340
342
  zip_reader.define_singleton_method("new", function!(archive::ZipReader::new, 1))?;
341
343
  zip_reader.define_method("names", method!(archive::ZipReader::names, 0))?;
342
344
  zip_reader.define_method("entries", method!(archive::ZipReader::entries, 0))?;
343
345
  zip_reader.define_method("read", method!(archive::ZipReader::read, 2))?;
344
346
  zip_reader.define_method("extract", method!(archive::ZipReader::extract, 3))?;
347
+ Class::pin_wrapped::<archive::ZipReader>(ruby, zip_reader)?;
345
348
  document::define(ruby, native)?;
346
349
  let workbook = native.define_class("Workbook", ruby.class_object())?;
347
350
  workbook.define_singleton_method("new", function!(NativeWorkbook::new, 0))?;
@@ -357,5 +360,5 @@ fn init(ruby: &Ruby) -> Result<(), Error> {
357
360
  workbook.define_method("next_row", method!(NativeWorkbook::next_row, 1))?;
358
361
  workbook.define_method("render", method!(NativeWorkbook::render, 0))?;
359
362
  workbook.define_method("save", method!(NativeWorkbook::save, 1))?;
360
- Ok(())
363
+ Class::pin_wrapped::<NativeWorkbook>(ruby, workbook).map(drop)
361
364
  }
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Imprimatur
4
- VERSION = '0.8.1'
4
+ VERSION = '0.9.1'
5
5
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: imprimatur
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.8.1
4
+ version: 0.9.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Abdelkader Boudih
@@ -156,6 +156,7 @@ files:
156
156
  - ext/imprimatur_native/ffi/src/archive.rs
157
157
  - ext/imprimatur_native/ffi/src/barcode.rs
158
158
  - ext/imprimatur_native/ffi/src/blocking.rs
159
+ - ext/imprimatur_native/ffi/src/classes.rs
159
160
  - ext/imprimatur_native/ffi/src/convert.rs
160
161
  - ext/imprimatur_native/ffi/src/document.rs
161
162
  - ext/imprimatur_native/ffi/src/lib.rs