Esempio n. 1
0
func (w *writer) writeFrame(frame protocol.Frame, more bool) error {
	// Setup the length of the frame. If the length is < 0xff, only one
	// byte is needed. For bigger frames, the first byte is 0xff and the
	// next 8 bytes consists of the length.
	var size int
	var length = uint64(frame.Len()) + 1
	if length < 0xff {
		w.buf[0] = byte(length)
		size = 1
	} else {
		w.buf[0] = 0xff
		binary.BigEndian.PutUint64(w.buf[1:9], length)
		size = 9
	}

	// Add flags for the frame.
	var flags = uint8(0)
	if more {
		flags |= frameFlagMore
	}
	w.buf[size] = flags
	size++

	if n, err := w.wr.Write(w.buf[0:size]); err != nil {
		return err
	} else if n != size {
		return errors.New("zenio: failed to write frame header")
	}

	// TODO can performance be improved if frame implemented WriteTo?
	if _, err := io.Copy(w.wr, frame); err != nil {
		return err
	}
	return nil
}
Esempio n. 2
0
func TestReader(t *testing.T) {
	for i, c := range testCases {
		if c.skipDec {
			continue
		}
		var (
			j     int
			n     int64
			err   error
			msg   protocol.Message
			frame protocol.Frame
		)
		r := newReader(bytes.NewReader(c.encoded))
		if msg, err = r.Read(); err != nil {
			t.Fatal(err)
		}
		for _, p := range c.decoded {
			frame, err = msg.Next()
			j++
			if err != nil {
				break
			} else if frame.Len() != len(p) {
				t.Errorf("%d invalid length", i)
			}

			var buf bytes.Buffer
			if n, err = io.Copy(&buf, frame); err != nil {
				break
			} else if n != int64(len(p)) {
				t.Errorf("%d invalid length", i)
			} else if !bytes.Equal(buf.Bytes(), p) {
				t.Errorf("%d %#v != %#v", i, buf, p)
			}

			if !msg.More() {
				break
			}
		}

		if err != c.err {
			t.Errorf("%d %#v != %#v", i, err, c.err)
		} else if msg.More() {
			t.Fatal("not all frames consumed")
		}
	}
}
Esempio n. 3
0
func TestReader(t *testing.T) {
	var (
		err   error
		msg   protocol.Message
		frame protocol.Frame
	)
	for _, c := range testCases {
		r := newReader(bytes.NewReader(c.encoded))
		for _, p := range c.decoded {
			var buf bytes.Buffer
			msg, err = r.Read()
			if err != nil {
				break
			}
			frame, err = msg.Next()
			if err != nil {
				break
			} else if frame.Len() != len(p) {
				t.Error("invalid length")
			}
			if n, err := io.Copy(&buf, frame); err != nil {
				break
			} else if n != int64(len(p)) {
				t.Error("invalid length")
			} else if !bytes.Equal(buf.Bytes(), p) {
				t.Errorf("%#v != %#v", buf, p)
			}

			if msg.More() {
				t.Fatal("more")
			}
		}

		if err != c.err {
			t.Errorf("%#v != %#v", err, c.err)
		}
	}
}