encode encodes the given value to the writer and panics on error. depth holds the depth of the container nesting.
(v reflect.Value, depth int)
| 80 | // encode encodes the given value to the writer and panics on error. depth holds |
| 81 | // the depth of the container nesting. |
| 82 | func (enc *encoder) encode(v reflect.Value, depth int) { |
| 83 | if depth > 64 { |
| 84 | panic(FormatError("input exceeds depth limitation")) |
| 85 | } |
| 86 | enc.align(alignment(v.Type())) |
| 87 | switch v.Kind() { |
| 88 | case reflect.Uint8: |
| 89 | var b [1]byte |
| 90 | b[0] = byte(v.Uint()) |
| 91 | if _, err := enc.out.Write(b[:]); err != nil { |
| 92 | panic(err) |
| 93 | } |
| 94 | enc.pos++ |
| 95 | case reflect.Bool: |
| 96 | if v.Bool() { |
| 97 | enc.encode(reflect.ValueOf(uint32(1)), depth) |
| 98 | } else { |
| 99 | enc.encode(reflect.ValueOf(uint32(0)), depth) |
| 100 | } |
| 101 | case reflect.Int16: |
| 102 | enc.binwrite(int16(v.Int())) |
| 103 | enc.pos += 2 |
| 104 | case reflect.Uint16: |
| 105 | enc.binwrite(uint16(v.Uint())) |
| 106 | enc.pos += 2 |
| 107 | case reflect.Int, reflect.Int32: |
| 108 | if v.Type() == unixFDType { |
| 109 | fd := v.Int() |
| 110 | idx := len(enc.fds) |
| 111 | enc.fds = append(enc.fds, int(fd)) |
| 112 | enc.binwrite(uint32(idx)) |
| 113 | } else { |
| 114 | enc.binwrite(int32(v.Int())) |
| 115 | } |
| 116 | enc.pos += 4 |
| 117 | case reflect.Uint, reflect.Uint32: |
| 118 | enc.binwrite(uint32(v.Uint())) |
| 119 | enc.pos += 4 |
| 120 | case reflect.Int64: |
| 121 | enc.binwrite(v.Int()) |
| 122 | enc.pos += 8 |
| 123 | case reflect.Uint64: |
| 124 | enc.binwrite(v.Uint()) |
| 125 | enc.pos += 8 |
| 126 | case reflect.Float64: |
| 127 | enc.binwrite(v.Float()) |
| 128 | enc.pos += 8 |
| 129 | case reflect.String: |
| 130 | str := v.String() |
| 131 | if !utf8.ValidString(str) { |
| 132 | panic(FormatError("input has a not-utf8 char in string")) |
| 133 | } |
| 134 | if strings.IndexByte(str, byte(0)) != -1 { |
| 135 | panic(FormatError("input has a null char('\\000') in string")) |
| 136 | } |
| 137 | if v.Type() == objectPathType { |
| 138 | if !ObjectPath(str).IsValid() { |
| 139 | panic(FormatError("invalid object path")) |
no test coverage detected