package sfz import "strings" // Value is the Go types that the value of an opcode can be read as. type Value interface { int | int64 | float64 | string } // GetAs returns the value of an opcode, read as a T, and whether the opcode is // set and can be read as one. An opcode that the format gives aliases is found // by any of its names, so GetAs(o, "loop_mode") finds loopmode. An integer // opcode that takes notes, such as lokey, reads a note name as its MIDI number, // with middle C as c4. A string is returned without surrounding whitespace. func GetAs[T Value](o Opcodes, name string) (T, bool) { var zero T raw, ok := o[name] if !ok { info, known := Lookup(name) if !known { return zero, false } for _, alias := range append([]string{info.Name}, info.Aliases...) { if raw, ok = o[alias]; ok { break } } if !ok { return zero, false } } raw = strings.TrimSpace(raw) switch any(zero).(type) { case string: return any(raw).(T), true case float64: f, ok := parseNumber(raw) if !ok { return zero, false } return any(f).(T), true } var n int if info, known := Lookup(name); known && info.Note { n, ok = parseNote(raw) } else { var f float64 if f, ok = parseNumber(raw); ok { n = int(f) } } if !ok { return zero, false } if _, is64 := any(zero).(int64); is64 { return any(int64(n)).(T), true } return any(n).(T), true }