-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: cache file read by stat mod time
- Loading branch information
Showing
2 changed files
with
79 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,73 @@ | ||
package main | ||
|
||
import ( | ||
"os" | ||
"sync" | ||
) | ||
|
||
func readFileWithStatCache(file string) func() ([]byte, error) { | ||
mu := new(sync.RWMutex) | ||
var ( | ||
lastReadContent []byte | ||
lastStat os.FileInfo | ||
) | ||
|
||
fast := func() (bool, []byte, error) { | ||
stat, err := os.Stat(file) | ||
if err != nil { | ||
return false, nil, err | ||
} | ||
|
||
mu.RLock() | ||
defer mu.RUnlock() | ||
|
||
if lastStat == nil { | ||
// no cache | ||
return false, nil, nil | ||
} | ||
|
||
if lastStat.ModTime() == stat.ModTime() { | ||
return true, lastReadContent, nil | ||
} | ||
|
||
// mod time changed | ||
return false, nil, nil | ||
} | ||
|
||
slow := func() ([]byte, error) { | ||
mu.Lock() | ||
defer mu.Unlock() | ||
|
||
stat, err := os.Stat(file) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
if lastStat != nil && lastStat.ModTime() == stat.ModTime() { | ||
return lastReadContent, nil | ||
} | ||
|
||
lastStat = stat | ||
lastReadContent = nil | ||
|
||
content, err := os.ReadFile(file) | ||
if err != nil { | ||
return nil, err | ||
} | ||
lastReadContent = content | ||
|
||
return content, nil | ||
} | ||
|
||
return func() ([]byte, error) { | ||
readFromCache, content, err := fast() | ||
if err != nil { | ||
return nil, err | ||
} | ||
if readFromCache { | ||
return content, nil | ||
} | ||
|
||
return slow() | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters