v2 / vlib / os / asset / asset.v
44 lines · 40 sloc · 1.55 KB · 2cd1c9e26bcdc0a87ef800cbe98aee6c52804bfc
Raw
1module asset
2
3import os
4
5// get_path returns a platform specific path, based on the given asset base folder and relative path
6// of a resource in it. On desktop systems, it returns a path relative to the location of the executable.
7// On Android, it will return just the relative_path segment, allowing you to later use os.read_apk_asset
8// to read from it.
9@[manualfree]
10pub fn get_path(base_folder string, relative_path string) string {
11 $if android {
12 return relative_path.clone()
13 } $else {
14 fpath := os.join_path_single(base_folder, relative_path)
15 defer { unsafe { fpath.free() } }
16 return os.resource_abs_path(fpath)
17 }
18}
19
20// read_bytes will read all of the given asset, specified by its base_folder and relative path in it.
21// On Android, it will use os.read_apk_asset, relying that the asset base folder has been prepared, and
22// prepackaged inside your APK. On desktop systems, it will use the base_folder and relative_path, to
23// locate the file, in a way, that is relative to the executable.
24@[manualfree]
25pub fn read_bytes(base_folder string, relative_path string) ![]u8 {
26 fpath := get_path(base_folder, relative_path)
27 defer { unsafe { fpath.free() } }
28 mut f_read := os.read_bytes
29 $if android {
30 f_read = os.read_apk_asset
31 }
32 res := f_read(fpath)!
33 return res
34}
35
36// read_text will return the full content of the given asset as a string.
37// See also read_bytes.
38@[manualfree]
39pub fn read_text(base_folder string, relative_path string) !string {
40 bytes := read_bytes(base_folder, relative_path)!
41 defer { unsafe { bytes.free() } }
42 res := bytes.bytestr()
43 return res
44}
45