forked from rodd-oss/gomp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathasset-library.go
82 lines (66 loc) · 1.65 KB
/
asset-library.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*
This Source Code Form is subject to the terms of the Mozilla
Public License, v. 2.0. If a copy of the MPL was not distributed
with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package gomp
import (
"fmt"
"github.com/negrel/assert"
)
type AnyAssetLibrary interface {
LoadAll()
Unload(path string)
UnloadAll()
}
func CreateAssetLibrary[T any](loader func(path string) T, unloader func(path string, asset *T)) AssetLibrary[T] {
return AssetLibrary[T]{
data: make(map[string]*T),
loader: loader,
unloader: unloader,
loaderQueue: make([]string, 0, 1024),
}
}
type AssetLibrary[T any] struct {
data map[string]*T
loader func(path string) T
unloader func(path string, asset *T)
loaderQueue []string
}
func (r *AssetLibrary[T]) Get(path string) *T {
value, ok := r.data[path]
if !ok {
r.loaderQueue = append(r.loaderQueue, path)
value = new(T)
r.data[path] = value
}
return value
}
func (r *AssetLibrary[T]) Load(path string) {
_, ok := r.data[path]
assert.False(ok, fmt.Errorf("asset already loaded: %s", path))
resource := r.loader(path)
r.data[path] = &resource
}
func (r *AssetLibrary[T]) LoadAll() {
if len(r.loaderQueue) == 0 {
return
}
for _, path := range r.loaderQueue {
resource := r.loader(path)
*r.data[path] = resource
}
r.loaderQueue = r.loaderQueue[:0]
}
func (r *AssetLibrary[T]) Unload(path string) {
value, ok := r.data[path]
assert.True(ok, fmt.Errorf("asset not loaded: %s", path))
r.unloader(path, value)
delete(r.data, path)
}
func (r *AssetLibrary[T]) UnloadAll() {
for path, value := range r.data {
r.unloader(path, value)
}
r.data = make(map[string]*T)
}