MCPcopy
hub / github.com/spicetify/cli / ReadStringFromUTF16Binary

Function ReadStringFromUTF16Binary

src/utils/file-utils.go:11–60  ·  view source on GitHub ↗
(inputFile string, startMarker []byte, endMarker []byte)

Source from the content-addressed store, hash-verified

9)
10
11func ReadStringFromUTF16Binary(inputFile string, startMarker []byte, endMarker []byte) (string, int, int, error) {
12 fileContent, err := os.ReadFile(inputFile)
13 if err != nil {
14 return "", -1, -1, fmt.Errorf("error reading file %s: %w", inputFile, err)
15 }
16
17 isUTF16LE := false
18 if len(fileContent) >= 2 && fileContent[0] == 0xFF && fileContent[1] == 0xFE {
19 isUTF16LE = true
20 }
21
22 if !isUTF16LE && len(fileContent) > 100 && fileContent[1] == 0x00 {
23 isUTF16LE = true
24 }
25
26 var startIdx, endIdx int
27 var contentToSearch []byte
28 var searchStartMarker, searchEndMarker []byte
29
30 if !isUTF16LE {
31 return "", -1, -1, fmt.Errorf("file is not in UTF-16LE format: %s", inputFile)
32 }
33
34 contentToSearch = fileContent[2:]
35 searchStartMarker = encodeUTF16LE(startMarker)
36 searchEndMarker = encodeUTF16LE(endMarker)
37
38 startIdx = bytes.Index(contentToSearch, searchStartMarker)
39 if startIdx == -1 {
40 return "", -1, -1, fmt.Errorf("start marker not found: %s", string(startMarker))
41 }
42
43 searchSpace := contentToSearch[startIdx+len(searchStartMarker):]
44 endIdx = bytes.Index(searchSpace, searchEndMarker)
45 if endIdx == -1 {
46 return "", -1, -1, fmt.Errorf("end marker not found after start index %d: %s", startIdx+len(searchStartMarker), string(endMarker))
47 }
48
49 stringContentBytes := contentToSearch[startIdx : startIdx+len(searchStartMarker)+endIdx+len(searchEndMarker)]
50
51 decodedStringBytes, err := decodeUTF16LE(stringContentBytes)
52 if err != nil {
53 return "", -1, -1, fmt.Errorf("error decoding UTF-16LE content: %w", err)
54 }
55
56 // Adjust indices to be byte offsets in the original file
57 originalStartIdx := 2 + startIdx
58 originalEndIdx := 2 + endIdx + len(stringContentBytes)
59 return string(decodedStringBytes), originalStartIdx, originalEndIdx, nil
60}
61
62// Helper function to encode a byte slice (assumed UTF-8) to UTF-16LE
63func encodeUTF16LE(data []byte) []byte {

Callers 1

StartFunction · 0.92

Calls 2

encodeUTF16LEFunction · 0.85
decodeUTF16LEFunction · 0.85

Tested by

no test coverage detected