Skip to content

Commit 5a159ce

Browse files
committed
updateDiffSync(): fix potential race
When updateDiffSync() is called asynchronously, it should lock the line array when calling Bytes(), to prevent race if the line array is being modified by the main goroutine in the meantime.
1 parent bca35a5 commit 5a159ce

File tree

1 file changed

+13
-4
lines changed

1 file changed

+13
-4
lines changed

internal/buffer/buffer.go

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1280,7 +1280,7 @@ func (b *Buffer) Write(bytes []byte) (n int, err error) {
12801280
return len(bytes), nil
12811281
}
12821282

1283-
func (b *Buffer) updateDiffSync() {
1283+
func (b *Buffer) updateDiff(synchronous bool) {
12841284
b.diffLock.Lock()
12851285
defer b.diffLock.Unlock()
12861286

@@ -1291,7 +1291,16 @@ func (b *Buffer) updateDiffSync() {
12911291
}
12921292

12931293
differ := dmp.New()
1294-
baseRunes, bufferRunes, _ := differ.DiffLinesToRunes(string(b.diffBase), string(b.Bytes()))
1294+
1295+
if !synchronous {
1296+
b.Lock()
1297+
}
1298+
bytes := b.Bytes()
1299+
if !synchronous {
1300+
b.Unlock()
1301+
}
1302+
1303+
baseRunes, bufferRunes, _ := differ.DiffLinesToRunes(string(b.diffBase), string(bytes))
12951304
diffs := differ.DiffMainRunes(baseRunes, bufferRunes, false)
12961305
lineN := 0
12971306

@@ -1333,11 +1342,11 @@ func (b *Buffer) UpdateDiff() {
13331342
}
13341343

13351344
if lineCount < 1000 {
1336-
b.updateDiffSync()
1345+
b.updateDiff(true)
13371346
} else if lineCount < 30000 {
13381347
b.updateDiffTimer = time.AfterFunc(500*time.Millisecond, func() {
13391348
b.updateDiffTimer = nil
1340-
b.updateDiffSync()
1349+
b.updateDiff(false)
13411350
screen.Redraw()
13421351
})
13431352
} else {

0 commit comments

Comments
 (0)