cell.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package xvdoc
  2. import (
  3. "encoding/json"
  4. )
  5. type Cell interface {
  6. Val() interface{}
  7. Type() string
  8. Styles() []string
  9. }
  10. type CellConstructor func(*json.Decoder, json.Token) (Cell, error)
  11. var (
  12. cellConstructors []CellConstructor
  13. )
  14. func AppendCellConstructor(constructor CellConstructor) {
  15. cellConstructors = append(cellConstructors, constructor)
  16. }
  17. func init() {
  18. cellConstructors = []CellConstructor{
  19. constructorString,
  20. constructorNumber,
  21. constructorObject,
  22. }
  23. }
  24. func parseCell(dec *json.Decoder, t json.Token) (cell Cell, err error) {
  25. for _, constructor := range cellConstructors {
  26. if cell, err = constructor(dec, t); cell != nil || err != nil {
  27. return
  28. }
  29. }
  30. return
  31. }
  32. func parseCells(dec *json.Decoder) (res []Cell, err error) {
  33. var (
  34. t json.Token
  35. cell Cell
  36. )
  37. if t, err = dec.Token(); err == nil {
  38. if _, check := t.(json.Delim); check && t == json.Delim('[') {
  39. for err == nil {
  40. if t, err = dec.Token(); err == nil {
  41. if _, check := t.(json.Delim); check && t == json.Delim(']') {
  42. return
  43. }
  44. }
  45. if cell, err = parseCell(dec, t); err == nil && cell != nil {
  46. res = append(res, cell)
  47. }
  48. }
  49. } else {
  50. if cell, err = parseCell(dec, t); err == nil && cell != nil {
  51. res = []Cell{cell}
  52. }
  53. }
  54. }
  55. return
  56. }