flow-toon-format 0.9.0b2__py3-none-any.whl

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.
toon_format/writer.py ADDED
@@ -0,0 +1,53 @@
1
+ # Copyright (c) 2025 TOON Format Organization
2
+ # SPDX-License-Identifier: MIT
3
+ """Line writer for managing indented TOON output.
4
+
5
+ Provides LineWriter class that manages indented text generation with optimized
6
+ indent string caching for performance.
7
+ """
8
+
9
+ from typing import Dict, List
10
+
11
+ from .types import Depth
12
+
13
+
14
+ class LineWriter:
15
+ """Manages indented text output with optimized indent caching."""
16
+
17
+ def __init__(self, indent_size: int) -> None:
18
+ """Initialize the line writer.
19
+
20
+ Args:
21
+ indent_size: Number of spaces per indentation level
22
+ """
23
+ self._lines: List[str] = []
24
+ # Ensure nested structures remain distinguishable even for indent=0
25
+ normalized_indent = indent_size if indent_size > 0 else 1
26
+ self._indentation_string = " " * normalized_indent
27
+ self._indent_cache: Dict[int, str] = {0: ""}
28
+ self._indent_size = indent_size
29
+
30
+ def push(self, depth: Depth, content: str) -> None:
31
+ """Add a line with appropriate indentation.
32
+
33
+ Args:
34
+ depth: Indentation depth level
35
+ content: Content to add
36
+ """
37
+ # Use cached indent string for performance
38
+ if depth not in self._indent_cache:
39
+ if self._indent_size == 0:
40
+ # indent=0 uses minimal spacing to preserve structure
41
+ self._indent_cache[depth] = " " * depth
42
+ else:
43
+ self._indent_cache[depth] = self._indentation_string * depth
44
+ indent = self._indent_cache[depth]
45
+ self._lines.append(indent + content)
46
+
47
+ def to_string(self) -> str:
48
+ """Return all lines joined with newlines.
49
+
50
+ Returns:
51
+ Complete output string
52
+ """
53
+ return "\n".join(self._lines)