This repository has been archived by the owner on Jul 22, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.coffee
65 lines (54 loc) · 1.83 KB
/
index.coffee
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
class LazyLines
[rCode, nCode] = ['\r'.charCodeAt(0), '\n'.charCodeAt(0)]
constructor: (@stream) ->
return new LazyLines(@stream) if @ not instanceof LazyLines
@bufferedChunks = []
@bufferedLength = 0
@actions = []
@encoding = 'utf-8'
@stream.on('data', => onChunkReceived.apply(@, arguments))
@stream.on('end', => onStreamEnd.apply(@, arguments))
onChunkReceived = (chunk) ->
firstUnhandledIndex = 0
for chr, i in chunk
if chr in [rCode, nCode]
@bufferedChunks.push(chunk.slice(firstUnhandledIndex, i))
@bufferedLength += i - firstUnhandledIndex
onLineEndFound.call(@)
i += 1 if chr == rCode and chunk[i+1] == nCode
firstUnhandledIndex = i + 1
if firstUnhandledIndex != chunk.length
@bufferedChunks.push(chunk.slice(firstUnhandledIndex))
@bufferedLength += chunk.length - firstUnhandledIndex
onStreamEnd = ->
if @bufferedLength > 0
onLineEndFound.call(@)
onLineEndFound = ->
if @encoding?
line = (bufferedChunk.toString(@encoding) for bufferedChunk in @bufferedChunks).join('')
else
line = new Buffer(@bufferedLength)
targetLength = 0
for bufferedChunk in @bufferedChunks
bufferedChunk.copy(line, targetLength)
targetLength += bufferedChunk.length
@bufferedChunks = []
@bufferedLength = 0
for action in @actions
switch action.type
when 'forEach' then action.f(line)
when 'map' then line = action.f(line)
when 'filter' then return if action.f(line) == false
return
setEncoding: (@encoding) ->
return @
forEach: (f) ->
@actions.push({type: 'forEach', f: f})
return @
map: (f) ->
@actions.push({type: 'map', f: f})
return @
filter: (f) ->
@actions.push({type: 'filter', f: f})
return @
module.exports = LazyLines