| 1 |
// =========================================================================== |
| 2 |
// |
| 3 |
// PUBLIC DOMAIN NOTICE |
| 4 |
// National Center for Biotechnology Information (NCBI) |
| 5 |
// |
| 6 |
// This software/database is a "United States Government Work" under the |
| 7 |
// terms of the United States Copyright Act. It was written as part of |
| 8 |
// the author's official duties as a United States Government employee and |
| 9 |
// thus cannot be copyrighted. This software/database is freely available |
| 10 |
// to the public for use. The National Library of Medicine and the U.S. |
| 11 |
// Government do not place any restriction on its use or reproduction. |
| 12 |
// We would, however, appreciate having the NCBI and the author cited in |
| 13 |
// any work or product based on this material. |
| 14 |
// |
| 15 |
// Although all reasonable efforts have been taken to ensure the accuracy |
| 16 |
// and reliability of the software and data, the NLM and the U.S. |
| 17 |
// Government do not and cannot warrant the performance or results that |
| 18 |
// may be obtained by using this software or data. The NLM and the U.S. |
| 19 |
// Government disclaim all warranties, express or implied, including |
| 20 |
// warranties of performance, merchantability or fitness for any particular |
| 21 |
// purpose. |
| 22 |
// |
| 23 |
// =========================================================================== |
| 24 |
// |
| 25 |
// File Name: text.go |
| 26 |
// |
| 27 |
// Author: Jonathan Kans |
| 28 |
// |
| 29 |
// ========================================================================== |
| 30 |
|
| 31 |
package eutils |
| 32 |
|
| 33 |
import ( |
| 34 |
"bytes" |
| 35 |
"container/heap" |
| 36 |
"io" |
| 37 |
"os" |
| 38 |
"strings" |
| 39 |
) |
| 40 |
|
| 41 |
// TextBlock is a (multi-line) string that is trimmed back to end with the last newline. |
| 42 |
// The excluded characters are saved and prepended to the next buffer. Providing complete |
| 43 |
// lines simplifies subsequent parsing. |
| 44 |
// (Derived from the more complex XMLBlock original.) |
| 45 |
type TextBlock string |
| 46 |
|
| 47 |
// CreateTextStreamer reads input blocks of line-oriented text that is trimmed back to end |
| 48 |
// at the last newline. The excluded characters are saved and prepended to the next buffer. |
| 49 |
func CreateTextStreamer(in io.Reader) <-chan TextBlock { |
| 50 |
|
| 51 |
if in == nil { |
| 52 |
return nil |
| 53 |
} |
| 54 |
|
| 55 |
out := make(chan TextBlock, chanDepth) |
| 56 |
if out == nil { |
| 57 |
DisplayError("Unable to create line block reader channel") |
| 58 |
os.Exit(1) |
| 59 |
} |
| 60 |
|
| 61 |
// lineReader sends trimmed line blocks through the output channel. |
| 62 |
lineReader := func(in io.Reader, out chan<- TextBlock) { |
| 63 |
|
| 64 |
// close channel when all blocks have been processed |
| 65 |
defer close(out) |
| 66 |
|
| 67 |
// 65536 appears to be the maximum number of characters presented to io.Reader |
| 68 |
// when input is piped from stdin. Increasing the buffer size when input is from |
| 69 |
// a file does not improve program performance. An additional 16384 bytes are |
| 70 |
// reserved for copying the previous remainder to the beginning of the buffer |
| 71 |
// before the next read. |
| 72 |
const BUFSIZE = 65536 + 16384 |
| 73 |
|
| 74 |
buffer := make([]byte, BUFSIZE) |
| 75 |
remainder := "" |
| 76 |
position := int64(0) |
| 77 |
delta := 0 |
| 78 |
isClosed := false |
| 79 |
|
| 80 |
// nextBuffer reads one buffer, trims back to the right-most newline character, |
| 81 |
// and retains the remainder for prepending in the next call. It also signals if |
| 82 |
// there was no newline character, resulting in subsequent calls to nextBuffer to |
| 83 |
// continue reading a large content string. |
| 84 |
nextBuffer := func() ([]byte, bool, bool) { |
| 85 |
|
| 86 |
if isClosed { |
| 87 |
return nil, false, true |
| 88 |
} |
| 89 |
|
| 90 |
// prepend previous remainder to beginning of buffer |
| 91 |
m := copy(buffer, remainder) |
| 92 |
remainder = "" |
| 93 |
if m > 16384 { |
| 94 |
// previous remainder is larger than reserved section, |
| 95 |
// write and signal the need to continue reading. |
| 96 |
return buffer[:m], true, false |
| 97 |
} |
| 98 |
|
| 99 |
// read next block, append behind copied remainder from previous read |
| 100 |
n, err := in.Read(buffer[m:]) |
| 101 |
// with data piped through stdin, read function may not always return the |
| 102 |
// same number of bytes each time |
| 103 |
if err != nil { |
| 104 |
if err != io.EOF { |
| 105 |
// real error. |
| 106 |
DisplayError("%s", err.Error()) |
| 107 |
// ignore bytes - non-conforming implementations of io.Reader may |
| 108 |
// return mangled data on non-EOF errors |
| 109 |
isClosed = true |
| 110 |
return nil, false, true |
| 111 |
} |
| 112 |
// end of file. |
| 113 |
isClosed = true |
| 114 |
if n == 0 { |
| 115 |
// if EOF and no more data, do not send final remainder (not terminated |
| 116 |
// by right angle bracket that is used as a sentinel) |
| 117 |
return nil, false, true |
| 118 |
} |
| 119 |
} |
| 120 |
if n < 0 { |
| 121 |
// reality check - non-conforming implementations of io.Reader may return -1 |
| 122 |
DisplayError("io.Reader returned negative count %d", n) |
| 123 |
// treat as n == 0 in order to update file offset and avoid losing previous remainder |
| 124 |
n = 0 |
| 125 |
} |
| 126 |
|
| 127 |
// keep track of file offset |
| 128 |
position += int64(delta) |
| 129 |
delta = n |
| 130 |
|
| 131 |
// slice of actual characters read |
| 132 |
bufr := buffer[:n+m] |
| 133 |
|
| 134 |
// Look for last newline character. It is safe to back up on UTF-8 rune array when looking |
| 135 |
// for a 7-bit ASCII character. |
| 136 |
pos := -1 |
| 137 |
for pos = len(bufr) - 1; pos >= 0; pos-- { |
| 138 |
if bufr[pos] == '\n' { |
| 139 |
// found end of line, break |
| 140 |
break |
| 141 |
} |
| 142 |
} |
| 143 |
|
| 144 |
// trim back to last newline character, save remainder for next buffer |
| 145 |
if pos > -1 { |
| 146 |
pos++ |
| 147 |
remainder = string(bufr[pos:]) |
| 148 |
return bufr[:pos], false, false |
| 149 |
} |
| 150 |
|
| 151 |
// no > found, signal need to continue reading long content |
| 152 |
return bufr[:], true, false |
| 153 |
} |
| 154 |
|
| 155 |
// nextBlock reads buffer, concatenates if necessary to place long element content |
| 156 |
// into a single string. All result strings end in a newline character that is used |
| 157 |
// sentinel in subsequent code. |
| 158 |
nextBlock := func() string { |
| 159 |
|
| 160 |
// read next buffer |
| 161 |
line, cont, closed := nextBuffer() |
| 162 |
|
| 163 |
if closed { |
| 164 |
// no sentinel in remainder at end of file |
| 165 |
return "" |
| 166 |
} |
| 167 |
|
| 168 |
if cont { |
| 169 |
// current line does not end with newline character |
| 170 |
var buff bytes.Buffer |
| 171 |
|
| 172 |
// keep reading long content blocks |
| 173 |
for { |
| 174 |
if len(line) > 0 { |
| 175 |
buff.Write(line) |
| 176 |
} |
| 177 |
if !cont { |
| 178 |
// last buffer ended with sentinel |
| 179 |
break |
| 180 |
} |
| 181 |
line, cont, closed = nextBuffer() |
| 182 |
if closed { |
| 183 |
// no sentinel in multi-block buffer at end of file |
| 184 |
return "" |
| 185 |
} |
| 186 |
} |
| 187 |
|
| 188 |
// concatenate blocks |
| 189 |
return buff.String() |
| 190 |
} |
| 191 |
|
| 192 |
return string(line) |
| 193 |
} |
| 194 |
|
| 195 |
// read lines and send blocks through channel |
| 196 |
for { |
| 197 |
str := nextBlock() |
| 198 |
|
| 199 |
// trimming spaces here would throw off line tracking |
| 200 |
|
| 201 |
out <- TextBlock(str) |
| 202 |
|
| 203 |
// bail after sending empty string sentinel |
| 204 |
if str == "" { |
| 205 |
return |
| 206 |
} |
| 207 |
} |
| 208 |
} |
| 209 |
|
| 210 |
// launch single block reader goroutine |
| 211 |
go lineReader(in, out) |
| 212 |
|
| 213 |
return out |
| 214 |
} |
| 215 |
|
| 216 |
// TextRecord wraps a numbered text record or the results of data extraction on that |
| 217 |
// record. The Index field stores the record's original position in the input stream. |
| 218 |
type TextRecord struct { |
| 219 |
Text string |
| 220 |
Index int |
| 221 |
} |
| 222 |
|
| 223 |
// CreateTextProducer partitions a text line set and sends records down a channel. |
| 224 |
// After processing asynchronously in multiple concurrent go routines, the |
| 225 |
// original order can be restored by passage through the TextUnshuffler. |
| 226 |
func CreateTextProducer(pat, require, exclude string, min, max int, inp <-chan TextBlock) <-chan TextRecord { |
| 227 |
|
| 228 |
if inp == nil || pat == "" { |
| 229 |
return nil |
| 230 |
} |
| 231 |
|
| 232 |
out := make(chan TextRecord, chanDepth) |
| 233 |
if out == nil { |
| 234 |
DisplayError("Unable to create text producer channel") |
| 235 |
os.Exit(1) |
| 236 |
} |
| 237 |
|
| 238 |
var ( |
| 239 |
rqr *BMHSearcher |
| 240 |
exc *BMHSearcher |
| 241 |
) |
| 242 |
|
| 243 |
if require != "" { |
| 244 |
rqr = StringSearcher(require, true, false, false, false, false) |
| 245 |
} |
| 246 |
|
| 247 |
if exclude != "" { |
| 248 |
exc = StringSearcher(exclude, true, false, false, false, false) |
| 249 |
} |
| 250 |
|
| 251 |
stringHasPattern := func(str string, sch *BMHSearcher) bool { |
| 252 |
|
| 253 |
found := false |
| 254 |
sch.Search(string(str[:]), 0, func(str, ptn string, pos int) bool { |
| 255 |
found = true |
| 256 |
return true |
| 257 |
}) |
| 258 |
return found |
| 259 |
} |
| 260 |
|
| 261 |
// textProducer sends partitioned strings through channel |
| 262 |
textProducer := func(pat string, rdr <-chan TextBlock, out chan<- TextRecord) { |
| 263 |
|
| 264 |
// close channel when all records have been processed |
| 265 |
defer close(out) |
| 266 |
|
| 267 |
rec := 0 |
| 268 |
pos := 0 |
| 269 |
|
| 270 |
// partition all input by pattern and send text substring to available consumer through channel |
| 271 |
PartitionText(pat, rdr, |
| 272 |
func(str string) { |
| 273 |
pos++ |
| 274 |
if rqr != nil && !stringHasPattern(str[:], rqr) { |
| 275 |
return |
| 276 |
} |
| 277 |
if exc != nil && stringHasPattern(str[:], exc) { |
| 278 |
return |
| 279 |
} |
| 280 |
if min > 0 && pos < min { |
| 281 |
return |
| 282 |
} |
| 283 |
if max > 0 && pos > max { |
| 284 |
return |
| 285 |
} |
| 286 |
rec++ |
| 287 |
out <- TextRecord{Index: rec, Text: str} |
| 288 |
}) |
| 289 |
} |
| 290 |
|
| 291 |
// launch single producer goroutine |
| 292 |
go textProducer(pat, inp, out) |
| 293 |
|
| 294 |
return out |
| 295 |
} |
| 296 |
|
| 297 |
// textRecordHeap collects asynchronous processing results for presentation in the original order. |
| 298 |
type textRecordHeap []TextRecord |
| 299 |
|
| 300 |
// methods that satisfy heap.Interface |
| 301 |
func (h textRecordHeap) Len() int { |
| 302 |
return len(h) |
| 303 |
} |
| 304 |
func (h textRecordHeap) Less(i, j int) bool { |
| 305 |
return h[i].Index < h[j].Index |
| 306 |
} |
| 307 |
func (h textRecordHeap) Swap(i, j int) { |
| 308 |
h[i], h[j] = h[j], h[i] |
| 309 |
} |
| 310 |
func (h *textRecordHeap) Push(x interface{}) { |
| 311 |
*h = append(*h, x.(TextRecord)) |
| 312 |
} |
| 313 |
func (h *textRecordHeap) Pop() interface{} { |
| 314 |
old := *h |
| 315 |
n := len(old) |
| 316 |
x := old[n-1] |
| 317 |
*h = old[0 : n-1] |
| 318 |
return x |
| 319 |
} |
| 320 |
|
| 321 |
// CreateTextUnshuffler passes the output of multiple concurrent processors to |
| 322 |
// a heap, which releases results in the same order as the original records. |
| 323 |
func CreateTextUnshuffler(inp <-chan TextRecord) <-chan string { |
| 324 |
|
| 325 |
if inp == nil { |
| 326 |
return nil |
| 327 |
} |
| 328 |
|
| 329 |
out := make(chan string, chanDepth) |
| 330 |
if out == nil { |
| 331 |
DisplayError("Unable to create text unshuffler channel") |
| 332 |
os.Exit(1) |
| 333 |
} |
| 334 |
|
| 335 |
// textUnshuffler restores original order with heap. |
| 336 |
textUnshuffler := func(inp <-chan TextRecord, out chan<- string) { |
| 337 |
|
| 338 |
// close channel when all records have been processed |
| 339 |
defer close(out) |
| 340 |
|
| 341 |
// initialize empty heap |
| 342 |
hp := &textRecordHeap{} |
| 343 |
heap.Init(hp) |
| 344 |
|
| 345 |
// index of next desired result |
| 346 |
next := 1 |
| 347 |
|
| 348 |
delay := 0 |
| 349 |
|
| 350 |
for ext := range inp { |
| 351 |
|
| 352 |
// push result onto heap |
| 353 |
heap.Push(hp, ext) |
| 354 |
|
| 355 |
// Read several values before checking to see if next record to print has been processed. |
| 356 |
// The default heapSize value has been tuned by experiment for maximum performance. |
| 357 |
if delay < heapSize { |
| 358 |
delay++ |
| 359 |
continue |
| 360 |
} |
| 361 |
|
| 362 |
delay = 0 |
| 363 |
|
| 364 |
for hp.Len() > 0 { |
| 365 |
|
| 366 |
// remove lowest item from heap, use interface type assertion |
| 367 |
curr := heap.Pop(hp).(TextRecord) |
| 368 |
|
| 369 |
if curr.Index > next { |
| 370 |
|
| 371 |
// record should be printed later, push back onto heap |
| 372 |
heap.Push(hp, curr) |
| 373 |
// and go back to waiting on input channel |
| 374 |
break |
| 375 |
} |
| 376 |
|
| 377 |
// send even if empty to get all record counts for reordering |
| 378 |
out <- curr.Text |
| 379 |
|
| 380 |
// prevent ambiguous -limit filter from clogging heap (deprecated) |
| 381 |
if curr.Index == next { |
| 382 |
// increment index for next expected match |
| 383 |
next++ |
| 384 |
} |
| 385 |
|
| 386 |
// continue to check heap to see if next result is already available |
| 387 |
} |
| 388 |
} |
| 389 |
|
| 390 |
// flush remainder of heap to output |
| 391 |
for hp.Len() > 0 { |
| 392 |
curr := heap.Pop(hp).(TextRecord) |
| 393 |
|
| 394 |
out <- curr.Text |
| 395 |
} |
| 396 |
} |
| 397 |
|
| 398 |
// launch single unshuffler goroutine |
| 399 |
go textUnshuffler(inp, out) |
| 400 |
|
| 401 |
return out |
| 402 |
} |
| 403 |
|
| 404 |
// PartitionText splits a set of text lines by a pattern and sends individual records |
| 405 |
// to a callback. Requiring the input to be a TextBlock channel of trimmed strings, |
| 406 |
// generated by CreateTextStreamer, simplifies the code by eliminating the need to |
| 407 |
// check for an incomplete pattern at the end. |
| 408 |
func PartitionText(pat string, inp <-chan TextBlock, proc func(string)) { |
| 409 |
|
| 410 |
if pat == "" || inp == nil || proc == nil { |
| 411 |
return |
| 412 |
} |
| 413 |
|
| 414 |
blk := make(chan string, chanDepth) |
| 415 |
out := make(chan string, chanDepth) |
| 416 |
if blk == nil || out == nil { |
| 417 |
DisplayError("Unable to create text producer channel") |
| 418 |
os.Exit(1) |
| 419 |
} |
| 420 |
|
| 421 |
// single string search uses Boyer-Moore-Horspool algorithm |
| 422 |
srchr := StringSearcher(pat, true, false, false, false, false) |
| 423 |
|
| 424 |
blockReader := func(inp <-chan TextBlock, blk chan<- string) { |
| 425 |
|
| 426 |
// close internal channel when all records have been processed |
| 427 |
defer close(blk) |
| 428 |
|
| 429 |
prevHit := 0 |
| 430 |
|
| 431 |
for text := range inp { |
| 432 |
|
| 433 |
srchr.Search(string(text[:]), 0, |
| 434 |
func(str, ptn string, pos int) bool { |
| 435 |
if prevHit != pos { |
| 436 |
txt := text[prevHit:pos] |
| 437 |
if txt != "" { |
| 438 |
blk <- string(txt) |
| 439 |
} |
| 440 |
prevHit = pos |
| 441 |
} |
| 442 |
return true |
| 443 |
}) |
| 444 |
|
| 445 |
if prevHit < len(text) { |
| 446 |
txt := text[prevHit:] |
| 447 |
if txt != "" { |
| 448 |
blk <- string(txt) |
| 449 |
} |
| 450 |
} |
| 451 |
|
| 452 |
prevHit = 0 |
| 453 |
} |
| 454 |
} |
| 455 |
|
| 456 |
blockMerger := func(blk <-chan string, out chan<- string) { |
| 457 |
|
| 458 |
// close channel when all records have been processed |
| 459 |
defer close(out) |
| 460 |
|
| 461 |
prev := "" |
| 462 |
|
| 463 |
for str := range blk { |
| 464 |
|
| 465 |
if str == "" { |
| 466 |
continue |
| 467 |
} |
| 468 |
|
| 469 |
// check for block starting with pattern |
| 470 |
if strings.HasPrefix(str, pat) { |
| 471 |
if prev != "" { |
| 472 |
// send previous buffer |
| 473 |
out <- prev |
| 474 |
// clear buffer |
| 475 |
prev = "" |
| 476 |
} |
| 477 |
} |
| 478 |
|
| 479 |
// add current block to buffer |
| 480 |
prev += str |
| 481 |
} |
| 482 |
|
| 483 |
if prev != "" { |
| 484 |
// send last buffer |
| 485 |
out <- prev |
| 486 |
} |
| 487 |
} |
| 488 |
|
| 489 |
// launch single block reader goroutine |
| 490 |
go blockReader(inp, blk) |
| 491 |
|
| 492 |
// launch single block merger goroutine |
| 493 |
go blockMerger(blk, out) |
| 494 |
|
| 495 |
// drain channel and send results to callback |
| 496 |
for str := range out { |
| 497 |
proc(str[:]) |
| 498 |
} |
| 499 |
} |