ops-rs 1.63.594

A Rust ops framework with composable wrappers and batch execution
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
use crate::prelude::*;
use serde::{Deserialize, Serialize};
use serde_json::json;

/// A hierarchical table of contents entry that can represent various Outline structures
///
/// This flexible model can handle:
/// - Simple flat TOCs: title + page
/// - Chapter-based TOCs: chapters with subsections
/// - Part-based TOCs: parts with chapters with sections
/// - Mixed hierarchies: any combination of the above
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OutlineEntry {
    /// The title/heading text (required)
    pub title: String,

    /// Page number or range (e.g., "15", "15-20", "iv", "A-1")
    /// Optional because some entries might be section dividers
    pub page: Option<String>,

    /// Hierarchical level (0 = top level, 1 = subsection, etc.)
    /// Helps maintain structure without complex nesting
    pub level: u8,

    /// Optional type/category for semantic meaning
    /// Examples: "part", "chapter", "section", "appendix", "index"
    pub entry_type: Option<String>,

    /// Child entries for hierarchical structures
    /// Empty for leaf entries
    pub children: Vec<OutlineEntry>,
}

impl OutlineEntry {
    pub fn new(title: String, page: Option<String>, level: u8) -> Self {
        Self {
            title,
            page,
            level,
            entry_type: None,
            children: Vec::new(),
        }
    }

    pub fn with_type(mut self, entry_type: String) -> Self {
        self.entry_type = Some(entry_type);
        self
    }

    pub fn with_children(mut self, children: Vec<OutlineEntry>) -> Self {
        self.children = children;
        self
    }

    /// Add a child entry
    pub fn add_child(&mut self, child: OutlineEntry) {
        self.children.push(child);
    }

    /// Get all entries flattened with their hierarchical context
    pub fn flatten(&self) -> Vec<FlatOutlineEntry> {
        let mut result = Vec::new();
        self.flatten_recursive(&mut result, Vec::new());
        result
    }

    fn flatten_recursive(&self, result: &mut Vec<FlatOutlineEntry>, mut path: Vec<String>) {
        path.push(self.title.clone());

        result.push(FlatOutlineEntry {
            title: self.title.clone(),
            page: self.page.clone(),
            level: self.level,
            entry_type: self.entry_type.clone(),
            path: path.clone(),
        });

        for child in &self.children {
            child.flatten_recursive(result, path.clone());
        }
    }
}

/// A flattened representation of a Outline entry with full hierarchical path
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FlatOutlineEntry {
    pub title: String,
    pub page: Option<String>,
    pub level: u8,
    pub entry_type: Option<String>,
    /// Full path from root to this entry (e.g., ["Part I", "Chapter 1", "Section 1.1"])
    pub path: Vec<String>,
}

/// Complete table of contents structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ListingOutline {
    /// Document title (optional)
    pub document_title: Option<String>,

    /// Main Outline entries
    pub entries: Vec<OutlineEntry>,

    /// Extraction confidence (0.0 - 1.0)
    pub confidence: f64,

    /// Additional metadata about the Outline structure
    pub metadata: OutlineMetadata,
}

impl ListingOutline {
    pub fn new() -> Self {
        Self {
            document_title: None,
            entries: Vec::new(),
            confidence: 0.0,
            metadata: OutlineMetadata::default(),
        }
    }

    /// Get all entries as a flat list
    pub fn flatten(&self) -> Vec<FlatOutlineEntry> {
        self.entries
            .iter()
            .flat_map(|entry| entry.flatten())
            .collect()
    }

    /// Get entries at a specific level
    pub fn entries_at_level(&self, level: u8) -> Vec<&OutlineEntry> {
        fn collect_at_level<'a>(
            entries: &'a [OutlineEntry],
            target_level: u8,
            result: &mut Vec<&'a OutlineEntry>,
        ) {
            for entry in entries {
                if entry.level == target_level {
                    result.push(entry);
                }
                collect_at_level(&entry.children, target_level, result);
            }
        }

        let mut result = Vec::new();
        collect_at_level(&self.entries, level, &mut result);
        result
    }

    /// Get the maximum depth of the Outline
    pub fn max_depth(&self) -> u8 {
        fn max_depth_recursive(entries: &[OutlineEntry]) -> u8 {
            entries
                .iter()
                .map(|entry| {
                    let child_depth = if entry.children.is_empty() {
                        0
                    } else {
                        max_depth_recursive(&entry.children)
                    };
                    entry.level.max(child_depth)
                })
                .max()
                .unwrap_or(0)
        }

        max_depth_recursive(&self.entries)
    }
}

impl Default for ListingOutline {
    fn default() -> Self {
        Self::new()
    }
}

/// Metadata about the table of contents structure
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct OutlineMetadata {
    /// Detected Outline style (e.g., "numeric", "roman", "alphabetic", "mixed")
    pub numbering_style: Option<String>,

    /// Whether the Outline uses dots or other leaders
    pub has_leaders: bool,

    /// Page numbering style (e.g., "arabic", "roman", "mixed")
    pub page_style: Option<String>,

    /// Total number of entries
    pub total_entries: usize,

    /// Number of hierarchical levels
    pub levels: u8,

    /// Detected structure type (e.g., "chapters", "parts_chapters", "sections")
    pub structure_type: Option<String>,
}

/// JSON Schema generation for table of contents
pub fn generate_outline_schema() -> serde_json::Value {
    json!({
        "$schema": "http://json-schema.org/draft-07/schema#",
        "title": "Table of Contents",
        "description": "Hierarchical table of contents structure that can represent various Outline formats",
        "type": "object",
        "properties": {
            "document_title": {
                "type": ["string", "null"],
                "description": "Title of the document (optional)"
            },
            "entries": {
                "type": "array",
                "description": "Main table of contents entries",
                "items": {
                    "$ref": "#/definitions/OutlineEntry"
                }
            },
            "confidence": {
                "type": "number",
                "minimum": 0.0,
                "maximum": 1.0,
                "description": "Confidence level of the extraction (0.0 - 1.0)"
            },
            "metadata": {
                "$ref": "#/definitions/OutlineMetadata"
            }
        },
        "required": ["entries", "confidence"],
        "definitions": {
            "OutlineEntry": {
                "type": "object",
                "description": "A single table of contents entry with optional hierarchy",
                "properties": {
                    "title": {
                        "type": "string",
                        "description": "The heading or title text"
                    },
                    "page": {
                        "type": ["string", "null"],
                        "description": "Page number or range (e.g., '15', '15-20', 'iv', 'A-1')"
                    },
                    "level": {
                        "type": "integer",
                        "minimum": 0,
                        "maximum": 10,
                        "description": "Hierarchical level (0 = top level, 1 = subsection, etc.)"
                    },
                    "entry_type": {
                        "type": ["string", "null"],
                        "description": "Optional semantic type (e.g., 'part', 'chapter', 'section', 'appendix')",
                        "enum": ["part", "chapter", "section", "subsection", "appendix", "index", "bibliography", "preface", "introduction", "conclusion", null]
                    },
                    "children": {
                        "type": "array",
                        "description": "Child entries for hierarchical structures",
                        "items": {
                            "$ref": "#/definitions/OutlineEntry"
                        }
                    }
                },
                "required": ["title", "level"]
            },
            "OutlineMetadata": {
                "type": "object",
                "description": "Metadata about the table of contents structure",
                "properties": {
                    "numbering_style": {
                        "type": ["string", "null"],
                        "description": "Detected numbering style",
                        "enum": ["numeric", "roman", "alphabetic", "mixed", null]
                    },
                    "has_leaders": {
                        "type": "boolean",
                        "description": "Whether the Outline uses dots or other leaders"
                    },
                    "page_style": {
                        "type": ["string", "null"],
                        "description": "Page numbering style",
                        "enum": ["arabic", "roman", "alphabetic", "mixed", null]
                    },
                    "total_entries": {
                        "type": "integer",
                        "minimum": 0,
                        "description": "Total number of entries"
                    },
                    "levels": {
                        "type": "integer",
                        "minimum": 1,
                        "maximum": 10,
                        "description": "Number of hierarchical levels"
                    },
                    "structure_type": {
                        "type": ["string", "null"],
                        "description": "Detected overall structure type",
                        "enum": ["flat", "chapters", "parts_chapters", "sections", "mixed", null]
                    }
                },
                "required": ["has_leaders", "total_entries", "levels"]
            }
        }
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    // TEST0024: Build a flat ListingOutline with depth-0 entries and verify max_depth, levels, and flatten count
    #[test]
    fn test0024_simple_flat_outline() {
        let mut outline = ListingOutline::new();
        outline.entries = vec![
            OutlineEntry::new("Introduction".to_string(), Some("1".to_string()), 0),
            OutlineEntry::new(
                "Chapter 1: Getting Started".to_string(),
                Some("5".to_string()),
                0,
            ),
            OutlineEntry::new(
                "Chapter 2: Advanced Topics".to_string(),
                Some("15".to_string()),
                0,
            ),
            OutlineEntry::new("Conclusion".to_string(), Some("25".to_string()), 0),
        ];

        assert_eq!(outline.max_depth(), 0);
        assert_eq!(outline.entries_at_level(0).len(), 4);
        assert_eq!(outline.flatten().len(), 4);
    }

    // TEST0025: Build a two-level outline with chapters and sections and verify depth, level counts, and flatten
    #[test]
    fn test0025_hierarchical_outline() {
        let mut outline = ListingOutline::new();

        let mut chapter1 =
            OutlineEntry::new("Chapter 1: Basics".to_string(), Some("10".to_string()), 0)
                .with_type("chapter".to_string());
        chapter1.add_child(OutlineEntry::new(
            "1.1 Introduction".to_string(),
            Some("10".to_string()),
            1,
        ));
        chapter1.add_child(OutlineEntry::new(
            "1.2 Fundamentals".to_string(),
            Some("15".to_string()),
            1,
        ));

        let mut chapter2 =
            OutlineEntry::new("Chapter 2: Advanced".to_string(), Some("20".to_string()), 0)
                .with_type("chapter".to_string());
        chapter2.add_child(OutlineEntry::new(
            "2.1 Complex Topics".to_string(),
            Some("20".to_string()),
            1,
        ));

        outline.entries = vec![chapter1, chapter2];

        assert_eq!(outline.max_depth(), 1);
        assert_eq!(outline.entries_at_level(0).len(), 2);
        assert_eq!(outline.entries_at_level(1).len(), 3);
        assert_eq!(outline.flatten().len(), 5); // 2 chapters + 3 sections
    }

    // TEST0026: Build a three-level part/chapter/section outline and verify depth and per-level entry counts
    #[test]
    fn test0026_complex_part_based_outline() {
        let mut outline = ListingOutline::new();

        // Part I with chapters
        let mut part1 =
            OutlineEntry::new("Part I: Foundations".to_string(), Some("1".to_string()), 0)
                .with_type("part".to_string());

        let mut chapter1 = OutlineEntry::new(
            "Chapter 1: Introduction".to_string(),
            Some("3".to_string()),
            1,
        )
        .with_type("chapter".to_string());
        chapter1.add_child(OutlineEntry::new(
            "1.1 Overview".to_string(),
            Some("3".to_string()),
            2,
        ));
        chapter1.add_child(OutlineEntry::new(
            "1.2 Scope".to_string(),
            Some("5".to_string()),
            2,
        ));

        let chapter2 = OutlineEntry::new(
            "Chapter 2: Background".to_string(),
            Some("8".to_string()),
            1,
        )
        .with_type("chapter".to_string());

        part1.add_child(chapter1);
        part1.add_child(chapter2);

        // Part II
        let part2 = OutlineEntry::new(
            "Part II: Applications".to_string(),
            Some("15".to_string()),
            0,
        )
        .with_type("part".to_string());

        outline.entries = vec![part1, part2];

        assert_eq!(outline.max_depth(), 2);
        assert_eq!(outline.entries_at_level(0).len(), 2); // 2 parts
        assert_eq!(outline.entries_at_level(1).len(), 2); // 2 chapters
        assert_eq!(outline.entries_at_level(2).len(), 2); // 2 sections
        assert_eq!(outline.flatten().len(), 6); // 2 parts + 2 chapters + 2 sections
    }

    // TEST0027: Flatten a nested outline and verify each entry's path reflects its ancestry correctly
    #[test]
    fn test0027_flatten_preserves_hierarchy() {
        let mut outline = ListingOutline::new();

        let mut part = OutlineEntry::new("Part I".to_string(), Some("1".to_string()), 0);
        let mut chapter = OutlineEntry::new("Chapter 1".to_string(), Some("3".to_string()), 1);
        chapter.add_child(OutlineEntry::new(
            "Section 1.1".to_string(),
            Some("3".to_string()),
            2,
        ));
        part.add_child(chapter);
        outline.entries = vec![part];

        let flat = outline.flatten();
        assert_eq!(flat.len(), 3);

        // Check paths
        assert_eq!(flat[0].path, vec!["Part I"]);
        assert_eq!(flat[1].path, vec!["Part I", "Chapter 1"]);
        assert_eq!(flat[2].path, vec!["Part I", "Chapter 1", "Section 1.1"]);
    }

    // TEST0028: Call generate_outline_schema and verify the returned JSON contains all required definitions
    #[test]
    fn test0028_schema_generation() {
        let schema = generate_outline_schema();
        assert!(schema.is_object());
        assert!(schema["properties"]["entries"].is_object());
        assert!(schema["definitions"]["OutlineEntry"].is_object());
        assert!(schema["definitions"]["OutlineMetadata"].is_object());
    }
}