Libraryless. Click here for Pure Java version (2723L/18K).
1 | // returns pair(character range, line) or null if not found |
2 | // if no exact match found, return line above |
3 | // nav takes a line and returns -1 (move up), 0 (found) or 1 (move down) |
4 | static Pair<LongRange, S> binarySearchForLineInTextFile(File file, IF1<S, Int> nav) { |
5 | long length = l(file); |
6 | int bufSize = 1024; |
7 | temp RandomAccessFile raf = randomAccessFileForReading(file); |
8 | long min = 0, max = length; |
9 | int direction = 0; |
10 | Pair<LongRange, S> possibleResult = null; |
11 | while ping (min < max) { |
12 | long middle = (min+max)/2; |
13 | long lineStart = raf_findBeginningOfLine(raf, middle, bufSize); |
14 | long lineEnd = raf_findEndOfLine(raf, middle, bufSize); |
15 | ifdef binarySearchForLineInTextFile_debug |
16 | printVars_str("binsearch", +middle, +lineStart, +lineEnd); |
17 | endifdef |
18 | S line = fromUtf8(raf_readFilePart(raf, lineStart, (int) (lineEnd-1-lineStart))); |
19 | direction = nav.get(line); |
20 | possibleResult = pair(LongRange(lineStart, lineEnd), line); |
21 | ifdef binarySearchForLineInTextFile_debug |
22 | S _line = dropTrailingBackslashR(line); |
23 | printVars_str("binsearch", +min, +max, +middle, +lineStart, +lineEnd, line := _line, +direction); |
24 | endifdef |
25 | if (direction == 0) ret possibleResult; |
26 | // asserts are to assure that loop terminates |
27 | if (direction < 0) max = assertLessThan(max, lineStart); |
28 | else min = assertBiggerThan(min, lineEnd); |
29 | ifdef binarySearchForLineInTextFile_debug |
30 | printVars_str("binsearch", +min, +max); |
31 | endifdef |
32 | } |
33 | |
34 | ifdef binarySearchForLineInTextFile_debug |
35 | printVars_str("binsearch ending", +direction); |
36 | endifdef |
37 | if (direction >= 0) ret possibleResult; |
38 | |
39 | long lineStart = raf_findBeginningOfLine(raf, min-1, bufSize); |
40 | S line = fromUtf8(raf_readFilePart(raf, lineStart, (int) (min-1-lineStart))); |
41 | ifdef binarySearchForLineInTextFile_debug |
42 | printVars_str("binsearch end",+lineStart, +line); |
43 | endifdef |
44 | ret pair(LongRange(lineStart, min), line); |
45 | } |
download show line numbers debug dex old transpilations
Travelled to 7 computer(s): bhatertpkbcr, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tvejysmllsmz, vouqrxazstgt, xrpafgyirdlv
No comments. add comment
Snippet ID: | #1028341 |
Snippet name: | binarySearchForLineInTextFile |
Eternal ID of this version: | #1028341/17 |
Text MD5: | 9c7c1e37068d6da44d4018a852060399 |
Transpilation MD5: | 92829e6f376ff937d84d4c112991fdbe |
Author: | stefan |
Category: | javax |
Type: | JavaX fragment (include) |
Public (visible to everyone): | Yes |
Archived (hidden from active list): | No |
Created/modified: | 2020-06-13 01:38:56 |
Source code size: | 1980 bytes / 45 lines |
Pitched / IR pitched: | No / No |
Views / Downloads: | 271 / 439 |
Version history: | 16 change(s) |
Referenced in: | [show references] |