package filecache

import (
	
	
	
	
	
	
)

// New returns a new Cache implemented by fileCache.
func ( string) Cache {
	return newFileCache()
}

func newFileCache( string) *fileCache {
	return &fileCache{dirPath: }
}

// fileCache persists compiled functions into dirPath.
//
// Note: this can be expanded to do binary signing/verification, set TTL on each entry, etc.
type fileCache struct {
	dirPath string
}

func ( *fileCache) ( Key) string {
	return path.Join(.dirPath, hex.EncodeToString([:]))
}

func ( *fileCache) ( Key) ( io.ReadCloser,  bool,  error) {
	,  := os.Open(.path())
	if errors.Is(, os.ErrNotExist) {
		return nil, false, nil
	} else if  != nil {
		return nil, false, 
	} else {
		return , true, nil
	}
}

func ( *fileCache) ( Key,  io.Reader) ( error) {
	 := .path()
	,  := filepath.Split()

	,  := os.CreateTemp(, +".*.tmp")
	if  != nil {
		return
	}
	defer func() {
		.Close()
		if  != nil {
			_ = os.Remove(.Name())
		}
	}()
	if _,  = io.Copy(, );  != nil {
		return
	}
	if  = .Sync();  != nil {
		return
	}
	if  = .Close();  != nil {
		return
	}
	 = os.Rename(.Name(), )
	return
}

func ( *fileCache) ( Key) ( error) {
	 = os.Remove(.path())
	if errors.Is(, os.ErrNotExist) {
		 = nil
	}
	return
}