@@ -21,24 +21,64 @@ export function flushBuffered(destination: Destination) {
21
21
// transform streams. https://github.com/whatwg/streams/issues/960
22
22
}
23
23
24
+ let currentView = null ;
25
+ let writtenBytes = 0 ;
26
+
24
27
export function beginWriting ( destination : Destination ) { }
25
28
26
29
export function writeChunk (
27
30
destination : Destination ,
28
31
chunk : PrecomputedChunk | Chunk ,
29
32
) : void {
30
- destination. enqueue ( chunk ) ;
33
+ if ( currentView === null ) {
34
+ currentView = new Uint8Array ( 512 ) ;
35
+ writtenBytes = 0 ;
36
+ }
37
+
38
+ if ( chunk . length > currentView . length ) {
39
+ // this chunk is larger than our view which implies it was not
40
+ // one that is cached by the streaming renderer. We will enqueu
41
+ // it directly and expect it is not re-used
42
+ if ( writtenBytes > 0 ) {
43
+ destination . enqueue ( new Uint8Array ( currentView . buffer , 0 , writtenBytes ) ) ;
44
+ currentView = null ;
45
+ writtenBytes = 0 ;
46
+ }
47
+ destination . enqueue ( chunk ) ;
48
+ return ;
49
+ }
50
+
51
+ let allowableBytes = currentView . length - writtenBytes ;
52
+ if ( allowableBytes < chunk . length ) {
53
+ // this chunk would overflow the current view. We enqueu a full view
54
+ // and start a new view with the remaining chunk
55
+ currentView. set ( chunk . subarray ( 0 , allowableBytes ) , writtenBytes ) ;
56
+ destination . enqueue ( currentView ) ;
57
+ currentView = new Uint8Array ( 512 ) ;
58
+ currentView . set ( chunk . subarray ( allowableBytes ) ) ;
59
+ writtenBytes = chunk . length - allowableBytes ;
60
+ } else {
61
+ currentView . set ( chunk , writtenBytes ) ;
62
+ writtenBytes += chunk . length ;
63
+ }
31
64
}
32
65
33
66
export function writeChunkAndReturn (
34
67
destination : Destination ,
35
68
chunk : PrecomputedChunk | Chunk ,
36
69
) : boolean {
37
- destination . enqueue ( chunk ) ;
38
- return destination . desiredSize > 0 ;
70
+ writeChunk ( destination , chunk ) ;
71
+ // in web streams there is no backpressure so we can alwas write more
72
+ return true ;
39
73
}
40
74
41
- export function completeWriting ( destination : Destination ) { }
75
+ export function completeWriting ( destination : Destination ) {
76
+ if ( writtenBytes > 0 ) {
77
+ destination . enqueue ( new Uint8Array ( currentView . buffer , 0 , writtenBytes ) ) ;
78
+ currentView = null ;
79
+ writtenBytes = 0 ;
80
+ }
81
+ }
42
82
43
83
export function close ( destination : Destination ) {
44
84
destination . close ( ) ;
0 commit comments