func parseColumnType(buf *bytes.Buffer) (columnInfo, error) { var result columnInfo b, err := buf.ReadByte() //fmt.Printf("% X \n", buf.Bytes()) if err != nil { return result, err } ctype := columnType(b) result.columnType = ctype // So what follows might be the most useless switch statement in the world. Even the default clause is useless as it will never get executed, unless I really did something wrong. switch ctype & 0x30 { case 0x16: //Zero-length token, nothing to do case 0x30: //Above is the same as: //case NULLTYPE, INT1TYPE, BITTYPE, INT2TYPE, INT4TYPE, DATETIM4TYPE, FLT4TYPE, MONEY4TYPE, MONEYTYPE, DATETIMETYPE, FLT8TYPE, INT8TYPE: // Nothing to do for these, length is contained within type case 0x20: // Variable-length token, length is contained in value case 0x0: // Variable count token, default: panic(fmt.Sprintf("unknown column type: %x", b)) } return result, nil }
func (t *tScreen) parseFunctionKey(buf *bytes.Buffer) (bool, bool) { b := buf.Bytes() partial := false for e, k := range t.keycodes { esc := []byte(e) if (len(esc) == 1) && (esc[0] == '\x1b') { continue } if bytes.HasPrefix(b, esc) { // matched var r rune if len(esc) == 1 { r = rune(b[0]) } mod := k.mod if t.escaped { mod |= ModAlt t.escaped = false } ev := NewEventKey(k.key, r, mod) t.PostEvent(ev) for i := 0; i < len(esc); i++ { buf.ReadByte() } return true, true } if bytes.HasPrefix(esc, b) { partial = true } } return partial, false }
func decodeNextDictFrom(buffer *bytes.Buffer) (Dict, error) { initial, err := buffer.ReadByte() if initial != 'd' || err != nil { panic("How is this not a dictionary?") } result := make(Dict, 0) AccumulateItems: for { nextByte, err := buffer.ReadByte() switch { case err != nil: return nil, err case nextByte == 'e': break AccumulateItems default: buffer.UnreadByte() key, err := decodeNextStringFrom(buffer) if err != nil { return nil, err } value, err := decodeNextFrom(buffer) if err != nil { return nil, err } result[key] = value } } return result, nil }
func decodeNextFrom(buffer *bytes.Buffer) (Bencodable, error) { nextByte, err := buffer.ReadByte() if err != nil { return nil, err } buffer.UnreadByte() var result Bencodable switch nextByte { case 'i': result, err = decodeNextIntFrom(buffer) case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': result, err = decodeNextStringFrom(buffer) case 'l': result, err = decodeNextListFrom(buffer) case 'd': result, err = decodeNextDictFrom(buffer) default: err = errors.New(fmt.Sprintf( "Unexpected initial byte in bencoded data: %v", strconv.Quote(string(nextByte)))) } if err != nil { return nil, err } return result, nil }
func decodeNextListFrom(buffer *bytes.Buffer) (List, error) { initial, err := buffer.ReadByte() if initial != 'l' || err != nil { panic("How is this not a list?") } result := make(List, 0) AccumulateItems: for { nextByte, err := buffer.ReadByte() switch { case err != nil: return nil, err case nextByte == 'e': break AccumulateItems default: buffer.UnreadByte() value, err := decodeNextFrom(buffer) if err != nil { return nil, err } result = append(result, value) } } return result, nil }
// Skip will skip the next field we don't want to read. func Skip(buf *bytes.Buffer, kind byte) { switch kind { case Number, Datetime, Long, Ulong: Next(buf, 8) case String: // length of a string includes the 0 at the end, but not the size l := int(Pack.Uint32(Next(buf, 4))) Next(buf, l) case Object, Array: // the encoded length includes the 4 bytes for the size l := int(Pack.Uint32(Next(buf, 4))) if l < 4 { panic(NewBsonError("Object or Array should at least be 4 bytes long")) } Next(buf, l-4) case Binary: // length of a binary doesn't include the subtype l := int(Pack.Uint32(Next(buf, 4))) Next(buf, l+1) case Boolean: buf.ReadByte() case Int: Next(buf, 4) case Null: // no op default: panic(NewBsonError("unexpected kind %v for skip", kind)) } }
func parseMeta(buf *bytes.Buffer, repo string) { var name string pack := map[string]string{} pack["REPO"] = repo _, _ = buf.ReadByte() for { key, err := buf.ReadBytes('%') if err == io.EOF { break } key = bytes.Trim(key, "%") values, _ := buf.ReadBytes('%') values = bytes.Trim(values, "%") values = bytes.Replace(values, []byte("\n"), []byte(" "), -1) values = bytes.Trim(values, " ") if string(key) == "NAME" { name = string(values) } pack[string(key)] = string(values) } v, _ := packages[name] if v != nil { printf("%s exists\n", name) } packages[name] = pack }
func parse(r io.Reader) (*Match, error) { cmd := exec.Command("pdftotext", "-q", "-enc", "UTF-8", "-eol", "unix", "-layout", "-", "-") cmd.Stdin = r stdout := new(bytes.Buffer) cmd.Stdout = stdout stderr := new(bytes.Buffer) cmd.Stderr = stderr err := cmd.Run() if err != nil { return nil, err } m := new(Match) m.Results = make(map[Division][]Result) for { if err := parsePage(stdout, m); err != nil { return nil, err } if _, err := stdout.ReadByte(); err == io.EOF { return m, nil } else { stdout.UnreadByte() } } }
// decodeTrack will decode a single track from the supplied buffer, // and return it. // The buffer is forwarded to the end of the track data. // If not more tracks can be found io.EOF will be returned. func decodeTrack(r *bytes.Buffer) (*Track, error) { t := &Track{} // Read track header th := trackHeader{} err := binary.Read(r, binary.BigEndian, &th) if err != nil { return nil, err } t.Instrument.ID = th.ID err = t.Instrument.decodeName(r, int(th.NameLen)) if err != nil { return nil, err } // Read beats t.Steps = make([]Step, SpliceTrackLength) for i := range t.Steps { c, err := r.ReadByte() if err != nil { return nil, err } t.Steps[i] = Step(c) } return t, nil }
// Skip will skip a field we don't want to read func Skip(buf *bytes.Buffer, kind byte) { switch kind { case Number: buf.Next(8) case String: // length of a string includes the 0 at the end, but not the size l := int(Pack.Uint32(buf.Next(4))) buf.Next(l) case Object, Array: // the encoded length includes the 4 bytes for the size l := int(Pack.Uint32(buf.Next(4))) if l < 4 { panic(NewBsonError("Object or Array should at least be 4 bytes long")) } buf.Next(l - 4) case Binary: // length of a binary doesn't include the subtype l := int(Pack.Uint32(buf.Next(4))) buf.Next(l + 1) case Boolean: buf.ReadByte() case Datetime: buf.Next(8) case Int: buf.Next(4) case Long: buf.Next(8) case Ulong: buf.Next(8) case Null: // no op default: panic(NewBsonError("don't know how to skip kind %v yet", kind)) } }
// TestGetPasswd_Err tests errors are properly handled from getch() func TestGetPasswd_Err(t *testing.T) { var inBuffer *bytes.Buffer getch = func() (byte, error) { b, err := inBuffer.ReadByte() if err != nil { return 13, err } if b == 'z' { return 'z', fmt.Errorf("Forced error; byte returned should not be considered accurate.") } return b, nil } defer func() { getch = defaultGetCh }() for input, expectedPassword := range map[string]string{"abc": "abc", "abzc": "ab"} { inBuffer = bytes.NewBufferString(input) p, err := GetPasswdMasked() if string(p) != expectedPassword { t.Errorf("Expected %q but got %q instead.", expectedPassword, p) } if err == nil { t.Errorf("Expected error to be returned.") } } }
// ReadFrame reads an entire frame into memory. func ReadFrame(r io.Reader) (f Frame, err error) { headBuffer := new(bytes.Buffer) _, err = io.CopyN(headBuffer, r, frameHeadSize) if err != nil { return } if headBuffer.Bytes()[0]&0x80 == 0 { // Data df := DataFrame{} err = readBinary(headBuffer, &df.StreamID, &df.Flags) if err != nil { return } df.Data, err = readData(r) f = df } else { // Control cf := ControlFrame{} headBuffer.ReadByte() headBuffer.ReadByte() // skip version word err = readBinary(headBuffer, &cf.Type, &cf.Flags) if err != nil { return } cf.Data, err = readData(r) f = cf } return }
func readNextByteAsBool(buffer *bytes.Buffer) bool { switch byte, _ := buffer.ReadByte(); byte { case 0x01: return true } return false }
func (ev *AuthEvent) Decode(buffer *bytes.Buffer) (err error) { ev.User, err = DecodeStringValue(buffer) if nil != err { return err } // ev.Mac, err = DecodeStringValue(buffer) // if nil != err { // return err // } ev.RunId, err = DecodeInt64Value(buffer) if nil != err { return err } ev.Index, err = DecodeInt64Value(buffer) if nil != err { return err } ev.IV, err = DecodeUInt64Value(buffer) if nil != err { return err } ev.EncryptMethod, err = buffer.ReadByte() if nil != err { return err } //no need to decode Rand, since it's useless return err }
func getByte(buff *bytes.Buffer) byte { v, err := buff.ReadByte() if err != nil { panic(err) } return v }
// readFrame reads an entire frame into memory func readFrame(r io.Reader) (f frame, err error) { headBuffer := new(bytes.Buffer) _, err = io.CopyN(headBuffer, r, 5) if err != nil { return } if headBuffer.Bytes()[0]&0x80 == 0 { // Data df := dataFrame{} err = readBinary(headBuffer, &df.stream, &df.flags) if err != nil { return } df.data, err = readData(r) f = df } else { // Control cf := controlFrame{} headBuffer.ReadByte() // FIXME skip version word headBuffer.ReadByte() err = readBinary(headBuffer, &cf.kind, &cf.flags) if err != nil { return } cf.data, err = readData(r) f = cf } return }
func read_amf0(r *bytes.Buffer) interface{} { data_type, _ := r.ReadByte() switch data_type { case 0x0: return read_amf0_number(r) case 0x1: return read_amf0_bool(r) case 0x2: return read_amf0_string(r) case 0x3: return read_amf0_object(r) case 0x5: //null return nil case 0x6: //undefined return nil case 0x11: //change to amf3 return read_amf3(r) default: fmt.Printf("#unknown type:0x%x\n", data_type) panic("unknwo type") } return nil }
func assertReadMsg(t *testing.T, s *bytes.Buffer, m *testMsg) { ty, id, name, wait, size, err := ReadMsg(s) if err != nil && err != io.EOF { t.Fatalf("ReadMsg() failed: %v", err.Error()) } if ty != m.t { t.Fatalf("ReadMsg() ty = \"%v\", expected \"%v\"", ty, m.t) } if id != m.id { t.Fatalf("ReadMsg() id = \"%v\", expected \"%v\"", id, m.id) } if name != m.name { t.Fatalf("ReadMsg() name = \"%v\", expected \"%v\"", name, m.name) } if int(wait) != m.wait { t.Fatalf("ReadMsg() wait = %v, expected %v", wait, m.wait) } if int(size) != m.size { t.Fatalf("ReadMsg() size = %v, expected %v", size, m.size) } // Read payload if m.t != MsgTypeProtocolError { for i := 0; i != m.size; i++ { if b, err := s.ReadByte(); err != nil { t.Fatalf("ReadMsg() failed to read payload: %v", err.Error()) } else if b != kPayloadByte { t.Fatalf("ReadMsg() => '%c', expected '%c'", b, kPayloadByte) } } } }
func (header *commentHeader) read(buffer *bytes.Buffer) { b, _ := buffer.ReadByte() if b != 3 { panic(fmt.Sprintf("Header type == %d, expected type == 3.", b)) } if string(buffer.Next(6)) != "vorbis" { panic("vorbis string not found in comment header") } var length uint32 binary.Read(buffer, binary.LittleEndian, &length) header.Vendor_string = string(buffer.Next(int(length))) binary.Read(buffer, binary.LittleEndian, &length) header.User_comments = make([]string, length) for i := range header.User_comments { binary.Read(buffer, binary.LittleEndian, &length) header.User_comments[i] = string(buffer.Next(int(length))) } framing, _ := buffer.ReadByte() header.Framing = (framing & 0x1) != 0 if !header.Framing { panic("Framing bit not set in comment header") } }
// DecodeULEB128 decodes an unsigned Little Endian Base 128 // represented number. func DecodeULEB128(buf *bytes.Buffer) (uint64, uint32) { var ( result uint64 shift uint64 length uint32 ) if buf.Len() == 0 { return 0, 0 } for { b, err := buf.ReadByte() if err != nil { panic("Could not parse ULEB128 value") } length++ result |= uint64((uint(b) & 0x7f) << shift) // If high order bit is 1. if b&0x80 == 0 { break } shift += 7 } return result, length }
// DecodeSLEB128 decodes a signed Little Endian Base 128 // represented number. func DecodeSLEB128(buf *bytes.Buffer) (int64, uint32) { var ( b byte err error result int64 shift uint64 length uint32 ) if buf.Len() == 0 { return 0, 0 } for { b, err = buf.ReadByte() if err != nil { panic("Could not parse SLEB128 value") } length++ result |= int64((int64(b) & 0x7f) << shift) shift += 7 if b&0x80 == 0 { break } } if (shift < 8*uint64(length)) && (b&0x40 > 0) { result |= -(1 << shift) } return result, length }
func ByteRWerExample() { FOREND: for { fmt.Println("请输入要通过WriteByte写入的一个ASCII字符(b:返回上级;q:退出):") var ch byte fmt.Scanf("%c\n", &ch) switch ch { case 'b': fmt.Println("返回上级菜单!") break FOREND case 'q': fmt.Println("程序退出!") os.Exit(0) default: buffer := new(bytes.Buffer) err := buffer.WriteByte(ch) if err == nil { fmt.Println("写入一个字节成功!准备读取该字节……") newCh, _ := buffer.ReadByte() fmt.Printf("读取的字节:%c\n", newCh) } else { fmt.Println("写入错误") } } } }
// parsePacket publishes event according to data parsed func (n *Driver) parsePacket(buf *bytes.Buffer) { for buf.Len() > 0 { b, _ := buf.ReadByte() switch b { case CodeEx: n.Publish(n.Event("extended"), nil) case CodeSignalQuality: ret, _ := buf.ReadByte() n.Publish(n.Event("signal"), ret) case CodeAttention: ret, _ := buf.ReadByte() n.Publish(n.Event("attention"), ret) case CodeMeditation: ret, _ := buf.ReadByte() n.Publish(n.Event("meditation"), ret) case CodeBlink: ret, _ := buf.ReadByte() n.Publish(n.Event("blink"), ret) case CodeWave: buf.Next(1) var ret = make([]byte, 2) buf.Read(ret) n.Publish(n.Event("wave"), int16(ret[0])<<8|int16(ret[1])) case CodeAsicEEG: ret := make([]byte, 25) i, _ := buf.Read(ret) if i == 25 { n.Publish(n.Event("eeg"), n.parseEEG(ret)) } } } }
func (header *idHeader) read(buffer *bytes.Buffer) { b, _ := buffer.ReadByte() if b != 1 { panic(fmt.Sprintf("Header type == %d, expected type == 1.", b)) } if string(buffer.Next(6)) != "vorbis" { panic("vorbis string not found in id header") } binary.Read(buffer, binary.LittleEndian, &header.idHeaderFixed) var block_sizes uint8 binary.Read(buffer, binary.LittleEndian, &block_sizes) header.Blocksize_0 = int(1 << (block_sizes & 0x0f)) header.Blocksize_1 = int(1 << ((block_sizes & 0xf0) >> 4)) var framing uint8 binary.Read(buffer, binary.LittleEndian, &framing) if framing != 1 { panic("Id header not properly framed") } if header.Version != 0 { panic(fmt.Sprintf("Unexpected version number in id header: %d", header.Version)) } if header.Channels == 0 { panic("Channels set to zero in id header") } if header.Sample_rate == 0 { panic("Sample rate set to zero in id header") } if header.Blocksize_0 != 64 && header.Blocksize_0 != 128 && header.Blocksize_0 != 256 && header.Blocksize_0 != 512 && header.Blocksize_0 != 1024 && header.Blocksize_0 != 2048 && header.Blocksize_0 != 4096 && header.Blocksize_0 != 8192 { panic(fmt.Sprintf("Invalid block 0 size: %d", header.Blocksize_0)) } if header.Blocksize_1 != 64 && header.Blocksize_1 != 128 && header.Blocksize_1 != 256 && header.Blocksize_1 != 512 && header.Blocksize_1 != 1024 && header.Blocksize_1 != 2048 && header.Blocksize_1 != 4096 && header.Blocksize_1 != 8192 { panic(fmt.Sprintf("Invalid block 1 size: %d", header.Blocksize_1)) } if header.Blocksize_0 > header.Blocksize_1 { panic(fmt.Sprintf("Block 0 size > block 1 size: %d > %d", header.Blocksize_0, header.Blocksize_1)) } if buffer.Len() > 0 { // TODO: Shouldn't be anything leftover, log a warning? } }
func (c *Compressor) decode(buf *bytes.Buffer) []float64 { head, _ := buf.ReadByte() var pred int64 if (head & 0x80) != 0 { pred = c.pred2.Prediction() } else { pred = c.pred1.Prediction() } nzb := (head & 0x70) >> 4 if nzb > 3 { nzb++ } dst := make([]byte, 8-nzb) // FIXME: errors buf.Read(dst) diff := c.ToLong(dst) actual := pred ^ diff c.pred1.Update(actual) c.pred2.Update(actual) var ret []float64 ret = append(ret, math.Float64frombits(uint64(actual))) if (head & 0x08) != 0 { pred = c.pred2.Prediction() } else { pred = c.pred1.Prediction() } nzb = head & 0x07 if nzb > 3 { nzb++ } dst = make([]byte, 8-nzb) // FIXME: errors buf.Read(dst) diff = c.ToLong(dst) if nzb == 7 && diff == 0 { return ret } actual = pred ^ diff c.pred1.Update(actual) c.pred2.Update(actual) return append(ret, math.Float64frombits(uint64(actual))) }
func read_amf0_type_number(r *bytes.Buffer) float64 { data_type, _ := r.ReadByte() if data_type != 0x0 { panic("wrong data type") } return read_amf0_number(r) }
func read_amf0_type_string(r *bytes.Buffer) string { data_type, _ := r.ReadByte() if data_type != 0x2 { panic("wrong data type") } return read_amf0_string(r) }
func readCString(buf *bytes.Buffer) string { out := bytes.NewBuffer([]byte{}) var c byte for c, _ = buf.ReadByte(); c != 0; c, _ = buf.ReadByte() { out.WriteByte(c) } return out.String() }
func readUint16(b *bytes.Buffer) (uint16, error) { var i uint16 = 0 var n byte = 0 n, _ = b.ReadByte() i |= uint16(n) n, _ = b.ReadByte() i |= uint16(n) << 8 return i, nil }
func (t *tScreen) scanInput(buf *bytes.Buffer, expire bool) { for { b := buf.Bytes() if len(b) == 0 { buf.Reset() return } partials := 0 if part, comp := t.parseRune(buf); comp { continue } else if part { partials++ } if part, comp := t.parseFunctionKey(buf); comp { continue } else if part { partials++ } // Only parse mouse records if this term claims to have // mouse support if t.ti.Mouse != "" { if part, comp := t.parseXtermMouse(buf); comp { continue } else if part { partials++ } if part, comp := t.parseSgrMouse(buf); comp { continue } else if part { partials++ } } if partials == 0 || expire { // Nothing was going to match, or we timed out // waiting for more data -- just deliver the characters // to the app & let them sort it out. Possibly we should only // do this for control characters such like ESC. by, _ := buf.ReadByte() ev := NewEventKey(KeyRune, rune(by), ModNone) t.PostEvent(ev) continue } // well we have some partial data, wait until we get // some more break } }