encoder.go 7.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
package restruct

import (
	"encoding/binary"
	"fmt"
	"math"
	"reflect"
)

// Packer is a type capable of packing a native value into a binary
// representation. The Pack function is expected to overwrite a number of
// bytes in buf then return a slice of the remaining buffer. Note that you
// must also implement SizeOf, and returning an incorrect SizeOf will cause
// the encoder to crash. The SizeOf should be equal to the number of bytes
// consumed from the buffer slice in Pack. You may use a pointer receiver even
// if the type is used by value.
type Packer interface {
	Sizer
	Pack(buf []byte, order binary.ByteOrder) ([]byte, error)
}

type encoder struct {
	structstack
	order      binary.ByteOrder
	sfields    []field
	bitCounter int
	bitSize    int
}

func getBit(buf []byte, bitSize int, bit int) byte {
	bit = bitSize - 1 - bit
	return (buf[len(buf)-bit/8-1] >> (uint(bit) % 8)) & 1
}

func (e *encoder) writeBit(value byte) {
	e.buf[0] |= (value & 1) << uint(7-e.bitCounter)
	e.bitCounter++
	if e.bitCounter >= 8 {
		e.buf = e.buf[1:]
		e.bitCounter -= 8
	}
}

func (e *encoder) writeBits(f field, inBuf []byte) {
	var encodedBits int

	// Determine encoded size in bits.
	if e.bitSize == 0 {
		encodedBits = 8 * len(inBuf)
	} else {
		encodedBits = int(e.bitSize)
	}

	// Crop input buffer to relevant bytes only.
	inBuf = inBuf[len(inBuf)-(encodedBits+7)/8:]

	if e.bitCounter == 0 && encodedBits%8 == 0 {
		// Fast path: we are fully byte-aligned.
		copy(e.buf, inBuf)
		e.buf = e.buf[len(inBuf):]
	} else {
		// Slow path: work bit-by-bit.
		// TODO: This needs to be optimized in a way that can be easily
		// understood; the previous optimized version was simply too hard to
		// reason about.
		for i := 0; i < encodedBits; i++ {
			e.writeBit(getBit(inBuf, encodedBits, i))
		}
	}
}

func (e *encoder) write8(f field, x uint8) {
	b := make([]byte, 1)
	b[0] = x
	e.writeBits(f, b)
}

func (e *encoder) write16(f field, x uint16) {
	b := make([]byte, 2)
	e.order.PutUint16(b, x)
	e.writeBits(f, b)
}

func (e *encoder) write32(f field, x uint32) {
	b := make([]byte, 4)
	e.order.PutUint32(b, x)
	e.writeBits(f, b)
}

func (e *encoder) write64(f field, x uint64) {
	b := make([]byte, 8)
	e.order.PutUint64(b, x)
	e.writeBits(f, b)
}

func (e *encoder) writeS8(f field, x int8) { e.write8(f, uint8(x)) }

func (e *encoder) writeS16(f field, x int16) { e.write16(f, uint16(x)) }

func (e *encoder) writeS32(f field, x int32) { e.write32(f, uint32(x)) }

func (e *encoder) writeS64(f field, x int64) { e.write64(f, uint64(x)) }

func (e *encoder) skipBits(count int) {
	e.bitCounter += count % 8
	if e.bitCounter > 8 {
		e.bitCounter -= 8
		count += 8
	}
	e.buf = e.buf[count/8:]
}

func (e *encoder) skip(f field, v reflect.Value) {
	e.skipBits(e.fieldbits(f, v))
}

func (e *encoder) packer(v reflect.Value) (Packer, bool) {
	if s, ok := v.Interface().(Packer); ok {
		return s, true
	}

	if !v.CanAddr() {
		return nil, false
	}

	if s, ok := v.Addr().Interface().(Packer); ok {
		return s, true
	}

	return nil, false
}

func (e *encoder) intFromField(f field, v reflect.Value) int64 {
	switch v.Kind() {
	case reflect.Bool:
		b := v.Bool()
		if f.Flags&InvertedBoolFlag == InvertedBoolFlag {
			b = !b
		}
		if b {
			if f.Flags&VariantBoolFlag == VariantBoolFlag {
				return -1
			}
			return 1
		}
		return 0
	default:
		return v.Int()
	}
}

func (e *encoder) uintFromField(f field, v reflect.Value) uint64 {
	switch v.Kind() {
	case reflect.Bool:
		b := v.Bool()
		if f.Flags&InvertedBoolFlag == InvertedBoolFlag {
			b = !b
		}
		if b {
			if f.Flags&VariantBoolFlag == VariantBoolFlag {
				return ^uint64(0)
			}
			return 1
		}
		return 0
	default:
		return v.Uint()
	}
}

func (e *encoder) switc(f field, v reflect.Value, on interface{}) {
	var def *switchcase

	if v.Kind() != reflect.Struct {
		panic(fmt.Errorf("%s: only switches on structs are valid", f.Name))
	}

	sfields := cachedFieldsFromStruct(f.BinaryType)
	l := len(sfields)

	for i := 0; i < l; i++ {
		f := sfields[i]
		v := v.Field(f.Index)

		if f.Flags&DefaultFlag != 0 {
			if def != nil {
				panic(fmt.Errorf("%s: only one default case is allowed", f.Name))
			}
			def = &switchcase{f, v}
			continue
		}

		if f.CaseExpr == nil {
			panic(fmt.Errorf("%s: only cases are valid inside switches", f.Name))
		}

		if e.evalExpr(f.CaseExpr) == on {
			e.write(f, v)
			return
		}
	}

	if def != nil {
		e.write(def.f, def.v)
	}
}

func (e *encoder) write(f field, v reflect.Value) {
	if f.Flags&RootFlag == RootFlag {
		e.setancestor(f, v, e.root())
		return
	}

	if f.Flags&ParentFlag == ParentFlag {
		for i := 1; i < len(e.stack); i++ {
			if e.setancestor(f, v, e.ancestor(i)) {
				break
			}
		}
		return
	}

	if f.SwitchExpr != nil {
		e.switc(f, v, e.evalExpr(f.SwitchExpr))
		return
	}

	struc := e.ancestor(0)

	if f.Name != "_" {
		if s, ok := e.packer(v); ok {
			var err error
			e.buf, err = s.Pack(e.buf, e.order)
			if err != nil {
				panic(err)
			}
			return
		}
	} else {
		e.skipBits(e.fieldbits(f, v))
		return
	}

	if !e.evalIf(f) {
		return
	}

	sfields := e.sfields
	order := e.order

	if f.Order != nil {
		e.order = f.Order
		defer func() { e.order = order }()
	}

	if f.Skip != 0 {
		e.skipBits(f.Skip * 8)
	}

	e.bitSize = e.evalBits(f)

	// If this is a sizeof field, pull the current slice length into it.
	if f.TIndex != -1 {
		sv := struc.Field(f.TIndex)

		switch f.BinaryType.Kind() {
		case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
			v.SetInt(int64(sv.Len()))
		case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
			v.SetUint(uint64(sv.Len()))
		default:
			panic(fmt.Errorf("unsupported size type %s: %s", f.BinaryType.String(), f.Name))
		}
	}

	ov := v
	if f.OutExpr != nil {
		ov = reflect.ValueOf(e.evalExpr(f.OutExpr))
	}

	switch f.BinaryType.Kind() {
	case reflect.Ptr:
		// Skip if pointer is nil.
		if v.IsNil() {
			return
		}

		e.write(f.Elem(), v.Elem())

	case reflect.Array, reflect.Slice, reflect.String:
		switch f.NativeType.Kind() {
		case reflect.Slice, reflect.String:
			if f.SizeExpr != nil {
				if l := e.evalSize(f); l != ov.Len() {
					panic(fmt.Errorf("length does not match size expression (%d != %d)", ov.Len(), l))
				}
			}
			fallthrough
		case reflect.Array:
			ef := f.Elem()
			len := ov.Len()
			cap := len
			if f.BinaryType.Kind() == reflect.Array {
				cap = f.BinaryType.Len()
			}
			for i := 0; i < len; i++ {
				e.write(ef, ov.Index(i))
			}
			for i := len; i < cap; i++ {
				e.write(ef, reflect.New(f.BinaryType.Elem()).Elem())
			}
		default:
			panic(fmt.Errorf("invalid array cast type: %s", f.NativeType.String()))
		}

	case reflect.Struct:
		e.push(ov)
		e.sfields = cachedFieldsFromStruct(f.BinaryType)
		l := len(e.sfields)
		for i := 0; i < l; i++ {
			sf := e.sfields[i]
			sv := ov.Field(sf.Index)
			if sv.CanSet() {
				e.write(sf, sv)
			} else {
				e.skip(sf, sv)
			}
		}
		e.sfields = sfields
		e.pop(ov)

	case reflect.Int8:
		e.writeS8(f, int8(e.intFromField(f, ov)))
	case reflect.Int16:
		e.writeS16(f, int16(e.intFromField(f, ov)))
	case reflect.Int32:
		e.writeS32(f, int32(e.intFromField(f, ov)))
	case reflect.Int64:
		e.writeS64(f, int64(e.intFromField(f, ov)))

	case reflect.Uint8, reflect.Bool:
		e.write8(f, uint8(e.uintFromField(f, ov)))
	case reflect.Uint16:
		e.write16(f, uint16(e.uintFromField(f, ov)))
	case reflect.Uint32:
		e.write32(f, uint32(e.uintFromField(f, ov)))
	case reflect.Uint64:
		e.write64(f, uint64(e.uintFromField(f, ov)))

	case reflect.Float32:
		e.write32(f, math.Float32bits(float32(ov.Float())))
	case reflect.Float64:
		e.write64(f, math.Float64bits(float64(ov.Float())))

	case reflect.Complex64:
		x := ov.Complex()
		e.write32(f, math.Float32bits(float32(real(x))))
		e.write32(f, math.Float32bits(float32(imag(x))))
	case reflect.Complex128:
		x := ov.Complex()
		e.write64(f, math.Float64bits(float64(real(x))))
		e.write64(f, math.Float64bits(float64(imag(x))))
	}
}