Skip to content

Commit

Permalink
performance: slightly faster line wrap
Browse files Browse the repository at this point in the history
  • Loading branch information
hukkin authored Nov 13, 2024
1 parent 49cc084 commit 6da0ca6
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 4 deletions.
9 changes: 9 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,15 @@ commands = [
["python", "fuzzer/fuzz.py", "{toxworkdir}/fuzzer-corpus", { replace = "posargs", default = ["-len_control=10000"], extend = true }],
]

[tool.tox.env."benchmark"]
description = "benchmark mdformat against local doc files"
commands = [
["python", "-c", "print('Wrap mode: keep')"],
["python", "-m", "timeit", "from mdformat._cli import run", 'run(["README.md", "docs/", "--check"])'],
["python", "-c", "print('Wrap mode: 50')"],
["python", "-m", "timeit", "from mdformat._cli import run", 'run(["README.md", "docs/", "--check", "--wrap", "50"])'],
]


[tool.coverage.run]
source = ["mdformat"]
Expand Down
7 changes: 3 additions & 4 deletions src/mdformat/renderer/_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
# A marker used to indicate location of a character that should be preserved
# during word wrap. Should be converted to the actual character after wrap.
PRESERVE_CHAR = "\x00"
RE_PRESERVE_CHAR = re.compile(re.escape(PRESERVE_CHAR))


def make_render_children(separator: str) -> Render:
Expand Down Expand Up @@ -372,10 +373,8 @@ def _prepare_wrap(text: str) -> tuple[str, str]:


def _recover_preserve_chars(text: str, replacements: str) -> str:
replacement_iterator = iter(replacements)
return "".join(
next(replacement_iterator) if c == PRESERVE_CHAR else c for c in text
)
iter_replacements = iter(replacements)
return RE_PRESERVE_CHAR.sub(lambda _: next(iter_replacements), text)


def paragraph(node: RenderTreeNode, context: RenderContext) -> str: # noqa: C901
Expand Down
2 changes: 2 additions & 0 deletions tests/test_for_profiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,5 @@ def test_for_profiler():
docs_path = PROJECT_ROOT / "docs"
readme_path = PROJECT_ROOT / "README.md"
assert run([str(docs_path), str(readme_path), "--check"]) == 0
# Also profile --wrap=INT code
run([str(docs_path), str(readme_path), "--check", "--wrap", "50"])

0 comments on commit 6da0ca6

Please sign in to comment.