1 // netstring -- netstring format serialization library
2 // Copyright (C) 2015-2024 Sergey Matveev <stargrave@stargrave.org>
4 // This program is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, version 3 of the License.
8 // This program is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 // GNU General Public License for more details.
13 // You should have received a copy of the GNU General Public License
14 // along with this program. If not, see <http://www.gnu.org/licenses/>.
25 func TestTrivial(t *testing.T) {
28 if n, err := w.WriteChunk([]byte{}); err != nil || n != 3 || string(buf.Next(3)) != "0:," {
31 if n, err := w.WriteChunk([]byte("foo")); err != nil || n != 6 {
34 if n, err := w.WriteChunk([]byte("barz")); err != nil || n != 7 {
37 if buf.String() != "3:foo,4:barz," {
41 if n, err := r.Next(); err != nil || n != 3 {
44 if r.Discard() != nil {
47 if n, err := r.Next(); err != nil || n != 4 {
51 if n, err := r.Read(m); err != nil || n != 4 {
54 if !bytes.Equal(m, []byte("barz")) {
59 func TestSymmetric(t *testing.T) {
63 f := func(datum [][]byte) bool {
64 for _, data := range datum {
65 if n, err := w.WriteChunk(data); err != nil || n <= len(data) {
69 for _, data := range datum {
70 if n, err := r.Next(); err != nil || n != uint64(len(data)) {
73 got, err := io.ReadAll(r)
74 if err != nil || !bytes.Equal(got, data) {
80 if err := quick.Check(f, nil); err != nil {
85 func TestErrors(t *testing.T) {
86 b := bytes.NewBufferString("junk")
88 if _, err := r.Next(); err == nil {
92 b = bytes.NewBufferString("1111111111111111111111:")
94 if _, err := r.Next(); err == nil {
98 b = bytes.NewBufferString("6foobar")
100 if _, err := r.Next(); err == nil {
104 data := make([]byte, 1<<10)
106 b = bytes.NewBufferString("0:foobar,")
108 if _, err := r.Next(); err == nil {
112 b = bytes.NewBufferString("6:foobar")
114 if _, err := r.Next(); err != nil {
117 if _, err := r.Read(data); err == nil {
121 b = bytes.NewBufferString(":foobar,")
123 if _, err := r.Next(); err == nil {
127 b = bytes.NewBufferString("06:foobar,")
129 if _, err := r.Next(); err == nil {
134 func TestExample(t *testing.T) {
137 if n, err := w.WriteChunk([]byte("hello")); err != nil || n != 8 || b.String() != "5:hello," {
140 if n, err := w.WriteSize(6); err != nil || n != 2 {
143 if n, err := w.Write([]byte("wor")); err != nil || n != 3 {
146 if n, err := w.Write([]byte("ld!")); err != nil || n != 3 || b.String() != "5:hello,6:world!," {
150 if size, err := r.Next(); err != nil || size != 5 {
153 if err := r.Discard(); err != nil {
156 if size, err := r.Next(); err != nil || size != 6 {
159 if data, err := io.ReadAll(r); err != nil || string(data) != "world!" {