raw.go raw

   1  package easyjson
   2  
   3  import (
   4  	"github.com/mailru/easyjson/jlexer"
   5  	"github.com/mailru/easyjson/jwriter"
   6  )
   7  
   8  // RawMessage is a raw piece of JSON (number, string, bool, object, array or
   9  // null) that is extracted without parsing and output as is during marshaling.
  10  type RawMessage []byte
  11  
  12  // MarshalEasyJSON does JSON marshaling using easyjson interface.
  13  func (v *RawMessage) MarshalEasyJSON(w *jwriter.Writer) {
  14  	if len(*v) == 0 {
  15  		w.RawString("null")
  16  	} else {
  17  		w.Raw(*v, nil)
  18  	}
  19  }
  20  
  21  // UnmarshalEasyJSON does JSON unmarshaling using easyjson interface.
  22  func (v *RawMessage) UnmarshalEasyJSON(l *jlexer.Lexer) {
  23  	*v = RawMessage(l.Raw())
  24  }
  25  
  26  // UnmarshalJSON implements encoding/json.Unmarshaler interface.
  27  func (v *RawMessage) UnmarshalJSON(data []byte) error {
  28  	*v = make([]byte, len(data))
  29  	copy(*v, data)
  30  	return nil
  31  }
  32  
  33  var nullBytes = []byte("null")
  34  
  35  // MarshalJSON implements encoding/json.Marshaler interface.
  36  func (v RawMessage) MarshalJSON() ([]byte, error) {
  37  	if len(v) == 0 {
  38  		return nullBytes, nil
  39  	}
  40  	return v, nil
  41  }
  42  
  43  // IsDefined is required for integration with omitempty easyjson logic.
  44  func (v *RawMessage) IsDefined() bool {
  45  	return len(*v) > 0
  46  }
  47