The Go Programming Language

Source file src/pkg/encoding/binary/binary.go

     1	// Copyright 2009 The Go Authors.  All rights reserved.
     2	// Use of this source code is governed by a BSD-style
     3	// license that can be found in the LICENSE file.
     4	
     5	// Package binary implements translation between
     6	// unsigned integer values and byte sequences
     7	// and the reading and writing of fixed-size values.
     8	package binary
     9	
    10	import (
    11		"math"
    12		"io"
    13		"os"
    14		"reflect"
    15	)
    16	
    17	// A ByteOrder specifies how to convert byte sequences into
    18	// 16-, 32-, or 64-bit unsigned integers.
    19	type ByteOrder interface {
    20		Uint16(b []byte) uint16
    21		Uint32(b []byte) uint32
    22		Uint64(b []byte) uint64
    23		PutUint16([]byte, uint16)
    24		PutUint32([]byte, uint32)
    25		PutUint64([]byte, uint64)
    26		String() string
    27	}
    28	
    29	// This is byte instead of struct{} so that it can be compared,
    30	// allowing, e.g., order == binary.LittleEndian.
    31	type unused byte
    32	
    33	// LittleEndian is the little-endian implementation of ByteOrder.
    34	var LittleEndian littleEndian
    35	
    36	// BigEndian is the big-endian implementation of ByteOrder.
    37	var BigEndian bigEndian
    38	
    39	type littleEndian unused
    40	
    41	func (littleEndian) Uint16(b []byte) uint16 { return uint16(b[0]) | uint16(b[1])<<8 }
    42	
    43	func (littleEndian) PutUint16(b []byte, v uint16) {
    44		b[0] = byte(v)
    45		b[1] = byte(v >> 8)
    46	}
    47	
    48	func (littleEndian) Uint32(b []byte) uint32 {
    49		return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24
    50	}
    51	
    52	func (littleEndian) PutUint32(b []byte, v uint32) {
    53		b[0] = byte(v)
    54		b[1] = byte(v >> 8)
    55		b[2] = byte(v >> 16)
    56		b[3] = byte(v >> 24)
    57	}
    58	
    59	func (littleEndian) Uint64(b []byte) uint64 {
    60		return uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 |
    61			uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56
    62	}
    63	
    64	func (littleEndian) PutUint64(b []byte, v uint64) {
    65		b[0] = byte(v)
    66		b[1] = byte(v >> 8)
    67		b[2] = byte(v >> 16)
    68		b[3] = byte(v >> 24)
    69		b[4] = byte(v >> 32)
    70		b[5] = byte(v >> 40)
    71		b[6] = byte(v >> 48)
    72		b[7] = byte(v >> 56)
    73	}
    74	
    75	func (littleEndian) String() string { return "LittleEndian" }
    76	
    77	func (littleEndian) GoString() string { return "binary.LittleEndian" }
    78	
    79	type bigEndian unused
    80	
    81	func (bigEndian) Uint16(b []byte) uint16 { return uint16(b[1]) | uint16(b[0])<<8 }
    82	
    83	func (bigEndian) PutUint16(b []byte, v uint16) {
    84		b[0] = byte(v >> 8)
    85		b[1] = byte(v)
    86	}
    87	
    88	func (bigEndian) Uint32(b []byte) uint32 {
    89		return uint32(b[3]) | uint32(b[2])<<8 | uint32(b[1])<<16 | uint32(b[0])<<24
    90	}
    91	
    92	func (bigEndian) PutUint32(b []byte, v uint32) {
    93		b[0] = byte(v >> 24)
    94		b[1] = byte(v >> 16)
    95		b[2] = byte(v >> 8)
    96		b[3] = byte(v)
    97	}
    98	
    99	func (bigEndian) Uint64(b []byte) uint64 {
   100		return uint64(b[7]) | uint64(b[6])<<8 | uint64(b[5])<<16 | uint64(b[4])<<24 |
   101			uint64(b[3])<<32 | uint64(b[2])<<40 | uint64(b[1])<<48 | uint64(b[0])<<56
   102	}
   103	
   104	func (bigEndian) PutUint64(b []byte, v uint64) {
   105		b[0] = byte(v >> 56)
   106		b[1] = byte(v >> 48)
   107		b[2] = byte(v >> 40)
   108		b[3] = byte(v >> 32)
   109		b[4] = byte(v >> 24)
   110		b[5] = byte(v >> 16)
   111		b[6] = byte(v >> 8)
   112		b[7] = byte(v)
   113	}
   114	
   115	func (bigEndian) String() string { return "BigEndian" }
   116	
   117	func (bigEndian) GoString() string { return "binary.BigEndian" }
   118	
   119	// Read reads structured binary data from r into data.
   120	// Data must be a pointer to a fixed-size value or a slice
   121	// of fixed-size values.
   122	// A fixed-size value is either a fixed-size arithmetic
   123	// type (int8, uint8, int16, float32, complex64, ...)
   124	// or an array or struct containing only fixed-size values.
   125	// Bytes read from r are decoded using the specified byte order
   126	// and written to successive fields of the data.
   127	func Read(r io.Reader, order ByteOrder, data interface{}) os.Error {
   128		// Fast path for basic types.
   129		if n := intDestSize(data); n != 0 {
   130			var b [8]byte
   131			bs := b[:n]
   132			if _, err := io.ReadFull(r, bs); err != nil {
   133				return err
   134			}
   135			switch v := data.(type) {
   136			case *int8:
   137				*v = int8(b[0])
   138			case *uint8:
   139				*v = b[0]
   140			case *int16:
   141				*v = int16(order.Uint16(bs))
   142			case *uint16:
   143				*v = order.Uint16(bs)
   144			case *int32:
   145				*v = int32(order.Uint32(bs))
   146			case *uint32:
   147				*v = order.Uint32(bs)
   148			case *int64:
   149				*v = int64(order.Uint64(bs))
   150			case *uint64:
   151				*v = order.Uint64(bs)
   152			}
   153			return nil
   154		}
   155	
   156		// Fallback to reflect-based.
   157		var v reflect.Value
   158		switch d := reflect.ValueOf(data); d.Kind() {
   159		case reflect.Ptr:
   160			v = d.Elem()
   161		case reflect.Slice:
   162			v = d
   163		default:
   164			return os.NewError("binary.Read: invalid type " + d.Type().String())
   165		}
   166		size := TotalSize(v)
   167		if size < 0 {
   168			return os.NewError("binary.Read: invalid type " + v.Type().String())
   169		}
   170		d := &decoder{order: order, buf: make([]byte, size)}
   171		if _, err := io.ReadFull(r, d.buf); err != nil {
   172			return err
   173		}
   174		d.value(v)
   175		return nil
   176	}
   177	
   178	// Write writes the binary representation of data into w.
   179	// Data must be a fixed-size value or a pointer to
   180	// a fixed-size value.
   181	// A fixed-size value is either a fixed-size arithmetic
   182	// type (int8, uint8, int16, float32, complex64, ...)
   183	// or an array or struct containing only fixed-size values.
   184	// Bytes written to w are encoded using the specified byte order
   185	// and read from successive fields of the data.
   186	func Write(w io.Writer, order ByteOrder, data interface{}) os.Error {
   187		// Fast path for basic types.
   188		var b [8]byte
   189		var bs []byte
   190		switch v := data.(type) {
   191		case *int8:
   192			bs = b[:1]
   193			b[0] = byte(*v)
   194		case int8:
   195			bs = b[:1]
   196			b[0] = byte(v)
   197		case *uint8:
   198			bs = b[:1]
   199			b[0] = *v
   200		case uint8:
   201			bs = b[:1]
   202			b[0] = byte(v)
   203		case *int16:
   204			bs = b[:2]
   205			order.PutUint16(bs, uint16(*v))
   206		case int16:
   207			bs = b[:2]
   208			order.PutUint16(bs, uint16(v))
   209		case *uint16:
   210			bs = b[:2]
   211			order.PutUint16(bs, *v)
   212		case uint16:
   213			bs = b[:2]
   214			order.PutUint16(bs, v)
   215		case *int32:
   216			bs = b[:4]
   217			order.PutUint32(bs, uint32(*v))
   218		case int32:
   219			bs = b[:4]
   220			order.PutUint32(bs, uint32(v))
   221		case *uint32:
   222			bs = b[:4]
   223			order.PutUint32(bs, *v)
   224		case uint32:
   225			bs = b[:4]
   226			order.PutUint32(bs, v)
   227		case *int64:
   228			bs = b[:8]
   229			order.PutUint64(bs, uint64(*v))
   230		case int64:
   231			bs = b[:8]
   232			order.PutUint64(bs, uint64(v))
   233		case *uint64:
   234			bs = b[:8]
   235			order.PutUint64(bs, *v)
   236		case uint64:
   237			bs = b[:8]
   238			order.PutUint64(bs, v)
   239		}
   240		if bs != nil {
   241			_, err := w.Write(bs)
   242			return err
   243		}
   244		v := reflect.Indirect(reflect.ValueOf(data))
   245		size := TotalSize(v)
   246		if size < 0 {
   247			return os.NewError("binary.Write: invalid type " + v.Type().String())
   248		}
   249		buf := make([]byte, size)
   250		e := &encoder{order: order, buf: buf}
   251		e.value(v)
   252		_, err := w.Write(buf)
   253		return err
   254	}
   255	
   256	func TotalSize(v reflect.Value) int {
   257		if v.Kind() == reflect.Slice {
   258			elem := sizeof(v.Type().Elem())
   259			if elem < 0 {
   260				return -1
   261			}
   262			return v.Len() * elem
   263		}
   264		return sizeof(v.Type())
   265	}
   266	
   267	func sizeof(t reflect.Type) int {
   268		switch t.Kind() {
   269		case reflect.Array:
   270			n := sizeof(t.Elem())
   271			if n < 0 {
   272				return -1
   273			}
   274			return t.Len() * n
   275	
   276		case reflect.Struct:
   277			sum := 0
   278			for i, n := 0, t.NumField(); i < n; i++ {
   279				s := sizeof(t.Field(i).Type)
   280				if s < 0 {
   281					return -1
   282				}
   283				sum += s
   284			}
   285			return sum
   286	
   287		case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
   288			reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
   289			reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128:
   290			return int(t.Size())
   291		}
   292		return -1
   293	}
   294	
   295	type decoder struct {
   296		order ByteOrder
   297		buf   []byte
   298	}
   299	
   300	type encoder struct {
   301		order ByteOrder
   302		buf   []byte
   303	}
   304	
   305	func (d *decoder) uint8() uint8 {
   306		x := d.buf[0]
   307		d.buf = d.buf[1:]
   308		return x
   309	}
   310	
   311	func (e *encoder) uint8(x uint8) {
   312		e.buf[0] = x
   313		e.buf = e.buf[1:]
   314	}
   315	
   316	func (d *decoder) uint16() uint16 {
   317		x := d.order.Uint16(d.buf[0:2])
   318		d.buf = d.buf[2:]
   319		return x
   320	}
   321	
   322	func (e *encoder) uint16(x uint16) {
   323		e.order.PutUint16(e.buf[0:2], x)
   324		e.buf = e.buf[2:]
   325	}
   326	
   327	func (d *decoder) uint32() uint32 {
   328		x := d.order.Uint32(d.buf[0:4])
   329		d.buf = d.buf[4:]
   330		return x
   331	}
   332	
   333	func (e *encoder) uint32(x uint32) {
   334		e.order.PutUint32(e.buf[0:4], x)
   335		e.buf = e.buf[4:]
   336	}
   337	
   338	func (d *decoder) uint64() uint64 {
   339		x := d.order.Uint64(d.buf[0:8])
   340		d.buf = d.buf[8:]
   341		return x
   342	}
   343	
   344	func (e *encoder) uint64(x uint64) {
   345		e.order.PutUint64(e.buf[0:8], x)
   346		e.buf = e.buf[8:]
   347	}
   348	
   349	func (d *decoder) int8() int8 { return int8(d.uint8()) }
   350	
   351	func (e *encoder) int8(x int8) { e.uint8(uint8(x)) }
   352	
   353	func (d *decoder) int16() int16 { return int16(d.uint16()) }
   354	
   355	func (e *encoder) int16(x int16) { e.uint16(uint16(x)) }
   356	
   357	func (d *decoder) int32() int32 { return int32(d.uint32()) }
   358	
   359	func (e *encoder) int32(x int32) { e.uint32(uint32(x)) }
   360	
   361	func (d *decoder) int64() int64 { return int64(d.uint64()) }
   362	
   363	func (e *encoder) int64(x int64) { e.uint64(uint64(x)) }
   364	
   365	func (d *decoder) value(v reflect.Value) {
   366		switch v.Kind() {
   367		case reflect.Array:
   368			l := v.Len()
   369			for i := 0; i < l; i++ {
   370				d.value(v.Index(i))
   371			}
   372		case reflect.Struct:
   373			l := v.NumField()
   374			for i := 0; i < l; i++ {
   375				d.value(v.Field(i))
   376			}
   377	
   378		case reflect.Slice:
   379			l := v.Len()
   380			for i := 0; i < l; i++ {
   381				d.value(v.Index(i))
   382			}
   383	
   384		case reflect.Int8:
   385			v.SetInt(int64(d.int8()))
   386		case reflect.Int16:
   387			v.SetInt(int64(d.int16()))
   388		case reflect.Int32:
   389			v.SetInt(int64(d.int32()))
   390		case reflect.Int64:
   391			v.SetInt(d.int64())
   392	
   393		case reflect.Uint8:
   394			v.SetUint(uint64(d.uint8()))
   395		case reflect.Uint16:
   396			v.SetUint(uint64(d.uint16()))
   397		case reflect.Uint32:
   398			v.SetUint(uint64(d.uint32()))
   399		case reflect.Uint64:
   400			v.SetUint(d.uint64())
   401	
   402		case reflect.Float32:
   403			v.SetFloat(float64(math.Float32frombits(d.uint32())))
   404		case reflect.Float64:
   405			v.SetFloat(math.Float64frombits(d.uint64()))
   406	
   407		case reflect.Complex64:
   408			v.SetComplex(complex(
   409				float64(math.Float32frombits(d.uint32())),
   410				float64(math.Float32frombits(d.uint32())),
   411			))
   412		case reflect.Complex128:
   413			v.SetComplex(complex(
   414				math.Float64frombits(d.uint64()),
   415				math.Float64frombits(d.uint64()),
   416			))
   417		}
   418	}
   419	
   420	func (e *encoder) value(v reflect.Value) {
   421		switch v.Kind() {
   422		case reflect.Array:
   423			l := v.Len()
   424			for i := 0; i < l; i++ {
   425				e.value(v.Index(i))
   426			}
   427		case reflect.Struct:
   428			l := v.NumField()
   429			for i := 0; i < l; i++ {
   430				e.value(v.Field(i))
   431			}
   432		case reflect.Slice:
   433			l := v.Len()
   434			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			switch v.Type().Kind() {
   440			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			switch v.Type().Kind() {
   452			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			switch v.Type().Kind() {
   464			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			switch v.Type().Kind() {
   472			case reflect.Complex64:
   473				x := v.Complex()
   474				e.uint32(math.Float32bits(float32(real(x))))
   475				e.uint32(math.Float32bits(float32(imag(x))))
   476			case reflect.Complex128:
   477				x := v.Complex()
   478				e.uint64(math.Float64bits(real(x)))
   479				e.uint64(math.Float64bits(imag(x)))
   480			}
   481		}
   482	}
   483	
   484	// intDestSize returns the size of the integer that ptrType points to,
   485	// or 0 if the type is not supported.
   486	func intDestSize(ptrType interface{}) int {
   487		switch ptrType.(type) {
   488		case *int8, *uint8:
   489			return 1
   490		case *int16, *uint16:
   491			return 2
   492		case *int32, *uint32:
   493			return 4
   494		case *int64, *uint64:
   495			return 8
   496		}
   497		return 0
   498	}

release.r60.3. Except as noted, this content is licensed under a Creative Commons Attribution 3.0 License.