all repos — nds-converter @ 65fd5c5d446b6f9b9140ae33580f7311bec3167e

A lightweight save converter for NDS and DeSmuME.

convert.go (view raw)

 1package main
 2
 3import (
 4	"encoding/hex"
 5	"fmt"
 6	"io"
 7	"mime/multipart"
 8	"path/filepath"
 9)
10
11type ConverterFunction func([]byte) []byte
12
13const (
14	trimBytes          = 122
15	additionalBytesHex = "7C3C2D2D536E69702061626F7665206865726520746F2063726561746520612072617720736176206279206578636C7564696E672074686973204465536D754D4520736176656461746120666F6F7465723A0000010000000100030000000200000000000100000000007C2D4445534D554D4520534156452D7C"
16)
17
18var (
19	additionalBytes    = MustDecode(hex.DecodeString(additionalBytesHex))
20	converterFunctions = map[string]ConverterFunction{
21		".dsv": DsvToSav,
22		".sav": SavToDsv,
23	}
24)
25
26func MustDecode(content []byte, err error) []byte {
27	if err != nil {
28		panic(42)
29	}
30	return content
31}
32
33func DsvToSav(input []byte) []byte {
34	return input[:len(input)-trimBytes]
35}
36
37func SavToDsv(input []byte) []byte {
38	return append(input, additionalBytes...)
39}
40
41func Convert(file multipart.File, h *multipart.FileHeader) ([]byte, error) {
42	// Check file extension
43	fileExt := filepath.Ext(h.Filename)
44	converterFunction, exists := converterFunctions[fileExt]
45	if !exists {
46		return nil, fmt.Errorf("invalid file format: only .dsv and .sav files are allowed")
47	}
48
49	// Read file contents
50	content, err := io.ReadAll(file)
51	if err != nil {
52		return nil, err
53	}
54
55	// Return converted file
56	return converterFunction(content), nil
57}