github.com/d4l3k/go@v0.0.0-20151015000803-65fc379daeda/src/encoding/binary/binary.go (about) 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 simple translation between numbers and byte 6 // sequences and encoding and decoding of varints. 7 // 8 // Numbers are translated by reading and writing fixed-size values. 9 // A fixed-size value is either a fixed-size arithmetic 10 // type (int8, uint8, int16, float32, complex64, ...) 11 // or an array or struct containing only fixed-size values. 12 // 13 // The varint functions encode and decode single integer values using 14 // a variable-length encoding; smaller values require fewer bytes. 15 // For a specification, see 16 // https://developers.google.com/protocol-buffers/docs/encoding. 17 // 18 // This package favors simplicity over efficiency. Clients that require 19 // high-performance serialization, especially for large data structures, 20 // should look at more advanced solutions such as the encoding/gob 21 // package or protocol buffers. 22 package binary 23 24 import ( 25 "errors" 26 "io" 27 "math" 28 "reflect" 29 ) 30 31 // A ByteOrder specifies how to convert byte sequences into 32 // 16-, 32-, or 64-bit unsigned integers. 33 type ByteOrder interface { 34 Uint16([]byte) uint16 35 Uint32([]byte) uint32 36 Uint64([]byte) uint64 37 PutUint16([]byte, uint16) 38 PutUint32([]byte, uint32) 39 PutUint64([]byte, uint64) 40 String() string 41 } 42 43 // LittleEndian is the little-endian implementation of ByteOrder. 44 var LittleEndian littleEndian 45 46 // BigEndian is the big-endian implementation of ByteOrder. 47 var BigEndian bigEndian 48 49 type littleEndian struct{} 50 51 func (littleEndian) Uint16(b []byte) uint16 { return uint16(b[0]) | uint16(b[1])<<8 } 52 53 func (littleEndian) PutUint16(b []byte, v uint16) { 54 b[0] = byte(v) 55 b[1] = byte(v >> 8) 56 } 57 58 func (littleEndian) Uint32(b []byte) uint32 { 59 return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 60 } 61 62 func (littleEndian) PutUint32(b []byte, v uint32) { 63 b[0] = byte(v) 64 b[1] = byte(v >> 8) 65 b[2] = byte(v >> 16) 66 b[3] = byte(v >> 24) 67 } 68 69 func (littleEndian) Uint64(b []byte) uint64 { 70 return uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | 71 uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56 72 } 73 74 func (littleEndian) PutUint64(b []byte, v uint64) { 75 b[0] = byte(v) 76 b[1] = byte(v >> 8) 77 b[2] = byte(v >> 16) 78 b[3] = byte(v >> 24) 79 b[4] = byte(v >> 32) 80 b[5] = byte(v >> 40) 81 b[6] = byte(v >> 48) 82 b[7] = byte(v >> 56) 83 } 84 85 func (littleEndian) String() string { return "LittleEndian" } 86 87 func (littleEndian) GoString() string { return "binary.LittleEndian" } 88 89 type bigEndian struct{} 90 91 func (bigEndian) Uint16(b []byte) uint16 { return uint16(b[1]) | uint16(b[0])<<8 } 92 93 func (bigEndian) PutUint16(b []byte, v uint16) { 94 b[0] = byte(v >> 8) 95 b[1] = byte(v) 96 } 97 98 func (bigEndian) Uint32(b []byte) uint32 { 99 return uint32(b[3]) | uint32(b[2])<<8 | uint32(b[1])<<16 | uint32(b[0])<<24 100 } 101 102 func (bigEndian) PutUint32(b []byte, v uint32) { 103 b[0] = byte(v >> 24) 104 b[1] = byte(v >> 16) 105 b[2] = byte(v >> 8) 106 b[3] = byte(v) 107 } 108 109 func (bigEndian) Uint64(b []byte) uint64 { 110 return uint64(b[7]) | uint64(b[6])<<8 | uint64(b[5])<<16 | uint64(b[4])<<24 | 111 uint64(b[3])<<32 | uint64(b[2])<<40 | uint64(b[1])<<48 | uint64(b[0])<<56 112 } 113 114 func (bigEndian) PutUint64(b []byte, v uint64) { 115 b[0] = byte(v >> 56) 116 b[1] = byte(v >> 48) 117 b[2] = byte(v >> 40) 118 b[3] = byte(v >> 32) 119 b[4] = byte(v >> 24) 120 b[5] = byte(v >> 16) 121 b[6] = byte(v >> 8) 122 b[7] = byte(v) 123 } 124 125 func (bigEndian) String() string { return "BigEndian" } 126 127 func (bigEndian) GoString() string { return "binary.BigEndian" } 128 129 // Read reads structured binary data from r into data. 130 // Data must be a pointer to a fixed-size value or a slice 131 // of fixed-size values. 132 // Bytes read from r are decoded using the specified byte order 133 // and written to successive fields of the data. 134 // When reading into structs, the field data for fields with 135 // blank (_) field names is skipped; i.e., blank field names 136 // may be used for padding. 137 // When reading into a struct, all non-blank fields must be exported. 138 // 139 // The error is EOF only if no bytes were read. 140 // If an EOF happens after reading some but not all the bytes, 141 // Read returns ErrUnexpectedEOF. 142 func Read(r io.Reader, order ByteOrder, data interface{}) error { 143 // Fast path for basic types and slices. 144 if n := intDataSize(data); n != 0 { 145 var b [8]byte 146 var bs []byte 147 if n > len(b) { 148 bs = make([]byte, n) 149 } else { 150 bs = b[:n] 151 } 152 if _, err := io.ReadFull(r, bs); err != nil { 153 return err 154 } 155 switch data := data.(type) { 156 case *int8: 157 *data = int8(b[0]) 158 case *uint8: 159 *data = b[0] 160 case *int16: 161 *data = int16(order.Uint16(bs)) 162 case *uint16: 163 *data = order.Uint16(bs) 164 case *int32: 165 *data = int32(order.Uint32(bs)) 166 case *uint32: 167 *data = order.Uint32(bs) 168 case *int64: 169 *data = int64(order.Uint64(bs)) 170 case *uint64: 171 *data = order.Uint64(bs) 172 case []int8: 173 for i, x := range bs { // Easier to loop over the input for 8-bit values. 174 data[i] = int8(x) 175 } 176 case []uint8: 177 copy(data, bs) 178 case []int16: 179 for i := range data { 180 data[i] = int16(order.Uint16(bs[2*i:])) 181 } 182 case []uint16: 183 for i := range data { 184 data[i] = order.Uint16(bs[2*i:]) 185 } 186 case []int32: 187 for i := range data { 188 data[i] = int32(order.Uint32(bs[4*i:])) 189 } 190 case []uint32: 191 for i := range data { 192 data[i] = order.Uint32(bs[4*i:]) 193 } 194 case []int64: 195 for i := range data { 196 data[i] = int64(order.Uint64(bs[8*i:])) 197 } 198 case []uint64: 199 for i := range data { 200 data[i] = order.Uint64(bs[8*i:]) 201 } 202 } 203 return nil 204 } 205 206 // Fallback to reflect-based decoding. 207 v := reflect.ValueOf(data) 208 size := -1 209 switch v.Kind() { 210 case reflect.Ptr: 211 v = v.Elem() 212 size = dataSize(v) 213 case reflect.Slice: 214 size = dataSize(v) 215 } 216 if size < 0 { 217 return errors.New("binary.Read: invalid type " + reflect.TypeOf(data).String()) 218 } 219 d := &decoder{order: order, buf: make([]byte, size)} 220 if _, err := io.ReadFull(r, d.buf); err != nil { 221 return err 222 } 223 d.value(v) 224 return nil 225 } 226 227 // Write writes the binary representation of data into w. 228 // Data must be a fixed-size value or a slice of fixed-size 229 // values, or a pointer to such data. 230 // Bytes written to w are encoded using the specified byte order 231 // and read from successive fields of the data. 232 // When writing structs, zero values are written for fields 233 // with blank (_) field names. 234 func Write(w io.Writer, order ByteOrder, data interface{}) error { 235 // Fast path for basic types and slices. 236 if n := intDataSize(data); n != 0 { 237 var b [8]byte 238 var bs []byte 239 if n > len(b) { 240 bs = make([]byte, n) 241 } else { 242 bs = b[:n] 243 } 244 switch v := data.(type) { 245 case *int8: 246 b[0] = byte(*v) 247 case int8: 248 b[0] = byte(v) 249 case []int8: 250 for i, x := range v { 251 bs[i] = byte(x) 252 } 253 case *uint8: 254 b[0] = *v 255 case uint8: 256 b[0] = byte(v) 257 case []uint8: 258 bs = v 259 case *int16: 260 order.PutUint16(bs, uint16(*v)) 261 case int16: 262 order.PutUint16(bs, uint16(v)) 263 case []int16: 264 for i, x := range v { 265 order.PutUint16(bs[2*i:], uint16(x)) 266 } 267 case *uint16: 268 order.PutUint16(bs, *v) 269 case uint16: 270 order.PutUint16(bs, v) 271 case []uint16: 272 for i, x := range v { 273 order.PutUint16(bs[2*i:], x) 274 } 275 case *int32: 276 order.PutUint32(bs, uint32(*v)) 277 case int32: 278 order.PutUint32(bs, uint32(v)) 279 case []int32: 280 for i, x := range v { 281 order.PutUint32(bs[4*i:], uint32(x)) 282 } 283 case *uint32: 284 order.PutUint32(bs, *v) 285 case uint32: 286 order.PutUint32(bs, v) 287 case []uint32: 288 for i, x := range v { 289 order.PutUint32(bs[4*i:], x) 290 } 291 case *int64: 292 order.PutUint64(bs, uint64(*v)) 293 case int64: 294 order.PutUint64(bs, uint64(v)) 295 case []int64: 296 for i, x := range v { 297 order.PutUint64(bs[8*i:], uint64(x)) 298 } 299 case *uint64: 300 order.PutUint64(bs, *v) 301 case uint64: 302 order.PutUint64(bs, v) 303 case []uint64: 304 for i, x := range v { 305 order.PutUint64(bs[8*i:], x) 306 } 307 } 308 _, err := w.Write(bs) 309 return err 310 } 311 312 // Fallback to reflect-based encoding. 313 v := reflect.Indirect(reflect.ValueOf(data)) 314 size := dataSize(v) 315 if size < 0 { 316 return errors.New("binary.Write: invalid type " + reflect.TypeOf(data).String()) 317 } 318 buf := make([]byte, size) 319 e := &encoder{order: order, buf: buf} 320 e.value(v) 321 _, err := w.Write(buf) 322 return err 323 } 324 325 // Size returns how many bytes Write would generate to encode the value v, which 326 // must be a fixed-size value or a slice of fixed-size values, or a pointer to such data. 327 // If v is neither of these, Size returns -1. 328 func Size(v interface{}) int { 329 return dataSize(reflect.Indirect(reflect.ValueOf(v))) 330 } 331 332 // dataSize returns the number of bytes the actual data represented by v occupies in memory. 333 // For compound structures, it sums the sizes of the elements. Thus, for instance, for a slice 334 // it returns the length of the slice times the element size and does not count the memory 335 // occupied by the header. If the type of v is not acceptable, dataSize returns -1. 336 func dataSize(v reflect.Value) int { 337 if v.Kind() == reflect.Slice { 338 if s := sizeof(v.Type().Elem()); s >= 0 { 339 return s * v.Len() 340 } 341 return -1 342 } 343 return sizeof(v.Type()) 344 } 345 346 // sizeof returns the size >= 0 of variables for the given type or -1 if the type is not acceptable. 347 func sizeof(t reflect.Type) int { 348 switch t.Kind() { 349 case reflect.Array: 350 if s := sizeof(t.Elem()); s >= 0 { 351 return s * t.Len() 352 } 353 354 case reflect.Struct: 355 sum := 0 356 for i, n := 0, t.NumField(); i < n; i++ { 357 s := sizeof(t.Field(i).Type) 358 if s < 0 { 359 return -1 360 } 361 sum += s 362 } 363 return sum 364 365 case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, 366 reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, 367 reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128: 368 return int(t.Size()) 369 } 370 371 return -1 372 } 373 374 type coder struct { 375 order ByteOrder 376 buf []byte 377 } 378 379 type decoder coder 380 type encoder coder 381 382 func (d *decoder) uint8() uint8 { 383 x := d.buf[0] 384 d.buf = d.buf[1:] 385 return x 386 } 387 388 func (e *encoder) uint8(x uint8) { 389 e.buf[0] = x 390 e.buf = e.buf[1:] 391 } 392 393 func (d *decoder) uint16() uint16 { 394 x := d.order.Uint16(d.buf[0:2]) 395 d.buf = d.buf[2:] 396 return x 397 } 398 399 func (e *encoder) uint16(x uint16) { 400 e.order.PutUint16(e.buf[0:2], x) 401 e.buf = e.buf[2:] 402 } 403 404 func (d *decoder) uint32() uint32 { 405 x := d.order.Uint32(d.buf[0:4]) 406 d.buf = d.buf[4:] 407 return x 408 } 409 410 func (e *encoder) uint32(x uint32) { 411 e.order.PutUint32(e.buf[0:4], x) 412 e.buf = e.buf[4:] 413 } 414 415 func (d *decoder) uint64() uint64 { 416 x := d.order.Uint64(d.buf[0:8]) 417 d.buf = d.buf[8:] 418 return x 419 } 420 421 func (e *encoder) uint64(x uint64) { 422 e.order.PutUint64(e.buf[0:8], x) 423 e.buf = e.buf[8:] 424 } 425 426 func (d *decoder) int8() int8 { return int8(d.uint8()) } 427 428 func (e *encoder) int8(x int8) { e.uint8(uint8(x)) } 429 430 func (d *decoder) int16() int16 { return int16(d.uint16()) } 431 432 func (e *encoder) int16(x int16) { e.uint16(uint16(x)) } 433 434 func (d *decoder) int32() int32 { return int32(d.uint32()) } 435 436 func (e *encoder) int32(x int32) { e.uint32(uint32(x)) } 437 438 func (d *decoder) int64() int64 { return int64(d.uint64()) } 439 440 func (e *encoder) int64(x int64) { e.uint64(uint64(x)) } 441 442 func (d *decoder) value(v reflect.Value) { 443 switch v.Kind() { 444 case reflect.Array: 445 l := v.Len() 446 for i := 0; i < l; i++ { 447 d.value(v.Index(i)) 448 } 449 450 case reflect.Struct: 451 t := v.Type() 452 l := v.NumField() 453 for i := 0; i < l; i++ { 454 // Note: Calling v.CanSet() below is an optimization. 455 // It would be sufficient to check the field name, 456 // but creating the StructField info for each field is 457 // costly (run "go test -bench=ReadStruct" and compare 458 // results when making changes to this code). 459 if v := v.Field(i); v.CanSet() || t.Field(i).Name != "_" { 460 d.value(v) 461 } else { 462 d.skip(v) 463 } 464 } 465 466 case reflect.Slice: 467 l := v.Len() 468 for i := 0; i < l; i++ { 469 d.value(v.Index(i)) 470 } 471 472 case reflect.Int8: 473 v.SetInt(int64(d.int8())) 474 case reflect.Int16: 475 v.SetInt(int64(d.int16())) 476 case reflect.Int32: 477 v.SetInt(int64(d.int32())) 478 case reflect.Int64: 479 v.SetInt(d.int64()) 480 481 case reflect.Uint8: 482 v.SetUint(uint64(d.uint8())) 483 case reflect.Uint16: 484 v.SetUint(uint64(d.uint16())) 485 case reflect.Uint32: 486 v.SetUint(uint64(d.uint32())) 487 case reflect.Uint64: 488 v.SetUint(d.uint64()) 489 490 case reflect.Float32: 491 v.SetFloat(float64(math.Float32frombits(d.uint32()))) 492 case reflect.Float64: 493 v.SetFloat(math.Float64frombits(d.uint64())) 494 495 case reflect.Complex64: 496 v.SetComplex(complex( 497 float64(math.Float32frombits(d.uint32())), 498 float64(math.Float32frombits(d.uint32())), 499 )) 500 case reflect.Complex128: 501 v.SetComplex(complex( 502 math.Float64frombits(d.uint64()), 503 math.Float64frombits(d.uint64()), 504 )) 505 } 506 } 507 508 func (e *encoder) value(v reflect.Value) { 509 switch v.Kind() { 510 case reflect.Array: 511 l := v.Len() 512 for i := 0; i < l; i++ { 513 e.value(v.Index(i)) 514 } 515 516 case reflect.Struct: 517 t := v.Type() 518 l := v.NumField() 519 for i := 0; i < l; i++ { 520 // see comment for corresponding code in decoder.value() 521 if v := v.Field(i); v.CanSet() || t.Field(i).Name != "_" { 522 e.value(v) 523 } else { 524 e.skip(v) 525 } 526 } 527 528 case reflect.Slice: 529 l := v.Len() 530 for i := 0; i < l; i++ { 531 e.value(v.Index(i)) 532 } 533 534 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 535 switch v.Type().Kind() { 536 case reflect.Int8: 537 e.int8(int8(v.Int())) 538 case reflect.Int16: 539 e.int16(int16(v.Int())) 540 case reflect.Int32: 541 e.int32(int32(v.Int())) 542 case reflect.Int64: 543 e.int64(v.Int()) 544 } 545 546 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: 547 switch v.Type().Kind() { 548 case reflect.Uint8: 549 e.uint8(uint8(v.Uint())) 550 case reflect.Uint16: 551 e.uint16(uint16(v.Uint())) 552 case reflect.Uint32: 553 e.uint32(uint32(v.Uint())) 554 case reflect.Uint64: 555 e.uint64(v.Uint()) 556 } 557 558 case reflect.Float32, reflect.Float64: 559 switch v.Type().Kind() { 560 case reflect.Float32: 561 e.uint32(math.Float32bits(float32(v.Float()))) 562 case reflect.Float64: 563 e.uint64(math.Float64bits(v.Float())) 564 } 565 566 case reflect.Complex64, reflect.Complex128: 567 switch v.Type().Kind() { 568 case reflect.Complex64: 569 x := v.Complex() 570 e.uint32(math.Float32bits(float32(real(x)))) 571 e.uint32(math.Float32bits(float32(imag(x)))) 572 case reflect.Complex128: 573 x := v.Complex() 574 e.uint64(math.Float64bits(real(x))) 575 e.uint64(math.Float64bits(imag(x))) 576 } 577 } 578 } 579 580 func (d *decoder) skip(v reflect.Value) { 581 d.buf = d.buf[dataSize(v):] 582 } 583 584 func (e *encoder) skip(v reflect.Value) { 585 n := dataSize(v) 586 for i := range e.buf[0:n] { 587 e.buf[i] = 0 588 } 589 e.buf = e.buf[n:] 590 } 591 592 // intDataSize returns the size of the data required to represent the data when encoded. 593 // It returns zero if the type cannot be implemented by the fast path in Read or Write. 594 func intDataSize(data interface{}) int { 595 switch data := data.(type) { 596 case int8, uint8, *int8, *uint8: 597 return 1 598 case []int8: 599 return len(data) 600 case []uint8: 601 return len(data) 602 case int16, uint16, *int16, *uint16: 603 return 2 604 case []int16: 605 return 2 * len(data) 606 case []uint16: 607 return 2 * len(data) 608 case int32, uint32, *int32, *uint32: 609 return 4 610 case []int32: 611 return 4 * len(data) 612 case []uint32: 613 return 4 * len(data) 614 case int64, uint64, *int64, *uint64: 615 return 8 616 case []int64: 617 return 8 * len(data) 618 case []uint64: 619 return 8 * len(data) 620 } 621 return 0 622 }