From f51e583ddef136f6eb262c535f513cf66fccce51 Mon Sep 17 00:00:00 2001 From: Mason Lyons Date: Sun, 18 Oct 2026 14:44:06 +0000 Subject: [PATCH] Native truncatechars_html / truncatewords_html, filesizeformat and humanize intword - `truncatechars_html` / `truncatewords_html` ran Python's `HTMLParser` on every value. They are now a port of `TruncateCharsHTMLParser` / `TruncateWordsHTMLParser` for simple HTML (the grammar the native `striptags` accepts: plain tags with ordinary attributes and common entity references). On that grammar Python 3.12, 3.13 (old and new patch releases) and 3.14 produce identical output. Comments, raw-text elements, a stray `<` or `&`, unknown entities and non-`str` inputs run the stock `Truncator`. - `filesizeformat` (exact ints below 2**53) rounds the unit value with integer arithmetic and formats it through the native `floatformat` number formatter. - humanize `intword` (exact ints below 2**53) uses the same float division and `round_away_from_one` as stock, plus the native `floatformat`. Patched `ngettext`/`defaultfilters` globals take Python. - `Translator::cached` memoizes `gettext`/`ngettext` for static msgids per translation object. A catalog reload creates new objects, so the cache can't serve stale strings. - The truncation ellipsis cache now falls back when `django.utils.text.pgettext` is patched (this also covers `truncatechars`). gaps microbench (20-row loop, vs stock): truncatechars_html 1.2x -> 15x, truncatewords_html 1.2x -> 13x, intword 1.5x -> 15x, filesizeformat 1.4x -> 10x. New bench.py row truncate_html_sizes: 17.8x. Co-Authored-By: Claude Opus 5.5 --- README.md | 167 +++++++------- benchmarks/bench.py | 18 ++ benchmarks/jinja2_bench.py | 14 +- src/filters/floatformat.rs | 2 +- src/filters/humanize.rs | 99 ++++++++ src/filters/mod.rs | 72 +++++- src/filters/numbers.rs | 85 ++++++- src/filters/strings.rs | 26 ++- src/filters/truncate_html.rs | 426 +++++++++++++++++++++++++++++++++++ tests/test_realpage.py | 105 +++++++++ 10 files changed, 920 insertions(+), 94 deletions(-) create mode 100644 src/filters/truncate_html.rs diff --git a/README.md b/README.md index 75574e9..df74e60 100644 --- a/README.md +++ b/README.md @@ -120,8 +120,10 @@ template.render(Context({"user": {"name": "ada lovelace"}})) # 'Hello Ada Lovel - **Built-in tags and filters** run natively, including `extends`/`block`, `include`, `for`, `if`, `with`, `cycle`, `url`, `csrf_token`, Django 6.1 `partialdef`/`partial`, `{% translate "literal" %}`, `{% blocktranslate %}`, - `{% static %}`, and filters such as `date`, `floatformat`, `urlize`, `join` - and `striptags`, plus humanize's `intcomma` on integers and `naturaltime`. + `{% static %}`, and filters such as `date`, `floatformat`, `urlize`, `join`, + `striptags`, `truncatechars_html`/`truncatewords_html` and `filesizeformat`, + plus humanize's `naturaltime` and, on integers, `intcomma`, `intword` and + `ordinal`. - **Custom and third-party tag libraries** keep working. `simple_tag` and `inclusion_tag` run on native helper nodes. Other tags (custom compile functions, `simple_block_tag`) are @@ -141,43 +143,44 @@ stock Django. | scenario | render stock | render rust | render × | compile stock | compile rust | compile × | |---|---:|---:|---:|---:|---:|---:| -| simple_var | 12.1 µs | 2.7 µs | **4.54×** | 23.1 µs | 1.8 µs | **12.63×** | -| filter_chain | 71.2 µs | 5.9 µs | **12.15×** | 148.3 µs | 4.0 µs | **37.05×** | -| many_vars | 141.5 µs | 7.8 µs | **18.23×** | 511.1 µs | 31.2 µs | **16.40×** | -| loop | 4704.7 µs | 134.5 µs | **34.97×** | 96.8 µs | 5.3 µs | **18.39×** | -| if_branch | 1655.6 µs | 52.9 µs | **31.28×** | 113.4 µs | 7.2 µs | **15.69×** | -| attr_lookup | 1808.8 µs | 106.1 µs | **17.05×** | 166.5 µs | 9.1 µs | **18.29×** | -| autoescape | 701.2 µs | 44.1 µs | **15.90×** | 66.8 µs | 4.3 µs | **15.62×** | -| cycle_reset | 698.5 µs | 69.2 µs | **10.10×** | 117.2 µs | 6.8 µs | **17.12×** | -| firstof_widthratio | 30.0 µs | 3.1 µs | **9.71×** | 93.7 µs | 5.7 µs | **16.39×** | -| date_filter | 2972.9 µs | 90.4 µs | **32.87×** | 89.9 µs | 4.0 µs | **22.74×** | -| url_tag | 50.4 µs | 6.0 µs | **8.39×** | 40.0 µs | 2.5 µs | **16.10×** | -| include | 3121.2 µs | 322.1 µs | **9.69×** | 65.4 µs | 9.6 µs | **6.80×** | -| extends | 1626.4 µs | 42.9 µs | **37.89×** | 112.8 µs | 12.5 µs | **8.99×** | -| nested_table | 3542.3 µs | 112.4 µs | **31.53×** | 113.6 µs | 8.2 µs | **13.91×** | -| with_if_scopes | 89.7 µs | 11.5 µs | **7.81×** | 712.6 µs | 38.8 µs | **18.36×** | -| spaceless_table | 22.9 µs | 2.3 µs | **9.74×** | 12.0 µs | 1.7 µs | **7.03×** | -| bridged_simple_tag | 258.7 µs | 27.2 µs | **9.50×** | 72.7 µs | 17.1 µs | **4.25×** | -| cached_extends | 216.8 µs | 28.4 µs | **7.62×** | 1.2 µs | 0.3 µs | **3.56×** | -| value_types | 4478.1 µs | 274.1 µs | **16.34×** | 51.9 µs | 3.0 µs | **17.23×** | -| csrf_token_loop | 309.1 µs | 15.4 µs | **20.09×** | 43.0 µs | 3.2 µs | **13.52×** | -| inclusion_tag | 1101.3 µs | 160.4 µs | **6.87×** | 72.9 µs | 15.2 µs | **4.80×** | -| include_with | 3798.3 µs | 436.9 µs | **8.69×** | 101.7 µs | 13.8 µs | **7.37×** | -| index_none_lookup | 11495.9 µs | 195.5 µs | **58.82×** | 100.8 µs | 8.2 µs | **12.30×** | -| object_attrs | 2762.9 µs | 83.2 µs | **33.20×** | 78.3 µs | 6.3 µs | **12.43×** | -| object_methods | 1311.7 µs | 126.9 µs | **10.34×** | 65.8 µs | 5.3 µs | **12.43×** | -| object_properties | 2664.3 µs | 116.5 µs | **22.87×** | 96.8 µs | 7.5 µs | **12.91×** | -| realistic_page | 19429.3 µs | 1500.5 µs | **12.95×** | 1.2 µs | 0.3 µs | **3.54×** | -| floatformat | 12700.7 µs | 928.3 µs | **13.68×** | 222.7 µs | 8.4 µs | **26.52×** | -| urlize | 11147.1 µs | 307.5 µs | **36.25×** | 127.7 µs | 5.1 µs | **24.97×** | -| join | 3024.7 µs | 255.1 µs | **11.86×** | 139.6 µs | 5.2 µs | **26.73×** | -| i18n_tags | 3214.0 µs | 341.3 µs | **9.42×** | 166.7 µs | 14.6 µs | **11.44×** | -| aware_dates | 19388.1 µs | 1502.2 µs | **12.91×** | 226.6 µs | 8.2 µs | **27.67×** | -| localtime_block | 19006.7 µs | 1505.1 µs | **12.63×** | 243.8 µs | 50.4 µs | **4.84×** | -| simple_block_tag | 1820.6 µs | 118.0 µs | **15.43×** | 212.1 µs | 100.6 µs | **2.11×** | -| striptags_intcomma | 5082.3 µs | 617.9 µs | **8.22×** | 151.1 µs | 12.4 µs | **12.21×** | -| engine_e2e | 869.3 µs | 47.1 µs | **18.44×** | 70.4 µs | 8.4 µs | **8.42×** | -| **geomean** | | | **14.78×** | | | **11.85×** | +| simple_var | 12.4 µs | 2.6 µs | **4.74×** | 23.0 µs | 1.9 µs | **12.16×** | +| filter_chain | 71.1 µs | 5.8 µs | **12.20×** | 149.1 µs | 4.0 µs | **37.60×** | +| many_vars | 146.3 µs | 7.9 µs | **18.41×** | 512.9 µs | 31.5 µs | **16.26×** | +| loop | 4595.4 µs | 133.8 µs | **34.35×** | 96.6 µs | 5.4 µs | **17.96×** | +| if_branch | 1647.1 µs | 52.3 µs | **31.52×** | 113.1 µs | 7.7 µs | **14.71×** | +| attr_lookup | 1796.0 µs | 104.8 µs | **17.14×** | 164.1 µs | 9.2 µs | **17.76×** | +| autoescape | 697.9 µs | 41.8 µs | **16.69×** | 66.7 µs | 4.4 µs | **15.27×** | +| cycle_reset | 709.2 µs | 70.1 µs | **10.11×** | 115.7 µs | 6.6 µs | **17.51×** | +| firstof_widthratio | 29.9 µs | 3.0 µs | **9.88×** | 94.7 µs | 5.6 µs | **16.81×** | +| date_filter | 3038.9 µs | 91.9 µs | **33.06×** | 89.6 µs | 4.0 µs | **22.50×** | +| url_tag | 51.1 µs | 5.9 µs | **8.71×** | 39.8 µs | 2.5 µs | **16.20×** | +| include | 3075.3 µs | 313.4 µs | **9.81×** | 65.6 µs | 9.8 µs | **6.68×** | +| extends | 1626.7 µs | 40.3 µs | **40.38×** | 112.6 µs | 13.0 µs | **8.67×** | +| nested_table | 3516.5 µs | 105.3 µs | **33.40×** | 111.7 µs | 8.0 µs | **13.89×** | +| with_if_scopes | 89.1 µs | 10.7 µs | **8.36×** | 710.6 µs | 40.7 µs | **17.45×** | +| spaceless_table | 22.3 µs | 2.3 µs | **9.61×** | 11.9 µs | 1.7 µs | **7.15×** | +| bridged_simple_tag | 259.9 µs | 26.7 µs | **9.74×** | 72.6 µs | 17.1 µs | **4.24×** | +| cached_extends | 217.4 µs | 28.5 µs | **7.64×** | 1.2 µs | 0.3 µs | **3.64×** | +| value_types | 4411.6 µs | 276.0 µs | **15.98×** | 51.5 µs | 3.0 µs | **17.44×** | +| csrf_token_loop | 306.5 µs | 14.7 µs | **20.84×** | 43.1 µs | 3.2 µs | **13.28×** | +| inclusion_tag | 1085.7 µs | 155.2 µs | **6.99×** | 73.6 µs | 15.9 µs | **4.63×** | +| include_with | 3756.9 µs | 427.3 µs | **8.79×** | 101.5 µs | 14.7 µs | **6.91×** | +| index_none_lookup | 11742.6 µs | 202.2 µs | **58.08×** | 101.0 µs | 8.1 µs | **12.49×** | +| object_attrs | 2767.6 µs | 88.7 µs | **31.19×** | 78.2 µs | 6.1 µs | **12.75×** | +| object_methods | 1322.7 µs | 127.6 µs | **10.37×** | 65.6 µs | 5.2 µs | **12.70×** | +| object_properties | 2691.5 µs | 116.4 µs | **23.12×** | 97.3 µs | 7.5 µs | **13.00×** | +| realistic_page | 19678.7 µs | 1513.4 µs | **13.00×** | 1.2 µs | 0.3 µs | **3.56×** | +| floatformat | 12902.6 µs | 887.7 µs | **14.54×** | 221.1 µs | 8.3 µs | **26.79×** | +| urlize | 10992.3 µs | 302.1 µs | **36.38×** | 128.9 µs | 5.0 µs | **25.74×** | +| join | 3017.2 µs | 246.1 µs | **12.26×** | 139.8 µs | 5.1 µs | **27.39×** | +| i18n_tags | 3213.5 µs | 348.8 µs | **9.21×** | 168.5 µs | 14.3 µs | **11.82×** | +| aware_dates | 19351.8 µs | 1468.6 µs | **13.18×** | 226.5 µs | 8.3 µs | **27.31×** | +| localtime_block | 19014.6 µs | 1466.5 µs | **12.97×** | 244.5 µs | 53.3 µs | **4.58×** | +| simple_block_tag | 1808.2 µs | 121.4 µs | **14.89×** | 212.3 µs | 100.2 µs | **2.12×** | +| striptags_intcomma | 5095.0 µs | 616.6 µs | **8.26×** | 150.5 µs | 12.6 µs | **11.95×** | +| truncate_html_sizes | 14623.8 µs | 795.7 µs | **18.38×** | 203.6 µs | 15.9 µs | **12.84×** | +| engine_e2e | 865.5 µs | 46.0 µs | **18.82×** | 70.3 µs | 8.3 µs | **8.47×** | +| **geomean** | | | **15.06×** | | | **11.81×** | *Linux x86_64 (AMD EPYC 7601), Python 3.13.15, Django 6.1.2, release build.* @@ -196,8 +199,8 @@ production. `block.super`, an `{% include %}` per row, model-like objects with attributes, methods and properties, and the `date`, `floatformat`, `urlize` and `join` filters, all through the cached loader. -- The weakest rows are `simple_var` (4.5×, dominated by fixed per-render - overhead) and `inclusion_tag` (6.9×: the tag function is Python, and each +- The weakest rows are `simple_var` (4.7×, dominated by fixed per-render + overhead) and `inclusion_tag` (7.0×: the tag function is Python, and each call builds a fresh `Context` for the included template). - This measures template time only. A view's database queries and middleware are unaffected, so whole-request gains depend on how much of each request @@ -207,7 +210,7 @@ production. `{% url %}`, i18n tags, messages, a form and humanize filters. Python code that the page calls (context processors, form and widget classes, translation catalog lookups, bridged tags) runs at the same speed on both - engines, so this page is about 3.5× faster rather than 14×. + engines, so this page is about 3.5× faster rather than 15×. HTML escaping and the lexer's tag scanner use portable SIMD: `fearless_simd` picks SSE2 on x86_64 and NEON on aarch64, and `memchr` picks the best @@ -225,57 +228,59 @@ markupsafe writes `'` where Django writes `'`. | scenario | render stock | render jinja2 | render rust | rust vs jinja2 | |---|---:|---:|---:|---:| -| simple_var | 12.0 µs | 14.3 µs | 2.7 µs | **5.33×** | -| filter_chain | 71.1 µs | 55.6 µs | 6.1 µs | **9.15×** | -| many_vars | 144.3 µs | 42.3 µs | 7.8 µs | **5.39×** | -| loop | 4653.7 µs | 570.3 µs | 133.2 µs | **4.28×** | -| if_branch | 1701.7 µs | 52.0 µs | 53.2 µs | **0.98×** | -| attr_lookup | 1833.3 µs | 480.2 µs | 105.2 µs | **4.56×** | -| autoescape | 700.0 µs | 195.8 µs | 44.0 µs | **4.45×** | -| cycle_reset | 711.3 µs | 1087.3 µs | 69.1 µs | **15.73×** | -| firstof_widthratio | 29.6 µs | 18.8 µs | 3.1 µs | **6.06×** | -| date_filter | 3002.0 µs | 2410.8 µs | 90.2 µs | **26.73×** | -| url_tag | 49.5 µs | 52.6 µs | 6.2 µs | **8.49×** | -| include | 3004.0 µs | 868.7 µs | 292.5 µs | **2.97×** | -| extends | 1584.5 µs | 95.7 µs | 29.9 µs | **3.20×** | -| nested_table | 3510.4 µs | 129.2 µs | 113.9 µs | **1.13×** | -| with_if_scopes | 89.6 µs | 14.4 µs | 11.5 µs | **1.25×** | -| bridged_simple_tag | 262.9 µs | 121.0 µs | 26.6 µs | **4.54×** | -| cached_extends | 216.4 µs | 56.2 µs | 29.4 µs | **1.91×** | -| csrf_token_loop | 305.6 µs | 53.7 µs | 15.6 µs | **3.44×** | -| include_with | 3710.0 µs | 1154.2 µs | 409.9 µs | **2.82×** | -| index_none_lookup | 11651.0 µs | 228.6 µs | 182.8 µs | **1.25×** | -| object_attrs | 2772.3 µs | 229.0 µs | 84.3 µs | **2.72×** | -| object_methods | 1312.9 µs | 501.0 µs | 130.2 µs | **3.85×** | -| object_properties | 2654.3 µs | 356.5 µs | 115.0 µs | **3.10×** | -| realistic_page | 19718.0 µs | 14614.8 µs | 1545.2 µs | **9.46×** | -| floatformat | 12645.9 µs | 10625.2 µs | 915.1 µs | **11.61×** | -| urlize | 11024.5 µs | 10533.8 µs | 301.8 µs | **34.90×** | -| join | 3008.8 µs | 1017.1 µs | 244.0 µs | **4.17×** | -| i18n_tags | 3215.7 µs | 2570.9 µs | 347.5 µs | **7.40×** | -| aware_dates | 19147.8 µs | 15566.0 µs | 1548.9 µs | **10.05×** | -| striptags_intcomma | 5154.6 µs | 4344.5 µs | 618.3 µs | **7.03×** | -| engine_e2e | 784.8 µs | 45.8 µs | 18.0 µs | **2.54×** | -| **geomean** | | | | **4.64×** | +| simple_var | 12.0 µs | 14.3 µs | 2.7 µs | **5.37×** | +| filter_chain | 70.5 µs | 55.7 µs | 5.8 µs | **9.55×** | +| many_vars | 145.0 µs | 41.8 µs | 7.5 µs | **5.55×** | +| loop | 4687.9 µs | 573.3 µs | 131.4 µs | **4.36×** | +| if_branch | 1653.0 µs | 52.3 µs | 52.3 µs | **1.00×** | +| attr_lookup | 1839.5 µs | 469.1 µs | 101.6 µs | **4.62×** | +| autoescape | 705.1 µs | 199.1 µs | 42.8 µs | **4.65×** | +| cycle_reset | 726.1 µs | 1095.8 µs | 69.6 µs | **15.75×** | +| firstof_widthratio | 30.1 µs | 18.8 µs | 3.0 µs | **6.22×** | +| date_filter | 2992.4 µs | 2406.9 µs | 90.9 µs | **26.47×** | +| url_tag | 50.2 µs | 52.8 µs | 6.0 µs | **8.78×** | +| include | 3006.5 µs | 865.6 µs | 292.6 µs | **2.96×** | +| extends | 1641.8 µs | 94.5 µs | 28.7 µs | **3.29×** | +| nested_table | 3562.6 µs | 127.7 µs | 108.5 µs | **1.18×** | +| with_if_scopes | 88.5 µs | 14.5 µs | 10.5 µs | **1.38×** | +| bridged_simple_tag | 262.9 µs | 121.2 µs | 26.7 µs | **4.54×** | +| cached_extends | 217.2 µs | 56.3 µs | 28.8 µs | **1.95×** | +| csrf_token_loop | 313.4 µs | 52.8 µs | 14.8 µs | **3.56×** | +| include_with | 3764.5 µs | 1162.4 µs | 390.4 µs | **2.98×** | +| index_none_lookup | 11763.6 µs | 220.9 µs | 193.1 µs | **1.14×** | +| object_attrs | 2788.8 µs | 231.4 µs | 86.1 µs | **2.69×** | +| object_methods | 1321.7 µs | 498.0 µs | 122.9 µs | **4.05×** | +| object_properties | 2684.8 µs | 350.2 µs | 114.0 µs | **3.07×** | +| realistic_page | 19678.5 µs | 14524.2 µs | 1500.0 µs | **9.68×** | +| floatformat | 12933.4 µs | 10654.0 µs | 885.6 µs | **12.03×** | +| urlize | 11253.3 µs | 10490.7 µs | 301.7 µs | **34.77×** | +| join | 3047.0 µs | 1034.8 µs | 251.4 µs | **4.12×** | +| i18n_tags | 3231.8 µs | 2616.2 µs | 348.3 µs | **7.51×** | +| aware_dates | 19275.8 µs | 15657.8 µs | 1482.7 µs | **10.56×** | +| striptags_intcomma | 5105.1 µs | 4305.4 µs | 602.6 µs | **7.14×** | +| truncate_html_sizes | 14623.5 µs | 13136.0 µs | 790.8 µs | **16.61×** | +| engine_e2e | 783.3 µs | 45.6 µs | 16.3 µs | **2.80×** | +| **geomean** | | | | **4.93×** | *Same machine as above; Jinja2 3.1.6. Over the same rows, Jinja2 renders -3.45× faster than stock Django and this engine renders 16.00× faster.* +3.35× faster than stock Django and this engine renders 16.54× faster.* - **Compile.** Jinja2 compiles every template to Python bytecode. A fresh - parse takes about 9× longer than stock Django and **153×** longer than - this engine (geomean). A cache-hit `get_template()` is 2.6× faster here + parse takes about 9× longer than stock Django and **149×** longer than + this engine (geomean). A cache-hit `get_template()` is 2.8× faster here than in Jinja2. -- **Where Jinja2 keeps up.** `if_branch` (0.98×) is a loop of integer +- **Where Jinja2 keeps up.** `if_branch` (1.00×) is a loop of integer comparisons. Jinja2 turns `n > 90` into a Python `>` on the raw value, which is as fast as the native comparison here. Rows made of plain loops and lookups (`nested_table`, `index_none_lookup`, `with_if_scopes`) are also close to even. - **Where it doesn't.** Jinja2 has no `date`, `floatformat`, `urlize`, - `intcomma` or Django-style `truncatewords`. Django projects register + `intcomma` or `truncatewords_html`, and its `filesizeformat` and + `truncate` give different output from Django's. Django projects register Django's own filter functions in Jinja2 (as django-jinja does), and the benchmark does too, so those rows run Python code at stock speed. - Here they are native, which is why `realistic_page`, `urlize`, `date_filter` - and `aware_dates` are 9–35× faster than Jinja2. + Here they are native, which is why `realistic_page`, `urlize`, `date_filter`, + `aware_dates` and `truncate_html_sizes` are 9–35× faster than Jinja2. - **Setup.** `autoescape=True`, `ChainableUndefined` (missing lookups render as empty, as in DTL), `auto_reload=False`, and the i18n extension wired to Django's gettext. Because Jinja2 always caches compiled templates, the diff --git a/benchmarks/bench.py b/benchmarks/bench.py index 09166be..875508a 100644 --- a/benchmarks/bench.py +++ b/benchmarks/bench.py @@ -513,6 +513,24 @@ def _aware_ctx(): ) +scenario( + "truncate_html_sizes", + "{% load humanize %}{% for a in arts %}
{{ a.body|truncatewords_html:8 }}
" + "

{{ a.body|truncatechars_html:40 }}

" + "{{ a.size|filesizeformat }}, {{ a.views|intword }} views{% endfor %}", + lambda: { + "arts": [ + { + "body": f"

Lorem ipsum dolor sit amet, consectetur" + " adipiscing elit & sed do eiusmod tempor.

", + "size": i * 98765, + "views": i * 1234567, + } + for i in range(50) + ] + }, +) + scenario( "engine_e2e", "Hi {{ name }}! {% for n in nums %}{{ n }}{% endfor %}", diff --git a/benchmarks/jinja2_bench.py b/benchmarks/jinja2_bench.py index eaa59d9..d3bab6d 100644 --- a/benchmarks/jinja2_bench.py +++ b/benchmarks/jinja2_bench.py @@ -202,14 +202,21 @@ def jinja(name, source, loader=None): "{% for a in arts %}

{{ a.body|striptags|truncatewords(12) }}

" "{{ a.views|intcomma }} views{% endfor %}", ) +jinja( + "truncate_html_sizes", + "{% for a in arts %}
{{ a.body|truncatewords_html(8) }}
" + "

{{ a.body|truncatechars_html(40) }}

" + "{{ a.size|filesizeformat }}, {{ a.views|intword }} views{% endfor %}", +) jinja("engine_e2e", "Hi {{ name }}! {% for n in nums %}{{ n }}{% endfor %}") # Django filters with no same-output Jinja2 builtin. Jinja2's own ``urlize``, # ``striptags`` and ``truncate`` behave differently, so Django's replace them. _DJANGO_FILTERS = ( - "capfirst date default_if_none floatformat linebreaksbr striptags time" - " truncatechars truncatewords urlize urlizetrunc" + "capfirst date default_if_none filesizeformat floatformat linebreaksbr striptags" + " time truncatechars truncatechars_html truncatewords truncatewords_html urlize" + " urlizetrunc" ).split() @@ -226,7 +233,7 @@ def _django_filter(fn): def build_jinja_env(loader): import jinja2 - from django.contrib.humanize.templatetags.humanize import intcomma + from django.contrib.humanize.templatetags.humanize import intcomma, intword from django.template import defaultfilters from django.urls import reverse from django.utils.translation import gettext, ngettext @@ -243,6 +250,7 @@ def build_jinja_env(loader): for name in _DJANGO_FILTERS: env.filters[name] = _django_filter(getattr(defaultfilters, name)) env.filters["intcomma"] = intcomma + env.filters["intword"] = intword env.globals["url"] = lambda name, *args: reverse(name, args=args) env.globals["one_param"] = one_param return env diff --git a/src/filters/floatformat.rs b/src/filters/floatformat.rs index 4a78591..0881700 100644 --- a/src/filters/floatformat.rs +++ b/src/filters/floatformat.rs @@ -294,7 +294,7 @@ fn exact_str<'a>(v: &'a Bound<'_, PyAny>) -> Option<&'a str> { /// `formats.number_format(number, decimal_pos, use_l10n, force_grouping)` /// for a `str` number; `None` → Python. -fn number_format( +pub(super) fn number_format( rc: &mut Rctx<'_>, number: &str, decimal_pos: usize, diff --git a/src/filters/humanize.rs b/src/filters/humanize.rs index 9acfede..425b343 100644 --- a/src/filters/humanize.rs +++ b/src/filters/humanize.rs @@ -567,3 +567,102 @@ pub(crate) fn ordinal<'py>( } py_ordinal(py)?.call1((input,).into_pyobject(py)?.add_args(args)?) } + +/// The stock Python `intword` (fallback for everything but plain ints). +fn py_intword(py: Python<'_>) -> PyResult<&Bound<'_, PyAny>> { + static F: PyOnceLock> = PyOnceLock::new(); + Ok(F.get_or_try_init(py, || -> PyResult> { + Ok(py + .import("django.contrib.humanize.templatetags.humanize")? + .getattr("intword")? + .unbind()) + })? + .bind(py)) +} + +/// `True` while the humanize module's `ngettext` / `defaultfilters` globals +/// are the stock objects (the `intword_converters` lambdas and `intword` +/// resolve both at call time). +fn intword_globals_stock(py: Python<'_>) -> PyResult { + static G: PyOnceLock<(Py, Py, Py)> = PyOnceLock::new(); + let (globals, ngettext, defaultfilters) = G.get_or_try_init(py, || -> PyResult<_> { + Ok(( + py.import("django.contrib.humanize.templatetags.humanize")? + .dict() + .unbind(), + py.import("django.utils.translation")? + .getattr("ngettext")? + .unbind(), + py.import("django.template.defaultfilters")? + .into_any() + .unbind(), + )) + })?; + let globals = globals.bind(py); + let same = |name: &str, f: &Py| -> PyResult { + Ok(globals.get_item(name)?.is_some_and(|g| g.is(f.bind(py)))) + }; + Ok(same("ngettext", ngettext)? && same("defaultfilters", defaultfilters)?) +} + +/// `intword(value)` for an exact `int` below 2**53 in magnitude (so +/// `value / 10**exponent` is one correctly rounded float division, as in +/// Python): the converter's `ngettext` through `Translator`, +/// `floatformat(new_value, 1)` through the native `floatformat`. Other +/// inputs or patched module globals take the Python function. +pub(crate) fn intword<'py>( + rc: &mut Rctx<'py>, + input: &Bound<'py, PyAny>, + args: &[Bound<'py, PyAny>], + _ae: Option, +) -> PyResult> { + const CONVERTERS: [(i32, &str); 4] = [ + (6, "%(value)s million"), + (9, "%(value)s billion"), + (12, "%(value)s trillion"), + (15, "%(value)s quadrillion"), + ]; + let py = input.py(); + if args.is_empty() && input.is_exact_instance_of::() { + if let Ok(n) = input.extract::() { + let abs = n.unsigned_abs(); + if abs < 1_000_000 { + return Ok(input.clone()); + } + if abs < 1 << 53 && intword_globals_stock(py)? { + #[allow(clippy::cast_precision_loss)] // exact below 2**53 + let (value, abs_f) = (n as f64, abs as f64); + for (exponent, msgid) in CONVERTERS { + let large = 10f64.powi(exponent); + if abs_f < large * 1000.0 { + let new_value = value / large; + // `round_away_from_one`: ROUND_UP of `new_value - 1`. + let y = new_value - 1.0; + let r = if y.fract() == 0.0 { + y + } else if y > 0.0 { + y.ceil() + } else { + y.floor() + }; + #[allow(clippy::cast_possible_truncation)] // |r| < 1e3 + let count = (r as i64 + 1).abs(); + let ff = super::floatformat::floatformat( + rc, + &pyo3::types::PyFloat::new(py, new_value).into_any(), + &[1i64.into_pyobject(py)?.into_any()], + None, + )? + .str()?; + let tmpl = super::Translator::new(py).cached(msgid, msgid, Some(count))?; + if let Some(s) = super::substitute(&tmpl, "%(value)s", ff.to_str()?) { + return Ok(PyString::new(py, &s).into_any()); + } + break; + } + } + } + } + } + py_intword(py)?.call1((input,).into_pyobject(py)?.add_args(args)?) +} diff --git a/src/filters/mod.rs b/src/filters/mod.rs index 93f6798..5076237 100644 --- a/src/filters/mod.rs +++ b/src/filters/mod.rs @@ -23,6 +23,9 @@ //! `urlize` are full ports with per-branch detection and Python fallbacks //! (see their modules; a mocked `Urlizer` disables the native path). +use std::cell::RefCell; +use std::collections::HashMap; + use pyo3::prelude::*; use pyo3::sync::PyOnceLock; use pyo3::type_object::PyTypeInfo; @@ -38,6 +41,7 @@ mod lists; mod misc; mod numbers; mod strings; +mod truncate_html; mod urlize; /// A native built-in filter. @@ -56,9 +60,7 @@ pub type NativeFn = for<'py> fn( ) -> PyResult>; /// Native implementation for a stock built-in name, `None` for filters that -/// stay bridged (`filesizeformat`, `dictsort`, -/// `dictsortreversed`, `truncatechars_html`, `truncatewords_html`) or -/// unknown names. +/// stay bridged (`dictsort`, `dictsortreversed`) or unknown names. pub(crate) fn lookup(name: &str) -> Option { match name { // strings @@ -72,6 +74,8 @@ pub(crate) fn lookup(name: &str) -> Option { "title" => Some(strings::title), "truncatechars" => Some(strings::truncatechars), "truncatewords" => Some(strings::truncatewords), + "truncatechars_html" => Some(truncate_html::truncatechars_html), + "truncatewords_html" => Some(truncate_html::truncatewords_html), "upper" => Some(strings::upper), "lower" => Some(strings::lower), "wordcount" => Some(strings::wordcount), @@ -93,6 +97,7 @@ pub(crate) fn lookup(name: &str) -> Option { "divisibleby" => Some(numbers::divisibleby), "pluralize" => Some(numbers::pluralize), "floatformat" => Some(floatformat::floatformat), + "filesizeformat" => Some(numbers::filesizeformat), // html strings "escape" => Some(html::escape_filter), "escapeseq" => Some(html::escapeseq), @@ -155,12 +160,23 @@ fn humanize_native(func: &Bound<'_, PyAny>) -> Option { let qualname: String = func.getattr("__qualname__").and_then(|m| m.extract()).ok()?; match qualname.as_str() { "intcomma" => Some(humanize::intcomma), + "intword" => Some(humanize::intword), "naturaltime" => Some(humanize::naturaltime), "ordinal" => Some(humanize::ordinal), _ => None, } } +/// `tmpl % arg` for a translated template whose only `%` starts `key` +/// (`"%(size)d"`, `"%s"`, ...), with `value` already formatted the way +/// that conversion would; `None` for any other template shape (the caller +/// then runs the Python filter, which formats or raises like stock). +pub(crate) fn substitute(tmpl: &Bound<'_, PyAny>, key: &str, value: &str) -> Option { + let t = tmpl.cast_exact::().ok()?.to_str().ok()?; + let pos = t.find(key)?; + (t.matches('%').count() == 1).then(|| format!("{}{value}{}", &t[..pos], &t[pos + key.len()..])) +} + /// `True` iff `e` is an instance of exception type `T` (Python class check). pub(crate) fn is_err(py: Python<'_>, e: &PyErr) -> bool { e.is_instance_of::(py) @@ -538,6 +554,56 @@ impl<'py> Translator<'py> { } } + /// `ngettext(singular, plural, n)` / `gettext(singular)` (`n = None`) + /// for static msgids, memoized per translation object: a + /// `DjangoTranslation`'s catalog never changes after construction, and + /// a reload builds new objects, so results are keyed on the object + /// itself (held, so its identity can't be reused). `trans_null` and the + /// Python fallback paths are not memoized. + pub(crate) fn cached( + &self, + singular: &'static str, + plural: &'static str, + n: Option, + ) -> PyResult> { + type Memo = Option<(Py, HashMap<(&'static str, Option), Py>)>; + thread_local! { + static MEMO: RefCell = const { RefCell::new(None) }; + } + let py = self.py; + let fname = if n.is_some() { "ngettext" } else { "gettext" }; + let compute = || match n { + Some(n) => self.ngettext(singular, plural, &n.into_pyobject(py)?.into_any()), + None => self.gettext(singular), + }; + let Some(TransObj::Real(t)) = self.obj(fname, n.is_some())? else { + return compute(); + }; + let key = (singular, n); + let hit = MEMO.with(|m| match &*m.borrow() { + Some((obj, map)) if obj.bind(py).is(&t) => map.get(&key).map(|v| v.clone_ref(py)), + _ => None, + }); + if let Some(v) = hit { + return Ok(v.into_bound(py)); + } + let v = compute()?; + MEMO.with(|m| { + let mut m = m.borrow_mut(); + match &mut *m { + Some((obj, map)) if obj.bind(py).is(&t) && map.len() < 4096 => { + map.insert(key, v.clone().unbind()); + } + _ => { + let mut map = HashMap::new(); + map.insert(key, v.clone().unbind()); + *m = Some((t.clone().unbind(), map)); + } + } + }); + Ok(v) + } + /// `npgettext(context, singular, plural, number)`. pub(crate) fn npgettext( &self, diff --git a/src/filters/numbers.rs b/src/filters/numbers.rs index a5fde3e..2b1464e 100644 --- a/src/filters/numbers.rs +++ b/src/filters/numbers.rs @@ -1,7 +1,8 @@ //! Integer filters of `django.template.defaultfilters` (native ports). use pyo3::prelude::*; -use pyo3::types::PyString; +use pyo3::sync::PyOnceLock; +use pyo3::types::{PyInt, PyString}; use crate::render::context::Rctx; use crate::render::value::helpers; @@ -137,3 +138,85 @@ pub(crate) fn pluralize<'py>( Err(e) => Err(e), } } + +/// The stock Python `filesizeformat` (fallback for everything but plain +/// ints). +fn py_filesizeformat(py: Python<'_>) -> PyResult<&Bound<'_, PyAny>> { + static F: PyOnceLock> = PyOnceLock::new(); + Ok(F.get_or_try_init(py, || -> PyResult> { + Ok(py + .import("django.template.defaultfilters")? + .getattr("filesizeformat")? + .unbind()) + })? + .bind(py)) +} + +/// `filesizeformat(bytes_)` for an exact `int` below 2**53 in magnitude +/// (so `bytes_ / KB` etc. are exact float divisions and `round(x, 1)` is +/// integer arithmetic on the tenths). The unit templates go through +/// `Translator`, `number_format(round(x, 1), 1)` through the native +/// `floatformat` formatter; other inputs take the Python filter. +pub(crate) fn filesizeformat<'py>( + rc: &mut Rctx<'py>, + input: &Bound<'py, PyAny>, + _args: &[Bound<'py, PyAny>], + _ae: Option, +) -> PyResult> { + let py = input.py(); + if input.is_exact_instance_of::() { + if let Ok(n) = input.extract::() { + if n.unsigned_abs() < 1 << 53 { + if let Some(s) = native_filesizeformat(rc, n)? { + return Ok(PyString::new(py, &s).into_any()); + } + } + } + } + py_filesizeformat(py)?.call1((input,)) +} + +fn native_filesizeformat(rc: &mut Rctx<'_>, n: i64) -> PyResult> { + const UNITS: [(u32, &str); 5] = [ + (10, "%s KB"), + (20, "%s MB"), + (30, "%s GB"), + (40, "%s TB"), + (50, "%s PB"), + ]; + let py = rc.py(); + let tr = super::Translator::new(py); + let b = n.unsigned_abs(); + let value = if b < 1 << 10 { + let tmpl = tr.cached("%(size)d byte", "%(size)d bytes", i64::try_from(b).ok())?; + let Some(v) = super::substitute(&tmpl, "%(size)d", &b.to_string()) else { + return Ok(None); + }; + v + } else { + let (shift, msgid) = UNITS + .iter() + .rev() + .find(|(shift, _)| b >= 1 << shift) + .copied() + .unwrap_or(UNITS[0]); + // `round(b / 2**shift, 1)` in tenths: half-even on the exact value. + let unit = 1u128 << shift; + let scaled = u128::from(b) * 10; + let (mut tenths, rem) = (scaled / unit, scaled % unit); + if rem * 2 > unit || (rem * 2 == unit && tenths % 2 == 1) { + tenths += 1; + } + let number = format!("{}.{}", tenths / 10, tenths % 10); + let Some(num) = super::floatformat::number_format(rc, &number, 1, true, false)? else { + return Ok(None); + }; + let tmpl = tr.cached(msgid, msgid, None)?; + let Some(v) = super::substitute(&tmpl, "%s", &num) else { + return Ok(None); + }; + v + }; + let value = if n < 0 { format!("-{value}") } else { value }; + Ok(Some(value.replace(' ', "\u{a0}"))) +} diff --git a/src/filters/strings.rs b/src/filters/strings.rs index c6eac23..1e74a51 100644 --- a/src/filters/strings.rs +++ b/src/filters/strings.rs @@ -12,7 +12,7 @@ use unicode_normalization::UnicodeNormalization; use super::{is_err, trans_state, utils, TransState}; -fn int_of<'py>(py: Python<'py>, v: &Bound<'py, PyAny>) -> PyResult> { +pub(super) fn int_of<'py>(py: Python<'py>, v: &Bound<'py, PyAny>) -> PyResult> { helpers(py)?.int_builtin.bind(py).call1((v,)) } @@ -163,7 +163,7 @@ pub(crate) fn title<'py>( /// Stock `add_truncation_text(text, truncate)` for an already-resolved /// `truncate` string. -fn add_truncation_text(text: &str, truncate: &str) -> String { +pub(super) fn add_truncation_text(text: &str, truncate: &str) -> String { const KEY: &str = "%(truncated_text)s"; if let Some(pos) = truncate.find(KEY) { // `truncate % {"truncated_text": text}`: the named key is @@ -201,7 +201,23 @@ thread_local! { }; } -fn translated_ellipsis(py: Python<'_>) -> PyResult> { +/// `True` while `django.utils.text`'s `pgettext` global (which +/// `add_truncation_text` resolves at call time) is the stock function. +fn text_pgettext_stock(py: Python<'_>) -> PyResult { + static G: pyo3::sync::PyOnceLock> = pyo3::sync::PyOnceLock::new(); + let globals = G + .get_or_try_init(py, || -> PyResult<_> { + Ok(py.import("django.utils.text")?.dict().unbind()) + })? + .bind(py); + let stock = utils(py)?.pgettext.bind(py); + Ok(globals.get_item("pgettext")?.is_some_and(|g| g.is(stock))) +} + +pub(super) fn translated_ellipsis(py: Python<'_>) -> PyResult> { + if !text_pgettext_stock(py)? { + return Ok(None); + } let state = trans_state(py); let hit = TRUNC.with(|c| { let c = c.borrow(); @@ -492,7 +508,7 @@ fn strip_simple(text: &str) -> Strip { } /// End of `&name;`, `&#digits;` or `&#xhex;` starting at `p`. -fn entity_end(b: &[u8], p: usize) -> Option { +pub(super) fn entity_end(b: &[u8], p: usize) -> Option { let mut j = p + 1; if b.get(j) == Some(&b'#') { j += 1; @@ -523,7 +539,7 @@ fn entity_end(b: &[u8], p: usize) -> Option { /// End (index after `>`) of a simple start or end tag at `start` /// (`bytes[start] == '<'`). -fn tag_end(bytes: &[u8], start: usize) -> Option { +pub(super) fn tag_end(bytes: &[u8], start: usize) -> Option { let at = |i: usize| bytes.get(i).copied(); let mut pos = start + 1; let end_tag = at(pos) == Some(b'/'); diff --git a/src/filters/truncate_html.rs b/src/filters/truncate_html.rs new file mode 100644 index 0000000..5abed6e --- /dev/null +++ b/src/filters/truncate_html.rs @@ -0,0 +1,426 @@ +//! Native `truncatechars_html` / `truncatewords_html`: a port of +//! `TruncateCharsHTMLParser` / `TruncateWordsHTMLParser` for "simple" HTML +//! (the grammar the native `striptags` accepts: plain start/end tags with +//! ordinary attributes, `&name;` / `&#N;` / `&#xH;` references). On that +//! grammar every `HTMLParser` version Django supports makes the same +//! callbacks: one `handle_data` per text run between tags (charrefs already +//! converted), `handle_starttag` / `handle_startendtag` / `handle_endtag` +//! per tag. Anything else (comments, declarations, raw-text elements, a +//! stray `<` or `&`, an unknown entity, a NUL) runs the stock `Truncator`. + +use pyo3::prelude::*; +use pyo3::types::PyString; + +use unicode_normalization::UnicodeNormalization; + +use crate::render::context::Rctx; +use crate::render::value::{escape_html, helpers}; + +use super::strings::{add_truncation_text, entity_end, int_of, tag_end, translated_ellipsis}; +use super::{is_err, utils}; + +/// `django.utils.html.VOID_ELEMENTS`. +const VOID_ELEMENTS: [&str; 16] = [ + "area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", + "track", "wbr", "frame", "spacer", +]; + +fn is_void(name: &str) -> bool { + VOID_ELEMENTS.contains(&name) +} + +enum Tok<'a> { + /// Raw start tag text (`get_starttag_text()`), lowercased name, `/>`. + Start(&'a str, String, bool), + End(String), + /// Raw text run (charrefs not yet converted). + Data(&'a str), +} + +/// Split simple HTML into tokens; `None` → not simple, use Python. +fn tokenize(text: &str) -> Option>> { + if text.contains('\0') { + return None; + } + let b = text.as_bytes(); + let mut toks = Vec::new(); + let mut i = 0; + let mut last = 0; + while let Some(off) = memchr::memchr2(b'<', b'&', &b[i..]) { + let p = i + off; + if b[p] == b'&' { + i = entity_end(b, p)?; + continue; + } + let e = tag_end(b, p)?; + if last < p { + toks.push(Tok::Data(&text[last..p])); + } + let end_tag = b[p + 1] == b'/'; + let name_start = if end_tag { p + 2 } else { p + 1 }; + let name_end = b[name_start..] + .iter() + .position(|c| !c.is_ascii_alphanumeric()) + .map_or(b.len(), |n| name_start + n); + let name = text[name_start..name_end].to_ascii_lowercase(); + if end_tag { + toks.push(Tok::End(name)); + } else { + toks.push(Tok::Start(&text[p..e], name, b[e - 2] == b'/')); + } + i = e; + last = e; + } + if last < text.len() { + toks.push(Tok::Data(&text[last..])); + } + Some(toks) +} + +/// `html.unescape` code points that come back as themselves. +fn plain_codepoint(c: u32) -> Option { + let ok = matches!(c, 0x9 | 0xa | 0xc | 0x20..=0x7e | 0xa0..=0xd7ff) + || ((0xe000..=0x10_ffff).contains(&c) + && !(0xfdd0..=0xfdef).contains(&c) + && (c & 0xfffe) != 0xfffe); + if ok { + char::from_u32(c) + } else { + None + } +} + +fn named_entity(name: &str) -> Option { + Some(match name { + "amp" => '&', + "lt" => '<', + "gt" => '>', + "quot" => '"', + "apos" => '\'', + "nbsp" => '\u{a0}', + "copy" => '\u{a9}', + "reg" => '\u{ae}', + "trade" => '\u{2122}', + "hellip" => '\u{2026}', + "mdash" => '\u{2014}', + "ndash" => '\u{2013}', + "lsquo" => '\u{2018}', + "rsquo" => '\u{2019}', + "ldquo" => '\u{201c}', + "rdquo" => '\u{201d}', + "laquo" => '\u{ab}', + "raquo" => '\u{bb}', + "middot" => '\u{b7}', + "bull" => '\u{2022}', + "times" => '\u{d7}', + "deg" => '\u{b0}', + "euro" => '\u{20ac}', + "pound" => '\u{a3}', + "sect" => '\u{a7}', + _ => return None, + }) +} + +/// `html.unescape(raw)` for the references `entity_end` accepts; `None` +/// for ones whose stock result is not modelled here. +fn unescape(raw: &str) -> Option> { + if !raw.contains('&') { + return Some(std::borrow::Cow::Borrowed(raw)); + } + let bytes = raw.as_bytes(); + let mut out = String::with_capacity(raw.len()); + let mut i = 0; + while let Some(off) = memchr::memchr(b'&', &bytes[i..]) { + let p = i + off; + out.push_str(&raw[i..p]); + let e = entity_end(bytes, p)?; + let body = &raw[p + 1..e - 1]; + let ch = if let Some(num) = body.strip_prefix('#') { + let v = match num.strip_prefix(['x', 'X']) { + Some(hex) => u32::from_str_radix(hex, 16).ok()?, + None => num.parse::().ok()?, + }; + plain_codepoint(v)? + } else { + named_entity(body)? + }; + out.push(ch); + i = e; + } + out.push_str(&raw[i..]); + Some(std::borrow::Cow::Owned(out)) +} + +fn escaped(s: &str) -> String { + escape_html(s).unwrap_or_else(|| s.to_string()) +} + +/// Python `str.isspace` (what `\s` matches in a `str` pattern). +fn py_isspace(c: char) -> bool { + c.is_whitespace() || ('\x1c'..='\x1f').contains(&c) +} + +/// `re.split(r"(?<=\S)\s+(?=\S)", data)`. +fn split_words(data: &str) -> Vec<&str> { + let Some(first) = data.find(|c: char| !py_isspace(c)) else { + return vec![data]; + }; + let mut pieces = Vec::new(); + let mut start = 0; + let mut chars = data[first..] + .char_indices() + .map(|(i, c)| (i + first, c)) + .peekable(); + while let Some((i, c)) = chars.next() { + if !py_isspace(c) { + continue; + } + // Whitespace run starting at `i` (preceded by a non-space). + let mut end = i + c.len_utf8(); + while let Some(&(j, d)) = chars.peek() { + if !py_isspace(d) { + break; + } + end = j + d.len_utf8(); + chars.next(); + } + if end < data.len() { + pieces.push(&data[start..i]); + start = end; + } + } + pieces.push(&data[start..]); + pieces +} + +enum Mode<'e> { + /// `TruncateCharsHTMLParser`: `length`, the ellipsis format, total + /// code points of the input (`len(self.rawdata)`). + Chars { + length: i64, + processed: i64, + ellipsis: &'e str, + raw_len: i64, + }, + Words, +} + +fn clen(s: &str) -> i64 { + i64::try_from(s.chars().count()).unwrap_or(i64::MAX) +} + +/// Run the parser callbacks over `toks`; `None` → Python. +fn truncate(toks: &[Tok<'_>], mut remaining: i64, mut mode: Mode<'_>) -> Option { + let mut out = String::new(); + let mut out_len: i64 = 0; + let mut tags: Vec<&str> = Vec::new(); + let push = |out: &mut String, out_len: &mut i64, s: &str| { + out.push_str(s); + *out_len += clen(s); + }; + let mut done = false; + for tok in toks { + match tok { + Tok::Start(raw, name, self_closing) => { + push(&mut out, &mut out_len, raw); + if !is_void(name) { + tags.push(name); + if *self_closing { + push(&mut out, &mut out_len, &format!("")); + if tags.last() == Some(&name.as_str()) { + tags.pop(); + } + } + } + } + Tok::End(name) => { + if !is_void(name) { + push(&mut out, &mut out_len, &format!("")); + if tags.last() == Some(&name.as_str()) { + tags.pop(); + } + } + } + Tok::Data(raw) => { + let data = unescape(raw)?; + match &mut mode { + Mode::Chars { + length, + processed, + ellipsis, + raw_len, + } => { + let data_len = clen(&data); + *processed += data_len; + if *processed == *length && out_len + data_len == *raw_len { + out.push_str(&data); + done = true; + } else { + let keep = usize::try_from(remaining).unwrap_or(0); + let head = match data.char_indices().nth(keep) { + Some((at, _)) => &data[..at], + None => &data[..], + }; + let output = escaped(head); + if remaining < data_len { + out.push_str(&add_truncation_text(&output, ellipsis)); + done = true; + } else { + remaining -= data_len; + push(&mut out, &mut out_len, &output); + } + } + } + Mode::Words => { + let words = split_words(&data); + let n = i64::try_from(words.len()).unwrap_or(i64::MAX); + let keep = usize::try_from(remaining).unwrap_or(0).min(words.len()); + let output = escaped(&words[..keep].join(" ")); + if remaining < n { + out.push_str(&add_truncation_text(&output, " …")); + done = true; + } else { + remaining -= n; + push(&mut out, &mut out_len, &output); + } + } + } + if done { + break; + } + } + } + } + if done { + for tag in tags.iter().rev() { + out.push_str("'); + } + } + Some(out) +} + +/// The `str` the stock `Truncator` would wrap, when it is an exact `str` +/// or `SafeString` (both stringify to their own contents). +fn plain_text<'a>(s: &'a Bound<'_, PyString>) -> PyResult> { + let py = s.py(); + if !(s.is_exact_instance_of::() || s.get_type().is(helpers(py)?.safe_string.bind(py))) + { + return Ok(None); + } + Ok(s.to_str().ok()) +} + +/// Shared prologue: `(str(value), int(arg), int(arg) as i64)`, or `Err(v)` +/// for a stock early return `v` (`int(arg)` `ValueError` → value, +/// `length <= 0` → ""). +type Prologue<'py> = + Result<(Bound<'py, PyString>, Bound<'py, PyAny>, Option), Bound<'py, PyAny>>; + +fn prologue<'py>(input: &Bound<'py, PyAny>, arg: &Bound<'py, PyAny>) -> PyResult> { + let py = input.py(); + let s = input.str()?; + let length = match int_of(py, arg) { + Ok(v) => v, + Err(e) if is_err::(py, &e) => return Ok(Err(s.into_any())), + Err(e) => return Err(e), + }; + let n = length.extract::().ok(); + if n.is_some_and(|n| n <= 0) { + return Ok(Err(PyString::new(py, "").into_any())); + } + Ok(Ok((s, length, n))) +} + +fn truncator_html<'py>( + s: &Bound<'py, PyString>, + method: &str, + length: &Bound<'py, PyAny>, + truncate: Option<&str>, +) -> PyResult> { + let py = s.py(); + let kwargs = pyo3::types::PyDict::new(py); + kwargs.set_item("html", true)?; + if let Some(t) = truncate { + kwargs.set_item("truncate", t)?; + } + let trunc = utils(py)?.truncator.bind(py).call1((s,))?; + trunc.call_method(method, (length,), Some(&kwargs)) +} + +/// `truncatechars_html`: `Truncator(value).chars(length, html=True)`. +pub(crate) fn truncatechars_html<'py>( + _rc: &mut Rctx<'py>, + input: &Bound<'py, PyAny>, + args: &[Bound<'py, PyAny>], + _ae: Option, +) -> PyResult> { + let py = input.py(); + let (s, length, n) = match prologue(input, &args[0])? { + Ok(v) => v, + Err(early) => return Ok(early), + }; + if let (Some(n), Some(raw)) = (n, plain_text(&s)?) { + let normed; + let text = if unicode_normalization::is_nfc_quick(raw.chars()) + == unicode_normalization::IsNormalized::Yes + { + raw + } else { + normed = raw.nfc().collect::(); + normed.as_str() + }; + if let Some(toks) = tokenize(text) { + if let Some((ellipsis, width)) = translated_ellipsis(py)? { + let mode = Mode::Chars { + length: n, + processed: 0, + ellipsis: &ellipsis, + raw_len: clen(text), + }; + if let Some(out) = truncate(&toks, (n - width).max(0), mode) { + return Ok(PyString::new(py, &out).into_any()); + } + } + } + } + truncator_html(&s, "chars", &length, None) +} + +/// `truncatewords_html`: `Truncator(value).words(length, html=True, +/// truncate=" …")`. +pub(crate) fn truncatewords_html<'py>( + _rc: &mut Rctx<'py>, + input: &Bound<'py, PyAny>, + args: &[Bound<'py, PyAny>], + _ae: Option, +) -> PyResult> { + let py = input.py(); + let (s, length, n) = match prologue(input, &args[0])? { + Ok(v) => v, + Err(early) => return Ok(early), + }; + if let (Some(n), Some(text)) = (n, plain_text(&s)?) { + if let Some(toks) = tokenize(text) { + if let Some(out) = truncate(&toks, n, Mode::Words) { + return Ok(PyString::new(py, &out).into_any()); + } + } + } + truncator_html(&s, "words", &length, Some(" …")) +} + +#[cfg(test)] +mod tests { + use super::split_words; + + #[test] + fn words_split() { + assert_eq!(split_words("a b"), vec!["a", "b"]); + assert_eq!(split_words(" a b "), vec![" a", "b "]); + assert_eq!(split_words(" "), vec![" "]); + assert_eq!(split_words("ab"), vec!["ab"]); + assert_eq!(split_words("a\u{a0}\nb\tc"), vec!["a", "b", "c"]); + } +} diff --git a/tests/test_realpage.py b/tests/test_realpage.py index 1e5d180..595e4f3 100644 --- a/tests/test_realpage.py +++ b/tests/test_realpage.py @@ -581,3 +581,108 @@ def test_ordinal_patched_globals(tmpl): assert_parity(src, {"vals": [1, 2, 11, 23]}, lang="de") finally: humanize.pgettext, humanize.mark_safe = orig_pg, orig_ms + + +TRUNCATE_HTML_VALUES = [ + "", + "plain text with no tags at all", + "

Hello world, this is some text.

", + "

one two three four five six

seven eight

", + "

Upper case tags

and tail", + "

a

b

\n

c d

", + "

café café 日本語 \U0001f600 text

", + "

& <b> "q" 's'  x… © — 😀

", + "link text here", + "

img \"a br
br2
hr


done

", + "

self

closing tags

", + "stray end tags unclosed nested", + "

lots of\n\n whitespace\t\there

", + "

exactly

", + "abcde", + "

a b c\x1cd

", + "

it's \"quoted\" > text

", + # Python fallbacks: comments, raw text, stray < / &, unknown entities. + "

commented text here

", + "

after script

", + "a < b and c > d in text", + "AT&T bold", + "

&foo; � €

", + "

x\x00y

", + "

trailing &", +] +TRUNCATE_HTML_ARGS = [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 12, 20, 100, "3", "x", 2**70] + + +@pytest.mark.parametrize("lang", [None, "de", "ja"]) +@pytest.mark.parametrize("filt", ["truncatechars_html", "truncatewords_html"]) +def test_truncate_html(filt, lang): + src = ( + "{% for v in vals %}{% for n in ns %}[{{ v|" + filt + ":n }}|{{ v|safe|" + filt + ":n }}" + "|{% autoescape off %}{{ v|" + filt + ":n }}{% endautoescape %}]{% endfor %}{% endfor %}" + ) + assert_parity(src, {"vals": TRUNCATE_HTML_VALUES, "ns": TRUNCATE_HTML_ARGS}, lang=lang) + + +@pytest.mark.parametrize("filt", ["truncatechars_html", "truncatewords_html"]) +def test_truncate_html_non_str(filt): + class Html: + def __str__(self): + return mark_safe("obj str value") + + vals = [12345, None, Html(), gettext_lazy("Hello world"), ["x", "y"]] + src = "{% for v in vals %}[{{ v|" + filt + ":2 }}]{% endfor %}" + assert_parity(src, {"vals": vals}, lang="de") + + +@pytest.mark.parametrize("ellipsis", ["%(truncated_text)s...", "[%(truncated_text)s]", "~"]) +def test_truncatechars_patched_pgettext(ellipsis): + """A patched `django.utils.text.pgettext` keeps stock output.""" + from django.utils import text + + src = "{% for n in ns %}[{{ v|truncatechars_html:n }}|{{ v|truncatechars:n }}]{% endfor %}" + orig = text.pgettext + text.pgettext = lambda ctx, msg: ellipsis + try: + with override_settings(USE_I18N=False): + ctx = {"v": "

Hello world again

", "ns": [1, 2, 3, 5, 8, 30]} + assert_parity(src, ctx) + finally: + text.pgettext = orig + + +NUMBER_WORD_VALUES = [ + 0, 1, 2, 1023, 1024, 1025, 1280, 1536, 1792, 10**6, 999_999, 1_000_000, 1_200_000, + 1_250_000, 1_950_000, 999_950_000, 999_999_999, 10**9, 1_234_567_890_123, 2**50, 2**53 - 1, + 2**53, 2**60, 2**63, 10**30, -1, -1024, -1_500_000, -(2**63), True, False, "1024", "x", + None, 1.5e6, 3.3, Decimal("2048"), [], +] + + +@pytest.mark.parametrize("thousands", [False, True]) +@pytest.mark.parametrize("lang", [None, "de", "fr", "ja", "ar", "ru"]) +def test_filesizeformat_intword(lang, thousands): + src = ( + "{% load humanize %}{% for v in vals %}[{{ v|filesizeformat }}|{{ v|intword }}" + "|{{ v|intword|length }}]{% endfor %}" + ) + with override_settings(USE_THOUSAND_SEPARATOR=thousands): + assert_parity(src, {"vals": NUMBER_WORD_VALUES}, lang=lang) + + +def test_filesizeformat_intword_i18n_off(): + with override_settings(USE_I18N=False): + src = "{% load humanize %}{% for v in vals %}[{{ v|filesizeformat }}|{{ v|intword }}]{% endfor %}" + assert_parity(src, {"vals": NUMBER_WORD_VALUES}, lang="de") + + +@pytest.mark.parametrize("tmpl", ["%(value)s M", "%(value)s %% x", "no placeholder", "%(value)d"]) +def test_intword_patched_ngettext(tmpl): + from django.contrib.humanize.templatetags import humanize + + src = "{% load humanize %}{% for v in vals %}[{{ v|intword }}]{% endfor %}" + orig = humanize.ngettext + humanize.ngettext = lambda s, p, n: tmpl + try: + assert_parity(src, {"vals": [10**6, 2 * 10**9, 5]}, lang="de") + finally: + humanize.ngettext = orig