src

Go monorepo.
git clone git://code.dwrz.net/src
Log | Files | Refs

encoder.go (1382B)


      1 package xml
      2 
      3 // writer interface used by the xml encoder to write an encoded xml
      4 // document in a writer.
      5 type writer interface {
      6 
      7 	// Write takes in a byte slice and returns number of bytes written and error
      8 	Write(p []byte) (n int, err error)
      9 
     10 	// WriteRune takes in a rune and returns number of bytes written and error
     11 	WriteRune(r rune) (n int, err error)
     12 
     13 	// WriteString takes in a string and returns number of bytes written and error
     14 	WriteString(s string) (n int, err error)
     15 
     16 	// String method returns a string
     17 	String() string
     18 
     19 	// Bytes return a byte slice.
     20 	Bytes() []byte
     21 }
     22 
     23 // Encoder is an XML encoder that supports construction of XML values
     24 // using methods. The encoder takes in a writer and maintains a scratch buffer.
     25 type Encoder struct {
     26 	w       writer
     27 	scratch *[]byte
     28 }
     29 
     30 // NewEncoder returns an XML encoder
     31 func NewEncoder(w writer) *Encoder {
     32 	scratch := make([]byte, 64)
     33 
     34 	return &Encoder{w: w, scratch: &scratch}
     35 }
     36 
     37 // String returns the string output of the XML encoder
     38 func (e Encoder) String() string {
     39 	return e.w.String()
     40 }
     41 
     42 // Bytes returns the []byte slice of the XML encoder
     43 func (e Encoder) Bytes() []byte {
     44 	return e.w.Bytes()
     45 }
     46 
     47 // RootElement builds a root element encoding
     48 // It writes it's start element tag. The value should be closed.
     49 func (e Encoder) RootElement(element StartElement) Value {
     50 	return newValue(e.w, e.scratch, element)
     51 }