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.
 
 
 

58 lines
1.7 KiB

  1. // Copyright 2016 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package gensupport
  15. import (
  16. "encoding/json"
  17. "errors"
  18. "fmt"
  19. "math"
  20. )
  21. // JSONFloat64 is a float64 that supports proper unmarshaling of special float
  22. // values in JSON, according to
  23. // https://developers.google.com/protocol-buffers/docs/proto3#json. Although
  24. // that is a proto-to-JSON spec, it applies to all Google APIs.
  25. //
  26. // The jsonpb package
  27. // (https://github.com/golang/protobuf/blob/master/jsonpb/jsonpb.go) has
  28. // similar functionality, but only for direct translation from proto messages
  29. // to JSON.
  30. type JSONFloat64 float64
  31. func (f *JSONFloat64) UnmarshalJSON(data []byte) error {
  32. var ff float64
  33. if err := json.Unmarshal(data, &ff); err == nil {
  34. *f = JSONFloat64(ff)
  35. return nil
  36. }
  37. var s string
  38. if err := json.Unmarshal(data, &s); err == nil {
  39. switch s {
  40. case "NaN":
  41. ff = math.NaN()
  42. case "Infinity":
  43. ff = math.Inf(1)
  44. case "-Infinity":
  45. ff = math.Inf(-1)
  46. default:
  47. return fmt.Errorf("google.golang.org/api/internal: bad float string %q", s)
  48. }
  49. *f = JSONFloat64(ff)
  50. return nil
  51. }
  52. return errors.New("google.golang.org/api/internal: data not float or string")
  53. }