Repository navigation
Refactor element handlers - #60
Conversation
WalkthroughReplaces tuple-based handler returns with a unified Changes
Sequence Diagram(s)sequenceDiagram
participant DW as DomWalker
participant CH as Chain / ElementHandlers
participant H as ElementHandler
participant R as HandlerResult
rect rgb(250,250,255)
Note over DW,CH: Old flow (tuple-based)
DW->>CH: proceed(node)
CH->>H: on_visit(chain, element)
H-->>CH: (Some(content), bool)
CH-->>DW: (content, bool)
end
rect rgb(245,255,245)
Note over DW,CH: New flow (HandlerResult)
DW->>CH: proceed(node)
CH->>H: handle(chain, element)
H-->>CH: Some(HandlerResult{content, markdown_translated})
CH-->>DW: Option<HandlerResult>
DW->>DW: if res.markdown_translated then push(res.content) else emit serialized HTML
end
rect rgb(255,250,240)
Note right of R: Unified return: content + markdown_translated\nreduces boolean plumbing across callers
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes
Possibly related PRs
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
Comment |
|
@coderabbitai summary |
✅ Actions performedSummary regeneration triggered. |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (8)
src/text_util.rs (1)
106-134: Consider optimizing memory allocations in join_contents.The function creates a new
Stringwith recalculated capacity on each iteration (line 131:result = next_result), leading to O(n) allocations for n non-empty strings. While functional, this could impact performance when joining many content pieces.Consider either:
- Pre-calculating total capacity before the loop
- Reusing the existing
resultString by calculating only the additional capacity neededExample optimization:
pub(crate) fn join_contents(contents: &[String]) -> String { - let mut result = String::new(); + // Pre-calculate approximate capacity + let total_capacity: usize = contents.iter().map(|s| s.len()).sum(); + let mut result = String::with_capacity(total_capacity); + for content in contents { let content_len = content.len(); if content_len == 0 { continue; } - let result_len = result.len(); - - let left = result.trim_end_matches('\n'); - let right = content.trim_start_matches('\n'); - - let max_trimmed_new_lines = - std::cmp::max(result_len - left.len(), content_len - right.len()); - let separator_new_lines = std::cmp::min(max_trimmed_new_lines, 2); - let separator = "\n".repeat(separator_new_lines); - - let mut next_result = String::with_capacity(left.len() + separator.len() + right.len()); - next_result.push_str(left); - next_result.push_str(&separator); - next_result.push_str(right); - - result = next_result; + if !result.is_empty() { + let result_len = result.len(); + let left_trim = result.trim_end_matches('\n'); + let right_trim = content.trim_start_matches('\n'); + + // Truncate result to remove trailing newlines + result.truncate(left_trim.len()); + + let max_trimmed_new_lines = + std::cmp::max(result_len - left_trim.len(), content_len - right_trim.len()); + let separator_new_lines = std::cmp::min(max_trimmed_new_lines, 2); + + for _ in 0..separator_new_lines { + result.push('\n'); + } + result.push_str(right_trim); + } else { + result.push_str(content); + } } result }src/element_handler/thead.rs (1)
1-6: thead_handler refactor looks correct; Vec allocation could be optimized laterThe move to
Option<HandlerResult>plus delegating tohandle_or_serialize_by_parentmatches the new handler pattern and should preserve behavior, given you pass throughelement.markdown_translatedand still gate withserialize_if_faithful!. The only minor concern is the per‑callvec!["table"]allocation; ifhandle_or_serialize_by_parentis used heavily, consider changing its parameter to&[&str]so callers can pass&["table"]without allocating.Also applies to: 8-13
src/dom_walker.rs (1)
6-7: HandlerResult integration in walk_node looks sound; join_contents use is appropriateSwitching to
text_util::join_contentsand feeding its result intohandlers.handlebefore truncating the buffer keeps the previous “collect children → compute Element.content → replace with handler output” pattern, and updatingmarkdown_translatedfromres.markdown_translatedaligns with the new HandlerResult‑centric flow. If you want a tiny readability tweak, you could bindjoin_contents(&buffer[prev_buffer_len..])to a localcontentvariable before thehandlecall, but functionally this looks correct.Also applies to: 75-82, 85-89
src/element_handler/head_body.rs (1)
1-5: head_body_handler correctly uses handle_or_serialize_by_parent; small Vec nitThe new
Option<HandlerResult>signature and delegation tohandle_or_serialize_by_parentwith"html"as the allowed parent look consistent with the overall refactor. Similar to other handlers, this currently allocates aVecviavec!["html"]on every call; ifhandle_or_serialize_by_parentis ever updated to take&[&str], you can then pass&["html"]and avoid that allocation.Also applies to: 7-8
src/element_handler/tr.rs (1)
1-6: tr_handler refactor matches the new pattern; considertfootand Vec allocationThe
tr_handlerchange toOption<HandlerResult>plusserialize_if_faithful!→handle_or_serialize_by_parentmirrors the other table handlers and should preserve behavior. Two small follow‑ups you might consider:
- If you want
<tr>under<tfoot>to be markdown‑translated in faithful mode as well, add"tfoot"to the allowed parent list.- As with other handlers, switching
handle_or_serialize_by_parentto accept&[&str]would let you replace&vec!["tbody", "thead"]with&["tbody", "thead"]and avoid per‑call allocations.Also applies to: 8-16
src/element_handler/td_th.rs (1)
1-11: HandlerResult migration looks correct; consider avoiding per-call Vec allocationThe td/th handler correctly uses
serialize_if_faithful!and delegates tohandle_or_serialize_by_parent, and the newOption<HandlerResult>signature aligns with the rest of the handler API.Given the PR’s performance goal, you might later consider changing
handle_or_serialize_by_parentto accept&[&str]so callers can pass a static slice (e.g.&["tr"]) instead of allocatingvec!["tr"]on every call. This is non-blocking but would remove a tiny allocation on hot paths.src/element_handler/mod.rs (2)
55-77: Consider deriving common traits onHandlerResult
HandlerResultis central to the new API. Deriving a few standard traits would make debugging and testing easier without changing semantics.Example:
-/// The processing result of a [ElementHandler] -pub struct HandlerResult { +/// The processing result of an [ElementHandler]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct HandlerResult { pub content: String, pub markdown_translated: bool, }The
From<String>/From<&str>impls look correct and ergonomically encodemarkdown_translated = truefor Markdown-producing paths.
79-86:ElementHandlerAPI update looks good; consider aligningappendwithHandlerResultThe switch to
fn handle(&self, chain: &dyn Chain, element: Element) -> Option<HandlerResult>together with the blanketimpl<F> ElementHandler for Fkeeps handler ergonomics intact and object safety preserved; no functional issues here.One design nit:
appendstill returnsOption<String>whilehandlenow returnsOption<HandlerResult>. Ifappendcontent is conceptually “more of the same output”, you may want to either:
- Clarify in docs that
appendis always Markdown and intentionally bypassesHandlerResult, or- Change it to
Option<HandlerResult>for a fully consistent handler contract.This is purely an API consistency concern; behavior today is fine.
Also applies to: 93-100
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (31)
Cargo.toml(1 hunks)README.md(1 hunks)benches/bench.ts(2 hunks)examples/simple/main.rs(1 hunks)src/dom_walker.rs(3 hunks)src/element_handler/anchor.rs(4 hunks)src/element_handler/blockquote.rs(1 hunks)src/element_handler/br.rs(1 hunks)src/element_handler/caption.rs(1 hunks)src/element_handler/code.rs(6 hunks)src/element_handler/element_util.rs(1 hunks)src/element_handler/emphasis.rs(2 hunks)src/element_handler/head_body.rs(1 hunks)src/element_handler/headings.rs(2 hunks)src/element_handler/hr.rs(1 hunks)src/element_handler/html.rs(2 hunks)src/element_handler/img.rs(3 hunks)src/element_handler/li.rs(2 hunks)src/element_handler/list.rs(2 hunks)src/element_handler/mod.rs(8 hunks)src/element_handler/p.rs(1 hunks)src/element_handler/pre.rs(2 hunks)src/element_handler/table.rs(7 hunks)src/element_handler/tbody.rs(1 hunks)src/element_handler/td_th.rs(1 hunks)src/element_handler/thead.rs(1 hunks)src/element_handler/tr.rs(1 hunks)src/lib.rs(5 hunks)src/node_util.rs(0 hunks)src/text_util.rs(1 hunks)tests/basic_tests.rs(2 hunks)
💤 Files with no reviewable changes (1)
- src/node_util.rs
🧰 Additional context used
🧬 Code graph analysis (17)
src/element_handler/caption.rs (1)
src/element_handler/element_util.rs (1)
handle_or_serialize_by_parent(12-35)
src/element_handler/tr.rs (1)
src/element_handler/element_util.rs (1)
handle_or_serialize_by_parent(12-35)
src/element_handler/li.rs (1)
src/node_util.rs (2)
get_node_tag_name(5-11)get_parent_node(13-24)
src/element_handler/td_th.rs (1)
src/element_handler/element_util.rs (1)
handle_or_serialize_by_parent(12-35)
src/element_handler/code.rs (2)
src/element_handler/element_util.rs (1)
serialize_element(39-169)src/node_util.rs (2)
get_node_tag_name(5-11)get_parent_node(13-24)
src/element_handler/anchor.rs (1)
src/element_handler/mod.rs (5)
handle(85-85)handle(97-99)handle(244-291)handle(302-302)handle(317-325)
src/lib.rs (1)
src/element_handler/mod.rs (1)
new(109-230)
src/element_handler/tbody.rs (1)
src/element_handler/element_util.rs (1)
handle_or_serialize_by_parent(12-35)
src/element_handler/element_util.rs (2)
src/dom_walker.rs (1)
is_block_element(400-402)src/node_util.rs (1)
parent_tag_name_equals(27-36)
src/element_handler/html.rs (1)
src/element_handler/element_util.rs (1)
serialize_element(39-169)
src/element_handler/list.rs (4)
src/element_handler/element_util.rs (1)
serialize_element(39-169)src/node_util.rs (2)
get_node_tag_name(5-11)get_parent_node(13-24)src/text_util.rs (2)
indent_text_except_first_line(178-197)join_contents(108-134)src/element_handler/mod.rs (1)
new(109-230)
src/element_handler/pre.rs (2)
src/element_handler/element_util.rs (1)
serialize_element(39-169)src/node_util.rs (1)
get_node_tag_name(5-11)
src/element_handler/table.rs (1)
src/element_handler/element_util.rs (1)
serialize_element(39-169)
src/element_handler/thead.rs (1)
src/element_handler/element_util.rs (1)
handle_or_serialize_by_parent(12-35)
src/dom_walker.rs (1)
src/text_util.rs (1)
join_contents(108-134)
src/element_handler/head_body.rs (1)
src/element_handler/element_util.rs (1)
handle_or_serialize_by_parent(12-35)
src/element_handler/mod.rs (6)
src/dom_walker.rs (1)
walk_node(17-103)src/element_handler/element_util.rs (1)
serialize_element(39-169)src/element_handler/p.rs (1)
p_handler(8-11)src/element_handler/pre.rs (1)
pre_handler(10-34)src/element_handler/table.rs (1)
table_handler(18-153)src/lib.rs (3)
new(87-94)new(164-171)options(174-177)
🔇 Additional comments (26)
benches/bench.ts (2)
20-23: Good refactor for observability, but inconsistent with PR objectives.The extraction of the result into an intermediate variable and the addition of logging improve code clarity and debugging. However, these changes don't appear to relate to the stated PR objectives ("Better element handler APIs" and "Fix performance"), which describe Rust handler API refactoring. This file only contains TypeScript benchmark script improvements.
50-50: LGTM: Markdown formatting fix.Removing the leading hyphen corrects the markdown formatting, as the line should not render as a list item.
Cargo.toml (1)
29-30: Verify that debug symbols in release builds are intentional.Enabling debug symbols in release builds significantly increases binary size. While this can be useful for profiling and debugging performance issues, it's unusual for production releases.
Is this temporary for performance investigation, or intended to be permanent? If temporary, consider documenting this or adding a TODO comment.
examples/simple/main.rs (1)
30-32: LGTM!The custom handler correctly uses the new API, returning
Option<HandlerResult>via the.into()conversion. This is more ergonomic than the previous tuple-based return.README.md (1)
65-65: LGTM!Documentation accurately reflects the simplified custom handler API, showing the new
Option<HandlerResult>return type via.into().src/element_handler/p.rs (1)
1-11: LGTM!The refactoring correctly updates the paragraph handler to return
Option<HandlerResult>instead of a tuple. The use of.into()for the conversion is idiomatic and leverages theFrom<String>implementation.src/element_handler/blockquote.rs (1)
1-17: LGTM!The blockquote handler correctly implements the new
HandlerResult-based API. The refactoring maintains the existing logic while improving the API surface.src/element_handler/pre.rs (1)
1-34: LGTM!The pre handler correctly handles both code paths:
- Line 27: Uses
.into()for markdown-translated content- Lines 29-32: Explicitly constructs
HandlerResultwithmarkdown_translated: falsefor serialized HTML contentThe refactoring maintains the existing logic while using the new
HandlerResulttype.src/element_handler/caption.rs (1)
1-11: LGTM!The caption handler correctly migrates to the new API using
handle_or_serialize_by_parenthelper. This encapsulates the parent-checking logic and returns the appropriateHandlerResult.src/element_handler/br.rs (1)
1-6: br_handler correctly adopts HandlerResult, relying on Into semanticsThe handler now cleanly returns
Option<HandlerResult>and keeps the existingBrStyle‑based newline behavior, withserialize_if_faithful!still guarding faithful mode. As long as theInto<HandlerResult>impl for string types setsmarkdown_translatedas expected (likelytruehere), this change is consistent with the new API.Also applies to: 8-14
tests/basic_tests.rs (1)
533-571: Tests correctly reflect newOption<HandlerResult>handler semanticsThe updated custom-handler tests for
<img>look good:
with_custom_rulesuses|_, _| Noneto fully skip images, and the empty Markdown expectation matches the new contract.with_custom_rules_and_fallbackcleanly demonstrates conditionalNonevschain.proceed(element)and verifies that the built‑in image handler is still used when the condition matches.Nice coverage of both the “skip” and “fallback” paths under the new API.
src/element_handler/anchor.rs (1)
5-77: Anchor handler’s move toOption<HandlerResult>is consistent and preserves behaviorThe updated
AnchorElementHandlercleanly switches tohandle(&self, _chain, element) -> Option<HandlerResult>:
- The no‑href case now returns
Some(element.content.into()), which matches the previous “pass content through” behavior.- All link cases return
Some(md.into()), aligning with theHandlerResultconversions used elsewhere.- Faithful-mode fallback via
serialize_if_faithful!remains intact.I don’t see any behavioral regressions here.
src/lib.rs (2)
35-54: Visibility change forElement::skipped_handlersmay be a breaking API changeChanging
skipped_handlersfrompubtopub(crate)tightens the public API. This is an improvement for encapsulation but will break any downstream code that accessed this field directly.If you consider
Elementpart of the public surface, please double‑check that you’re comfortable with this as a breaking change (and bump versioning accordingly) or, alternatively, expose any needed functionality via methods instead of the field.
85-219: OwnedOptionsand newskip_tagshandler semantics look goodThe changes to
HtmlToMarkdown::new/HtmlToMarkdownBuilder::newandoptions():
- Construct
ElementHandlerswith ownedOptionsand store them directly, which matches the refactoredElementHandlers::new(options: Options)and removes unnecessaryArcindirection.- Updating
self.handlers.optionsinoptions()keeps all element handlers reading the latest configuration viaelement.options.For skipping tags:
skip_tagsnow uses.add_handler(tags, |_: &dyn Chain, _: Element| None), and the doc example mirrors this. Under the new API,Nonecorrectly represents “produce no output for this element,” which aligns with how tests exercise custom handlers.This all looks consistent with the new
Option<HandlerResult>contract.src/element_handler/img.rs (1)
3-59: Verify compilation status and apply idiom improvementThe borrow-checker concern cannot be definitively verified without running
rustcin this environment. However:
If the code compiles as-is: the suggested fix using
as_deref().unwrap_or("")is still strongly recommended—it's more idiomatic, avoids creating temporaryStringobjects, and relies on the static lifetime of the empty string literal.If the code fails to compile: the fix is necessary. Apply the suggested change to use
as_deref().unwrap_or("")instead ofas_ref().unwrap_or(&String::new())for bothaltandlinkat lines ~48 and ~50.Please verify locally with
cargo checkwhether compilation succeeds with the current code, and apply the fix if needed (or if you want to adopt the more idiomatic pattern regardless).src/element_handler/tbody.rs (1)
1-6: tbody handler correctly delegates to shared parent-aware utilityThe refactor to
Option<HandlerResult>and delegation tohandle_or_serialize_by_parentcleanly centralizes the faithful vs markdown behavior for<tbody>and keeps the handler itself minimal. Looks good.Also applies to: 8-12
src/element_handler/html.rs (1)
5-6: Root detection and HandlerResult shaping inhtml_handlerlook soundThe faithful-mode root check via
get_parent_node/NodeData::Documentmatches the “only root html is markdown-translatable” intent, and the two return paths (.into()for markdown vs explicitserialize_elementwithmarkdown_translated: false) are consistent with the new handler API.Also applies to: 11-31
src/element_handler/element_util.rs (1)
39-168: Sharedserialize_elementandserialize_if_faithful!look consistent with existing semanticsThe split between inline vs block serialization, plus the newline-normalization for blocks, matches the provided earlier implementation, and the macro-based early return in faithful mode integrates cleanly with
HandlerResult. Centralizing these pieces here should simplify the other handlers without changing behavior.src/element_handler/li.rs (1)
3-5:list_item_handlercorrectly separates<ol>and<ul>behavior under the new APIThe refactor preserves the existing list formatting logic while cleanly routing ordered items via the parent tag check and returning
HandlerResultvia.into(). The earlyserialize_if_faithful!guard also keeps faithful-mode HTML fallback centralized.Also applies to: 10-38
src/element_handler/headings.rs (1)
2-7: Headings handler migration toHandlerResultpreserves formatting behaviorThe handler still computes heading level and chooses Setext vs ATX styles as before, and wrapping the final string in
HandlerResultvia.into()integrates smoothly with the new handler API and the faithful-mode macro.Also applies to: 9-29
src/element_handler/mod.rs (6)
6-6: Module wiring and imports match the new designThe new
element_utilmodule and added imports (walk_node,serialize_element,Node,Rc) line up with how this file now uses them; I don’t see any correctness or style issues here.Also applies to: 24-28, 45-48
102-113: OwningOptionsdirectly inElementHandlersis reasonableStoring
Optionsby value and taking it by value inElementHandlers::newsimplifies ownership and removesArcoverhead. Given the usage insrc/lib.rs(construct once and mutate viahandlers.options = options), this looks correct and should be a minor perf win.Just confirm that
ElementHandlersisn’t intended to be cheaply cloned/shared across threads anymore; if it is, you may want an explicitCloneonOptionsor a builder that clones as needed.
244-291: Handler dispatch and faithful fallback logic look correctRouting through
ElementHandlers::handlenow returningOption<HandlerResult>is consistent with the rest of the refactor:
- The
ruleslookup with.filter(...).rev().nth(skipped_handlers)preserves the “last registered wins, withproceedwalking backwards” semantics.- In the
Some(rule)case, the constructedElementpasses all the expected fields, includingskipped_handlers, into the handler.- In the
Nonecase:
- For
TranslationMode::Faithful, you serialize the element to HTML and correctly setmarkdown_translated: false.- For other modes,
Some(content.into())uses theFrom<&str>impl and marks the already-produced content as Markdown, which matches expectations.I don’t see functional issues in this method; the behavior matches how
walk_nodeand the downstream handlers consumeHandlerResult.
295-326:Chaintrait and itsElementHandlersimpl integrate cleanly withwalk_nodeThe updated
Chainmethods:
proceedcorrectly incrementsskipped_handlersand delegates back intoElementHandlers::handle, preserving the handler-chaining behavior.handlewrapsdom_walker::walk_nodeand returns a singleHandlerResultwith the joined buffer and the subtree’smarkdown_translatedflag, which matches how callers liketable_handlernow consume it.There’s no recursion bug here (the
walk_nodecalls the multi-argElementHandlers::handle, notChain::handle), and the Option is consistentlySomefor this implementation, which is fine.
328-337:block_handlercorrectly distinguishes pure vs faithful modesThe new
block_handlerimplementation maps cleanly ontoHandlerResult:
- In
TranslationMode::Pure, it emits Markdown-wrapped content viaconcat_strings!andInto<HandlerResult>, marking it as translated.- Otherwise, it serializes to HTML via
serialize_elementand explicitly setsmarkdown_translated: false, which is what faithful/raw HTML handling expects.No issues here; behavior is clear and aligned with the surrounding design.
339-345:bold_handleranditalic_handlercorrectly forward toemphasis_handlerBoth handlers now return
Option<HandlerResult>and simply delegate toemphasis_handlerwith the appropriate markers ("**"and"*"), keeping the behavior centralized. Types and delegation look consistent with the new API.
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
There was a problem hiding this comment.
Actionable comments posted: 3
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/element_handler/list.rs(2 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/element_handler/list.rs (3)
src/element_handler/element_util.rs (1)
serialize_element(39-169)src/node_util.rs (2)
get_node_tag_name(5-11)get_parent_node(13-24)src/text_util.rs (2)
indent_text_except_first_line(178-197)join_contents(108-134)
🔇 Additional comments (1)
src/element_handler/list.rs (1)
43-53: Previous borrow issue has been resolved.The temporary borrow issue flagged in the previous review has been correctly fixed by using owned strings. The logic now properly handles both
oland other list elements with appropriate trimming and newline spacing.
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (2)
src/element_handler/list.rs (2)
113-117: Fixdigits(0)returning 0.The past review correctly identified that
digits(0)returns 0 instead of 1. This bug persists in the current code:
log10(1) = 0.0,ceil(0.0) = 0, cast tousizegives 0- The string
"0"has 1 digit, not 0- This causes incorrect spacing calculation at line 127 and potential underflow
While this may not be reachable for non-empty lists, it's a latent bug for edge cases (e.g., if
li_count = 0leads tohighest_index = 0).Apply one of these fixes from the previous review:
Option 1 (explicit check):
fn digits(num: usize) -> usize { - ((num + 1) as f32).log10().ceil() as usize + if num == 0 { + 1 + } else { + ((num + 1) as f32).log10().ceil() as usize + } }Option 2 (use max):
fn digits(num: usize) -> usize { - ((num + 1) as f32).log10().ceil() as usize + ((num + 1) as f32).log10().ceil().max(1.0) as usize }
119-131: Prevent potential underflow in spacing calculation.Line 127's spacing calculation can underflow if:
digits(highest_index)returns 0 (the bug flagged in the previous comment)ol_number_spacingis set to a small value (default is 2, but users can configure it)index_str.len()exceedsol_number_spacing + digits(highest_index)The subtraction would panic in debug mode or wrap in release mode.
Apply this diff to use saturating arithmetic:
fn add_ol_li_marker( options: &Options, content: &str, index: usize, highest_index: usize, ) -> String { let index_str = index.to_string(); - let spacing = - " ".repeat(options.ol_number_spacing as usize + digits(highest_index) - index_str.len()); + let spacing_width = (options.ol_number_spacing as usize + digits(highest_index)) + .saturating_sub(index_str.len()); + let spacing = " ".repeat(spacing_width); let content = content.trim_start_matches('\n'); let content = indent_text_except_first_line(content, index_str.len() + 1 + spacing.len(), true); concat_strings!("\n", index_str, ".", spacing, content) }
🧹 Nitpick comments (1)
src/element_handler/list.rs (1)
61-111: Consider following the suggested pattern from the previous review.While line 69's
.max(1)clamp correctly prevents underflow, line 96's pattern (curr_li_idx = start_idx - 1followed by increment before use) is less clear than the pattern suggested in the previous review. The past review recommended starting withcurr_li_idx = start_idxand incrementing at the beginning of the usage block for better readability.Apply this diff to follow the cleaner pattern:
- let mut curr_li_idx = start_idx - 1; + let mut curr_li_idx = start_idx; let contents = buffer .into_iter() .map(|content| { if content.is_li { - curr_li_idx += 1; - add_ol_li_marker(element.options, &content.text, curr_li_idx, highest_index) + let marker = add_ol_li_marker(element.options, &content.text, curr_li_idx, highest_index); + curr_li_idx += 1; + marker } else { content.text }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
.gitignore(1 hunks)benches/README.md(1 hunks)src/element_handler/list.rs(2 hunks)tests/list_tests.rs(1 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
tests/list_tests.rs (2)
src/lib.rs (3)
builder(104-106)default(80-82)default(157-159)src/options.rs (1)
default(22-37)
src/element_handler/list.rs (4)
src/element_handler/element_util.rs (1)
serialize_element(39-169)src/node_util.rs (2)
get_node_tag_name(5-11)get_parent_node(13-24)src/text_util.rs (2)
indent_text_except_first_line(178-197)join_contents(108-134)src/element_handler/mod.rs (1)
new(109-230)
🪛 markdownlint-cli2 (0.18.1)
benches/README.md
17-17: Fenced code blocks should have a language specified
(MD040, fenced-code-language)
🔇 Additional comments (3)
.gitignore (1)
2-3: Good additions for generated artifacts.Both additions are appropriate for the
.gitignorefile and align with the PR objectives:
output_*.md: Generated markdown files from the handler result serialization refactoringflamegraph.svg: Performance profiling visualization outputtests/list_tests.rs (1)
76-104: LGTM! Good coverage of edge cases.The test properly verifies that invalid
startattribute values (zero and negative) are normalized to 1, which aligns with the implementation fix insrc/element_handler/list.rsat line 69.src/element_handler/list.rs (1)
12-54: LGTM! Handler refactor is clean.The migration to
HandlerResultis well-executed, and the delegation toget_ol_contentfor ordered lists properly separates concerns. The use of.to_owned()at line 46 correctly avoids the temporary borrow issue flagged in previous reviews.
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (2)
src/element_handler/list.rs (2)
65-111: LGTM! Integer underflow properly prevented.The
startattribute parsing correctly uses.max(1)to ensurestart_idx >= 1, preventing the underflow issue flagged in previous reviews. The subsequentcurr_li_idx = start_idx - 1is now safe.Minor: Consider handling empty list edge case explicitly.
When
li_count == 0, line 94 computeshighest_index = start_idx - 1, which could be 0. While this doesn't cause runtime issues (becauseadd_ol_li_markeris never called when there are no<li>elements), it's semantically inconsistent forhighest_index < start_idx. Consider initializinghighest_index = start_idxwhenli_count == 0for clarity:- let highest_index = start_idx + li_count - 1; + let highest_index = if li_count == 0 { + start_idx + } else { + start_idx + li_count - 1 + };
122-134: Consider saturating_sub for extra safety.The spacing calculation at line 130 is currently safe because
index <= highest_indexensuresindex_str.len() <= digits(highest_index). However, for defensive programming, consider usingsaturating_sub:- let spacing = - " ".repeat(options.ol_number_spacing as usize + digits(highest_index) - index_str.len()); + let spacing_width = (options.ol_number_spacing as usize + digits(highest_index)) + .saturating_sub(index_str.len()); + let spacing = " ".repeat(spacing_width);This guards against potential underflow if the function is called with unexpected parameters in the future.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/element_handler/list.rs(2 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/element_handler/list.rs (3)
src/element_handler/element_util.rs (1)
serialize_element(39-169)src/node_util.rs (2)
get_node_tag_name(5-11)get_parent_node(13-24)src/text_util.rs (2)
indent_text_except_first_line(178-197)join_contents(108-134)
🔇 Additional comments (6)
src/element_handler/list.rs (6)
1-10: LGTM! Clean import organization.The new imports support the HandlerResult refactoring and OL rendering logic introduced in this file.
12-37: LGTM! HandlerResult migration completed correctly.The function signature and return statements have been properly updated to use the unified
HandlerResulttype, maintaining all the original faithful mode validation logic.
43-54: LGTM! Borrow of temporary fixed correctly.The previous borrow-of-temporary issue has been properly resolved by materializing owned
Stringvalues before trimming. The logic correctly handles both OL and non-OL cases.
56-59: LGTM! Clear and simple data structure.The
ListChildContentstruct provides a clean abstraction for tracking list children during processing.
113-120: LGTM! Zero-case bug fixed correctly.The
digitsfunction now correctly handlesdigits(0) == 1, preventing the incorrect spacing calculations and potential underflow that were flagged in previous reviews.
136-147: LGTM! Good test coverage for digits function.The tests cover important edge cases including the zero case that was previously problematic.
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/element_handler/mod.rs (1)
233-248: Fix the redundant_closure warning causing CI failure in add_handler.The
or_insert_with(|| Vec::new())pattern on line 245 triggers clippy's redundant_closure lint, which fails CI since clippy runs with--deny warnings.The tag index maintenance logic is correct: the handler index is assigned once and appended to all tag entries, enabling proper override and Chain::proceed behavior.
Apply this fix:
- let indices = self - .tag_to_handler_indices - .entry(tag.to_owned()) - .or_insert_with(|| Vec::new()); + let indices = self + .tag_to_handler_indices + .entry(tag.to_owned()) + .or_insert_with(Vec::new);
Vec::newis a valid function reference matching theFnOnce() -> Vrequirement, replacing the unnecessary closure without behavior change. After applying, runcargo clippy -- --deny warningslocally to confirm the warning is resolved.
♻️ Duplicate comments (1)
benches/README.md (1)
15-24: Add language identifier to fenced benchmark output block.The fenced block under “# Result” still has no language, which keeps triggering MD040 from markdownlint. Suggest using
text(ornone) to keep rendering neutral:-``` +```text convert() time: [24.810 ms 24.847 ms 24.891 ms] ...Please re-run your markdownlint job after this change to confirm the warning is gone. </blockquote></details> </blockquote></details> <details> <summary>🧹 Nitpick comments (2)</summary><blockquote> <details> <summary>src/lib.rs (1)</summary><blockquote> `124-147`: **append() aggregation over handlers is correct but could be encapsulated.** Iterating `for handler in &self.handlers.handlers` and aggregating `append()` output works and preserves the intended “post-processing” behavior (e.g., link footnotes), but it couples `HtmlToMarkdown` to the internal `handlers` vec layout. A small helper on `ElementHandlers` like `fn collect_append(&self) -> String` would hide this detail and keep `HtmlToMarkdown` oblivious to the storage shape. If you plan more internal changes to `ElementHandlers` (e.g., different storage), consider adding such a helper now to avoid touching the public converter again later. </blockquote></details> <details> <summary>src/element_handler/mod.rs (1)</summary><blockquote> `55-79`: **HandlerResult design is coherent with the new handler flow.** The `HandlerResult { content, markdown_translated }` struct plus `From<String>` / `From<&str>` (defaulting `markdown_translated: true`) line up well with how `dom_walker` propagates translation state and how most handlers return fully‑markdown content. This should make handler implementations simpler and less error‑prone than the previous tuple type. If you anticipate debugging handlers often, consider deriving `Debug` (and maybe `Clone`) on `HandlerResult` to ease inspection, then re-run your tests to ensure no trait bounds are accidentally tightened. </blockquote></details> </blockquote></details> <details> <summary>📜 Review details</summary> **Configuration used**: CodeRabbit UI **Review profile**: CHILL **Plan**: Pro <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 990a4bc9fc421b025abe616a9523eff725700087 and 639d9a7ade6fbea4eae5af5d0b5170da32aa7f46. </details> <details> <summary>📒 Files selected for processing (3)</summary> * `benches/README.md` (1 hunks) * `src/element_handler/mod.rs` (7 hunks) * `src/lib.rs` (6 hunks) </details> <details> <summary>🧰 Additional context used</summary> <details> <summary>🧬 Code graph analysis (2)</summary> <details> <summary>src/lib.rs (1)</summary><blockquote> <details> <summary>src/element_handler/mod.rs (1)</summary> * `new` (109-231) </details> </blockquote></details> <details> <summary>src/element_handler/mod.rs (11)</summary><blockquote> <details> <summary>src/dom_walker.rs (1)</summary> * `walk_node` (17-103) </details> <details> <summary>src/element_handler/element_util.rs (1)</summary> * `serialize_element` (39-169) </details> <details> <summary>src/element_handler/p.rs (1)</summary> * `p_handler` (8-11) </details> <details> <summary>src/element_handler/pre.rs (1)</summary> * `pre_handler` (10-34) </details> <details> <summary>src/element_handler/table.rs (1)</summary> * `table_handler` (18-153) </details> <details> <summary>src/element_handler/tbody.rs (1)</summary> * `tbody_handler` (8-13) </details> <details> <summary>src/element_handler/td_th.rs (1)</summary> * `td_th_handler` (8-11) </details> <details> <summary>src/element_handler/thead.rs (1)</summary> * `thead_handler` (8-13) </details> <details> <summary>src/element_handler/tr.rs (1)</summary> * `tr_handler` (8-17) </details> <details> <summary>src/element_handler/anchor.rs (3)</summary> * `append` (20-30) * `handle` (32-77) * `new` (81-83) </details> <details> <summary>src/lib.rs (3)</summary> * `new` (88-95) * `new` (165-172) * `options` (175-178) </details> </blockquote></details> </details><details> <summary>🪛 GitHub Actions: Cargo Build & Test</summary> <details> <summary>src/element_handler/mod.rs</summary> [error] 245-245: redundant closure: replace the closure with the associated function itself (Vec::new) as clippy warns about redundant_closure when using or_insert_with(|| Vec::new()) --- [error] 293-293: you seem to be trying to use `&Box<T>`. Consider using just `&T` (suggested: `&dyn ElementHandler`) </details> </details> <details> <summary>🪛 markdownlint-cli2 (0.18.1)</summary> <details> <summary>benches/README.md</summary> 17-17: Fenced code blocks should have a language specified (MD040, fenced-code-language) </details> </details> </details> <details> <summary>🔇 Additional comments (6)</summary><blockquote> <details> <summary>src/lib.rs (2)</summary><blockquote> `34-55`: **Element.skipped_handlers field wiring looks consistent with Chain::proceed.** The new `pub(crate) skipped_handlers: usize` on `Element` matches how `ElementHandlers::handle` and `Chain::proceed` pass and increment the skip count, enabling multi‑handler chaining per tag without exposing it publicly. No issues spotted with lifetimes or visibility here. If you have custom handlers that call `Chain::proceed`, it’s worth re-running those tests to confirm they still see the expected “next handler” behavior under the new `skipped_handlers` model. --- `163-183`: **Builder `options` and `skip_tags` behavior aligns with the new handler API.** - `HtmlToMarkdownBuilder::new` and `.options()` correctly pass/assign `Options` by value to `ElementHandlers`. - `.skip_tags()` now installs a handler `|_, _| None`, which cleanly drops those tags using the new `Option<HandlerResult>` signature and still leaves `markdown_translated` driven by the children (for tags that have any). This keeps the public builder ergonomics intact with the refactored internals. After upgrading, it’s worth re-running any code that relies on `skip_tags` in faithful vs pure translation modes to confirm the new `None`-based semantics match your expectations. </blockquote></details> <details> <summary>src/element_handler/mod.rs (4)</summary><blockquote> `81-99`: **Updated ElementHandler trait and closure impl match the HandlerResult API.** Switching `ElementHandler::handle` to `Option<HandlerResult>` and keeping `append()` as a default no‑op is consistent with the new design, and the blanket impl for `Fn(&dyn Chain, Element) -> Option<HandlerResult>` keeps builder‑style closures ergonomic. For any existing custom handlers, double-check their signatures now return `Option<HandlerResult>` and that they set `markdown_translated` correctly when emitting HTML instead of Markdown. --- `101-115`: **ElementHandlers struct and constructor correctly encapsulate handler state.** Using `handlers: Vec<Box<dyn ElementHandler>>`, `tag_to_handler_indices: HashMap<String, Vec<usize>>`, and an owned `Options` value in `ElementHandlers::new(options)` cleanly centralizes handler wiring. The `Options` ownership change aligns with the rest of the refactor (no more `Arc` here) and keeps the public API unchanged. If any code relied on sharing `Options` by `Arc`, please confirm that the new by‑value ownership still satisfies your concurrency or sharing requirements. --- `250-291`: **Handler dispatch and faithful/pure fallback logic look correct.** - `ElementHandlers::handle` correctly uses `find_handler(tag, skipped_handlers)` to pick the most recently registered handler and passes through `Element { .., skipped_handlers }`, enabling `Chain::proceed` to walk earlier handlers. - When no handler exists: - In `TranslationMode::Faithful`, you serialize via `serialize_element` and mark `markdown_translated: false`, which is appropriate. - Otherwise, you return `content.into()` and keep `markdown_translated: true`, letting pure translation drop unknown tags while preserving their converted children. The explicit `skipped_handlers: 0` in the faithful fallback is fine since `serialize_element` ignores it. Please ensure your faithful-vs-pure mode regression tests still pass, especially around previously unhandled tags, since this path now always goes through `serialize_element` in faithful mode. --- `300-351`: **Chain implementation and block/emphasis helpers align with the new pipeline.** - `Chain::proceed` reuses `ElementHandlers::handle` with `skipped_handlers + 1`, which correctly moves to the previous handler for that tag. - `Chain::handle` walks a subtree via `walk_node` and wraps the result into a `HandlerResult`, making nested processing (e.g., in table/row handlers) straightforward. - `block_handler`, `bold_handler`, and `italic_handler` now return `Option<HandlerResult>` and use `concat_strings!` or delegate to `emphasis_handler` appropriately, preserving prior behavior with the new API. Given the centrality of `Chain` to custom handlers, it’s worth re-running any handler-heavy tests (tables, lists, nested quotes) to validate there are no unexpected recursion or markdown_translated propagation issues. </blockquote></details> </blockquote></details> </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
ElementHandlerRefactoring Part 2Fix performance(Optimize text_util #61 Refactor walk_children() #62)Summary by CodeRabbit
Documentation
Refactor
Tests
Chores