binary.go 11.1 KB
Newer Older
1 2 3 4
// Copyright 2009 The Go Authors.  All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

5 6 7
// Package binary implements translation between
// unsigned integer values and byte sequences
// and the reading and writing of fixed-size values.
8 9 10 11 12 13 14 15 16 17 18 19
package binary

import (
	"math"
	"io"
	"os"
	"reflect"
)

// A ByteOrder specifies how to convert byte sequences into
// 16-, 32-, or 64-bit unsigned integers.
type ByteOrder interface {
20 21 22
	Uint16([]byte) uint16
	Uint32([]byte) uint32
	Uint64([]byte) uint64
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
	PutUint16([]byte, uint16)
	PutUint32([]byte, uint32)
	PutUint64([]byte, uint64)
	String() string
}

// This is byte instead of struct{} so that it can be compared,
// allowing, e.g., order == binary.LittleEndian.
type unused byte

// LittleEndian is the little-endian implementation of ByteOrder.
var LittleEndian littleEndian

// BigEndian is the big-endian implementation of ByteOrder.
var BigEndian bigEndian

type littleEndian unused

func (littleEndian) Uint16(b []byte) uint16 { return uint16(b[0]) | uint16(b[1])<<8 }

func (littleEndian) PutUint16(b []byte, v uint16) {
	b[0] = byte(v)
	b[1] = byte(v >> 8)
}

func (littleEndian) Uint32(b []byte) uint32 {
	return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24
}

func (littleEndian) PutUint32(b []byte, v uint32) {
	b[0] = byte(v)
	b[1] = byte(v >> 8)
	b[2] = byte(v >> 16)
	b[3] = byte(v >> 24)
}

func (littleEndian) Uint64(b []byte) uint64 {
	return uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 |
		uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56
}

func (littleEndian) PutUint64(b []byte, v uint64) {
	b[0] = byte(v)
	b[1] = byte(v >> 8)
	b[2] = byte(v >> 16)
	b[3] = byte(v >> 24)
	b[4] = byte(v >> 32)
	b[5] = byte(v >> 40)
	b[6] = byte(v >> 48)
	b[7] = byte(v >> 56)
}

func (littleEndian) String() string { return "LittleEndian" }

func (littleEndian) GoString() string { return "binary.LittleEndian" }

type bigEndian unused

func (bigEndian) Uint16(b []byte) uint16 { return uint16(b[1]) | uint16(b[0])<<8 }

func (bigEndian) PutUint16(b []byte, v uint16) {
	b[0] = byte(v >> 8)
	b[1] = byte(v)
}

func (bigEndian) Uint32(b []byte) uint32 {
	return uint32(b[3]) | uint32(b[2])<<8 | uint32(b[1])<<16 | uint32(b[0])<<24
}

func (bigEndian) PutUint32(b []byte, v uint32) {
	b[0] = byte(v >> 24)
	b[1] = byte(v >> 16)
	b[2] = byte(v >> 8)
	b[3] = byte(v)
}

func (bigEndian) Uint64(b []byte) uint64 {
	return uint64(b[7]) | uint64(b[6])<<8 | uint64(b[5])<<16 | uint64(b[4])<<24 |
		uint64(b[3])<<32 | uint64(b[2])<<40 | uint64(b[1])<<48 | uint64(b[0])<<56
}

func (bigEndian) PutUint64(b []byte, v uint64) {
	b[0] = byte(v >> 56)
	b[1] = byte(v >> 48)
	b[2] = byte(v >> 40)
	b[3] = byte(v >> 32)
	b[4] = byte(v >> 24)
	b[5] = byte(v >> 16)
	b[6] = byte(v >> 8)
	b[7] = byte(v)
}

func (bigEndian) String() string { return "BigEndian" }

func (bigEndian) GoString() string { return "binary.BigEndian" }

// Read reads structured binary data from r into data.
// Data must be a pointer to a fixed-size value or a slice
// of fixed-size values.
// A fixed-size value is either a fixed-size arithmetic
// type (int8, uint8, int16, float32, complex64, ...)
// or an array or struct containing only fixed-size values.
// Bytes read from r are decoded using the specified byte order
// and written to successive fields of the data.
func Read(r io.Reader, order ByteOrder, data interface{}) os.Error {
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
	// Fast path for basic types.
	if n := intDestSize(data); n != 0 {
		var b [8]byte
		bs := b[:n]
		if _, err := io.ReadFull(r, bs); err != nil {
			return err
		}
		switch v := data.(type) {
		case *int8:
			*v = int8(b[0])
		case *uint8:
			*v = b[0]
		case *int16:
			*v = int16(order.Uint16(bs))
		case *uint16:
			*v = order.Uint16(bs)
		case *int32:
			*v = int32(order.Uint32(bs))
		case *uint32:
			*v = order.Uint32(bs)
		case *int64:
			*v = int64(order.Uint64(bs))
		case *uint64:
			*v = order.Uint64(bs)
		}
		return nil
	}

	// Fallback to reflect-based.
157
	var v reflect.Value
158 159
	switch d := reflect.ValueOf(data); d.Kind() {
	case reflect.Ptr:
160
		v = d.Elem()
161
	case reflect.Slice:
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
		v = d
	default:
		return os.NewError("binary.Read: invalid type " + d.Type().String())
	}
	size := TotalSize(v)
	if size < 0 {
		return os.NewError("binary.Read: invalid type " + v.Type().String())
	}
	d := &decoder{order: order, buf: make([]byte, size)}
	if _, err := io.ReadFull(r, d.buf); err != nil {
		return err
	}
	d.value(v)
	return nil
}

// Write writes the binary representation of data into w.
// Data must be a fixed-size value or a pointer to
// a fixed-size value.
// A fixed-size value is either a fixed-size arithmetic
// type (int8, uint8, int16, float32, complex64, ...)
// or an array or struct containing only fixed-size values.
// Bytes written to w are encoded using the specified byte order
// and read from successive fields of the data.
func Write(w io.Writer, order ByteOrder, data interface{}) os.Error {
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
	// Fast path for basic types.
	var b [8]byte
	var bs []byte
	switch v := data.(type) {
	case *int8:
		bs = b[:1]
		b[0] = byte(*v)
	case int8:
		bs = b[:1]
		b[0] = byte(v)
	case *uint8:
		bs = b[:1]
		b[0] = *v
	case uint8:
		bs = b[:1]
		b[0] = byte(v)
	case *int16:
		bs = b[:2]
		order.PutUint16(bs, uint16(*v))
	case int16:
		bs = b[:2]
		order.PutUint16(bs, uint16(v))
	case *uint16:
		bs = b[:2]
		order.PutUint16(bs, *v)
	case uint16:
		bs = b[:2]
		order.PutUint16(bs, v)
	case *int32:
		bs = b[:4]
		order.PutUint32(bs, uint32(*v))
	case int32:
		bs = b[:4]
		order.PutUint32(bs, uint32(v))
	case *uint32:
		bs = b[:4]
		order.PutUint32(bs, *v)
	case uint32:
		bs = b[:4]
		order.PutUint32(bs, v)
	case *int64:
		bs = b[:8]
		order.PutUint64(bs, uint64(*v))
	case int64:
		bs = b[:8]
		order.PutUint64(bs, uint64(v))
	case *uint64:
		bs = b[:8]
		order.PutUint64(bs, *v)
	case uint64:
		bs = b[:8]
		order.PutUint64(bs, v)
	}
	if bs != nil {
		_, err := w.Write(bs)
		return err
	}
244
	v := reflect.Indirect(reflect.ValueOf(data))
245 246 247 248 249 250 251 252 253 254 255 256
	size := TotalSize(v)
	if size < 0 {
		return os.NewError("binary.Write: invalid type " + v.Type().String())
	}
	buf := make([]byte, size)
	e := &encoder{order: order, buf: buf}
	e.value(v)
	_, err := w.Write(buf)
	return err
}

func TotalSize(v reflect.Value) int {
257 258
	if v.Kind() == reflect.Slice {
		elem := sizeof(v.Type().Elem())
259 260 261
		if elem < 0 {
			return -1
		}
262
		return v.Len() * elem
263 264 265 266
	}
	return sizeof(v.Type())
}

267 268 269
func sizeof(t reflect.Type) int {
	switch t.Kind() {
	case reflect.Array:
270 271 272 273 274 275
		n := sizeof(t.Elem())
		if n < 0 {
			return -1
		}
		return t.Len() * n

276
	case reflect.Struct:
277 278 279 280 281 282 283 284 285 286
		sum := 0
		for i, n := 0, t.NumField(); i < n; i++ {
			s := sizeof(t.Field(i).Type)
			if s < 0 {
				return -1
			}
			sum += s
		}
		return sum

287 288 289 290
	case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
		reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
		reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128:
		return int(t.Size())
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 365
	}
	return -1
}

type decoder struct {
	order ByteOrder
	buf   []byte
}

type encoder struct {
	order ByteOrder
	buf   []byte
}

func (d *decoder) uint8() uint8 {
	x := d.buf[0]
	d.buf = d.buf[1:]
	return x
}

func (e *encoder) uint8(x uint8) {
	e.buf[0] = x
	e.buf = e.buf[1:]
}

func (d *decoder) uint16() uint16 {
	x := d.order.Uint16(d.buf[0:2])
	d.buf = d.buf[2:]
	return x
}

func (e *encoder) uint16(x uint16) {
	e.order.PutUint16(e.buf[0:2], x)
	e.buf = e.buf[2:]
}

func (d *decoder) uint32() uint32 {
	x := d.order.Uint32(d.buf[0:4])
	d.buf = d.buf[4:]
	return x
}

func (e *encoder) uint32(x uint32) {
	e.order.PutUint32(e.buf[0:4], x)
	e.buf = e.buf[4:]
}

func (d *decoder) uint64() uint64 {
	x := d.order.Uint64(d.buf[0:8])
	d.buf = d.buf[8:]
	return x
}

func (e *encoder) uint64(x uint64) {
	e.order.PutUint64(e.buf[0:8], x)
	e.buf = e.buf[8:]
}

func (d *decoder) int8() int8 { return int8(d.uint8()) }

func (e *encoder) int8(x int8) { e.uint8(uint8(x)) }

func (d *decoder) int16() int16 { return int16(d.uint16()) }

func (e *encoder) int16(x int16) { e.uint16(uint16(x)) }

func (d *decoder) int32() int32 { return int32(d.uint32()) }

func (e *encoder) int32(x int32) { e.uint32(uint32(x)) }

func (d *decoder) int64() int64 { return int64(d.uint64()) }

func (e *encoder) int64(x int64) { e.uint64(uint64(x)) }

func (d *decoder) value(v reflect.Value) {
366 367
	switch v.Kind() {
	case reflect.Array:
368 369
		l := v.Len()
		for i := 0; i < l; i++ {
370
			d.value(v.Index(i))
371
		}
372
	case reflect.Struct:
373 374 375 376 377
		l := v.NumField()
		for i := 0; i < l; i++ {
			d.value(v.Field(i))
		}

378
	case reflect.Slice:
379 380
		l := v.Len()
		for i := 0; i < l; i++ {
381
			d.value(v.Index(i))
382 383
		}

384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
	case reflect.Int8:
		v.SetInt(int64(d.int8()))
	case reflect.Int16:
		v.SetInt(int64(d.int16()))
	case reflect.Int32:
		v.SetInt(int64(d.int32()))
	case reflect.Int64:
		v.SetInt(d.int64())

	case reflect.Uint8:
		v.SetUint(uint64(d.uint8()))
	case reflect.Uint16:
		v.SetUint(uint64(d.uint16()))
	case reflect.Uint32:
		v.SetUint(uint64(d.uint32()))
	case reflect.Uint64:
		v.SetUint(d.uint64())

	case reflect.Float32:
		v.SetFloat(float64(math.Float32frombits(d.uint32())))
	case reflect.Float64:
		v.SetFloat(math.Float64frombits(d.uint64()))

	case reflect.Complex64:
		v.SetComplex(complex(
			float64(math.Float32frombits(d.uint32())),
			float64(math.Float32frombits(d.uint32())),
		))
	case reflect.Complex128:
		v.SetComplex(complex(
			math.Float64frombits(d.uint64()),
			math.Float64frombits(d.uint64()),
		))
417 418 419 420
	}
}

func (e *encoder) value(v reflect.Value) {
421 422
	switch v.Kind() {
	case reflect.Array:
423 424
		l := v.Len()
		for i := 0; i < l; i++ {
425
			e.value(v.Index(i))
426
		}
427
	case reflect.Struct:
428 429 430 431
		l := v.NumField()
		for i := 0; i < l; i++ {
			e.value(v.Field(i))
		}
432
	case reflect.Slice:
433 434
		l := v.Len()
		for i := 0; i < l; i++ {
435
			e.value(v.Index(i))
436 437
		}

438
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
439 440
		switch v.Type().Kind() {
		case reflect.Int8:
441
			e.int8(int8(v.Int()))
442
		case reflect.Int16:
443
			e.int16(int16(v.Int()))
444
		case reflect.Int32:
445
			e.int32(int32(v.Int()))
446
		case reflect.Int64:
447
			e.int64(v.Int())
448 449
		}

450
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
451 452
		switch v.Type().Kind() {
		case reflect.Uint8:
453
			e.uint8(uint8(v.Uint()))
454
		case reflect.Uint16:
455
			e.uint16(uint16(v.Uint()))
456
		case reflect.Uint32:
457
			e.uint32(uint32(v.Uint()))
458
		case reflect.Uint64:
459
			e.uint64(v.Uint())
460 461
		}

462
	case reflect.Float32, reflect.Float64:
463 464
		switch v.Type().Kind() {
		case reflect.Float32:
465
			e.uint32(math.Float32bits(float32(v.Float())))
466
		case reflect.Float64:
467
			e.uint64(math.Float64bits(v.Float()))
468 469
		}

470
	case reflect.Complex64, reflect.Complex128:
471 472
		switch v.Type().Kind() {
		case reflect.Complex64:
473
			x := v.Complex()
474 475 476
			e.uint32(math.Float32bits(float32(real(x))))
			e.uint32(math.Float32bits(float32(imag(x))))
		case reflect.Complex128:
477
			x := v.Complex()
478 479 480 481 482
			e.uint64(math.Float64bits(real(x)))
			e.uint64(math.Float64bits(imag(x)))
		}
	}
}
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498

// intDestSize returns the size of the integer that ptrType points to,
// or 0 if the type is not supported.
func intDestSize(ptrType interface{}) int {
	switch ptrType.(type) {
	case *int8, *uint8:
		return 1
	case *int16, *uint16:
		return 2
	case *int32, *uint32:
		return 4
	case *int64, *uint64:
		return 8
	}
	return 0
}