Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix stack overflow when searching in a book with a large TOC #473

Merged
merged 3 commits into from
Sep 2, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -102,37 +102,37 @@ public class StringSearchService: SearchService {
private var index = -1

func next() async -> SearchResult<LocatorCollection?> {
guard index < publication.readingOrder.count - 1 else {
return .success(nil)
}
while index < publication.readingOrder.count - 1 {
index += 1

let link = publication.readingOrder[index]

guard
let resource = publication.get(link),
let mediaType = link.mediaType,
let extractor = extractorFactory.makeExtractor(for: resource, mediaType: mediaType)
else {
log(.warning, "Cannot extract text from resource: \(link.href)")
continue
}

index += 1
switch await extractor.extractText(of: resource) {
case let .success(text):
let locators = await findLocators(in: link, resourceIndex: index, text: text)
// If no occurrences were found in the current resource, skip to the next one automatically.
guard !locators.isEmpty else {
continue
}

let link = publication.readingOrder[index]
resultCount = (resultCount ?? 0) + locators.count
return .success(LocatorCollection(locators: locators))

guard
let resource = publication.get(link),
let mediaType = link.mediaType,
let extractor = extractorFactory.makeExtractor(for: resource, mediaType: mediaType)
else {
log(.warning, "Cannot extract text from resource: \(link.href)")
return await next()
}

switch await extractor.extractText(of: resource) {
case let .success(text):
let locators = await findLocators(in: link, resourceIndex: index, text: text)
// If no occurrences were found in the current resource, skip to the next one automatically.
guard !locators.isEmpty else {
return await next()
case let .failure(error):
return .failure(.reading(error))
}

resultCount = (resultCount ?? 0) + locators.count
return .success(LocatorCollection(locators: locators))

case let .failure(error):
return .failure(.reading(error))
}

return .success(nil)
}

private func findLocators(in link: Link, resourceIndex: Int, text: String) async -> [Locator] {
Expand Down
Loading