Fix rac.Writer with more than 510 leaf nodes
diff --git a/lib/rac/writer.go b/lib/rac/writer.go
index 610e331..b699120 100644
--- a/lib/rac/writer.go
+++ b/lib/rac/writer.go
@@ -21,6 +21,13 @@
 	"sort"
 )
 
+func btoi(b bool) int {
+	if b {
+		return 1
+	}
+	return 0
+}
+
 func isZeroOrAPowerOf2(x uint64) bool {
 	return (x & (x - 1)) == 0
 }
@@ -656,16 +663,16 @@
 		for ; j < len(nodes); j++ {
 			o := &nodes[j]
 
-			arity++
-			if (o.secondary != 0) && !resources[o.secondary] {
-				resources[o.secondary] = true
-				arity++
-			}
-			if (o.tertiary != 0) && !resources[o.tertiary] {
-				resources[o.tertiary] = true
-				arity++
-			}
+			new2 := (o.secondary != 0) && !resources[o.secondary]
+			new3 := (o.tertiary != 0) && !resources[o.tertiary]
+			arity += 1 + btoi(new2) + btoi(new3)
 			if arity <= 0xFF {
+				if new2 {
+					resources[o.secondary] = true
+				}
+				if new3 {
+					resources[o.tertiary] = true
+				}
 				continue
 			}
 
@@ -675,7 +682,15 @@
 			}
 
 			i = j
-			arity = 0
+			arity = 1
+			if o.secondary != 0 {
+				resources[o.secondary] = true
+				arity++
+			}
+			if o.tertiary != 0 {
+				resources[o.tertiary] = true
+				arity++
+			}
 		}
 
 		if i == 0 {
diff --git a/lib/rac/writer_test.go b/lib/rac/writer_test.go
index 2740fae..596c407 100644
--- a/lib/rac/writer_test.go
+++ b/lib/rac/writer_test.go
@@ -319,3 +319,22 @@
 		t.Fatalf("\ngot:\n%s\nwant:\n%s", got, want)
 	}
 }
+
+func TestWriter1000Chunks(t *testing.T) {
+	w := &Writer{
+		Writer: ioutil.Discard,
+		Codec:  fakeCodec,
+	}
+	data := make([]byte, 1)
+	res, _ := w.AddResource(data)
+	for i := 0; i < 1000; i++ {
+		if i == 2*255 {
+			_ = w.AddChunk(1, data, res, 0)
+		} else {
+			_ = w.AddChunk(1, data, 0, 0)
+		}
+	}
+	if err := w.Close(); err != nil {
+		t.Fatalf("Close: %v", err)
+	}
+}