Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Various bugfixes and improvements around buffer md5 hash calculation and fastdirty #3430

Merged
merged 7 commits into from
Aug 18, 2024
38 changes: 12 additions & 26 deletions internal/buffer/buffer.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,10 +64,6 @@ var (
// BTStdout is a buffer that only writes to stdout
// when closed
BTStdout = BufType{6, false, true, true}

// ErrFileTooLarge is returned when the file is too large to hash
// (fastdirty is automatically enabled)
ErrFileTooLarge = errors.New("File is too large to hash")
)

// SharedBuffer is a struct containing info that is shared among buffers
Expand Down Expand Up @@ -554,7 +550,11 @@ func (b *Buffer) ReOpen() error {

err = b.UpdateModTime()
if !b.Settings["fastdirty"].(bool) {
calcHash(b, &b.origHash)
if len(data) > LargeFileThreshold {
b.Settings["fastdirty"] = true
} else {
calcHash(b, &b.origHash)
}
}
b.isModified = false
b.RelocateCursors()
Expand Down Expand Up @@ -649,37 +649,23 @@ func (b *Buffer) Size() int {
}

// calcHash calculates md5 hash of all lines in the buffer
func calcHash(b *Buffer, out *[md5.Size]byte) error {
func calcHash(b *Buffer, out *[md5.Size]byte) {
h := md5.New()

size := 0
if len(b.lines) > 0 {
n, e := h.Write(b.lines[0].data)
if e != nil {
return e
}
size += n
h.Write(b.lines[0].data)

for _, l := range b.lines[1:] {
n, e = h.Write([]byte{'\n'})
if e != nil {
return e
}
size += n
n, e = h.Write(l.data)
if e != nil {
return e
if b.Endings == FFDos {
h.Write([]byte{'\r', '\n'})
} else {
h.Write([]byte{'\n'})
}
size += n
h.Write(l.data)
}
}

if size > LargeFileThreshold {
return ErrFileTooLarge
}

h.Sum((*out)[:0])
return nil
}

func parseDefFromFile(f config.RuntimeFile, header *highlight.Header) *highlight.Def {
Expand Down
14 changes: 10 additions & 4 deletions internal/buffer/settings.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package buffer

import (
"crypto/md5"

"github.com/zyedidia/micro/v2/internal/config"
"github.com/zyedidia/micro/v2/internal/screen"
)
Expand All @@ -10,10 +12,14 @@ func (b *Buffer) SetOptionNative(option string, nativeValue interface{}) error {

if option == "fastdirty" {
if !nativeValue.(bool) {
if !b.Modified() {
e := calcHash(b, &b.origHash)
if e == ErrFileTooLarge {
b.Settings["fastdirty"] = false
if b.Size() > LargeFileThreshold {
b.Settings["fastdirty"] = true
} else {
if !b.isModified {
calcHash(b, &b.origHash)
} else {
// prevent using an old stale origHash value
b.origHash = [md5.Size]byte{}
}
}
}
Expand Down