You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

56 lines
1.3 KiB

2 years ago
2 years ago
2 years ago
  1. package effects
  2. import (
  3. "encoding/json"
  4. "errors"
  5. lucifer3 "git.aiterp.net/lucifer3/server"
  6. )
  7. type serializedEffect struct {
  8. Manual *Manual `json:"manual,omitempty"`
  9. Gradient *Gradient `json:"gradient,omitempty"`
  10. Pattern *Pattern `json:"pattern,omitempty"`
  11. Random *Random `json:"random,omitempty"`
  12. }
  13. type Serializable struct {
  14. Effect lucifer3.Effect
  15. }
  16. func (s *Serializable) UnmarshalJSON(raw []byte) error {
  17. value := serializedEffect{}
  18. err := json.Unmarshal(raw, &value)
  19. if err != nil {
  20. return err
  21. }
  22. switch {
  23. case value.Manual != nil:
  24. s.Effect = *value.Manual
  25. case value.Gradient != nil:
  26. s.Effect = *value.Gradient
  27. case value.Pattern != nil:
  28. s.Effect = *value.Pattern
  29. case value.Random != nil:
  30. s.Effect = *value.Random
  31. default:
  32. return errors.New("unsupported effect")
  33. }
  34. return nil
  35. }
  36. func (s *Serializable) MarshalJSON() ([]byte, error) {
  37. switch effect := s.Effect.(type) {
  38. case Manual:
  39. return json.Marshal(serializedEffect{Manual: &effect})
  40. case Gradient:
  41. return json.Marshal(serializedEffect{Gradient: &effect})
  42. case Pattern:
  43. return json.Marshal(serializedEffect{Pattern: &effect})
  44. case Random:
  45. return json.Marshal(serializedEffect{Random: &effect})
  46. default:
  47. panic(s.Effect.EffectDescription() + "is not understood by serializer")
  48. }
  49. }