1// Copyright 2015 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
5package big
6
7import (
8	"bytes"
9	"fmt"
10	"io"
11	"math/bits"
12	"strings"
13	"testing"
14)
15
16// log2 computes the integer binary logarithm of x.
17// The result is the integer n for which 2^n <= x < 2^(n+1).
18// If x == 0, the result is -1.
19func log2(x Word) int {
20	return bits.Len(uint(x)) - 1
21}
22
23func itoa(x nat, base int) []byte {
24	// special cases
25	switch {
26	case base < 2:
27		panic("illegal base")
28	case len(x) == 0:
29		return []byte("0")
30	}
31
32	// allocate buffer for conversion
33	i := x.bitLen()/log2(Word(base)) + 1 // +1: round up
34	s := make([]byte, i)
35
36	// don't destroy x
37	q := nat(nil).set(x)
38
39	// convert
40	for len(q) > 0 {
41		i--
42		var r Word
43		q, r = q.divW(q, Word(base))
44		s[i] = digits[r]
45	}
46
47	return s[i:]
48}
49
50var strTests = []struct {
51	x nat    // nat value to be converted
52	b int    // conversion base
53	s string // expected result
54}{
55	{nil, 2, "0"},
56	{nat{1}, 2, "1"},
57	{nat{0xc5}, 2, "11000101"},
58	{nat{03271}, 8, "3271"},
59	{nat{10}, 10, "10"},
60	{nat{1234567890}, 10, "1234567890"},
61	{nat{0xdeadbeef}, 16, "deadbeef"},
62	{nat{0x229be7}, 17, "1a2b3c"},
63	{nat{0x309663e6}, 32, "o9cov6"},
64}
65
66func TestString(t *testing.T) {
67	// test invalid base explicitly
68	var panicStr string
69	func() {
70		defer func() {
71			panicStr = recover().(string)
72		}()
73		natOne.utoa(1)
74	}()
75	if panicStr != "invalid base" {
76		t.Errorf("expected panic for invalid base")
77	}
78
79	for _, a := range strTests {
80		s := string(a.x.utoa(a.b))
81		if s != a.s {
82			t.Errorf("string%+v\n\tgot s = %s; want %s", a, s, a.s)
83		}
84
85		x, b, _, err := nat(nil).scan(strings.NewReader(a.s), a.b, false)
86		if x.cmp(a.x) != 0 {
87			t.Errorf("scan%+v\n\tgot z = %v; want %v", a, x, a.x)
88		}
89		if b != a.b {
90			t.Errorf("scan%+v\n\tgot b = %d; want %d", a, b, a.b)
91		}
92		if err != nil {
93			t.Errorf("scan%+v\n\tgot error = %s", a, err)
94		}
95	}
96}
97
98var natScanTests = []struct {
99	s     string // string to be scanned
100	base  int    // input base
101	frac  bool   // fraction ok
102	x     nat    // expected nat
103	b     int    // expected base
104	count int    // expected digit count
105	ok    bool   // expected success
106	next  rune   // next character (or 0, if at EOF)
107}{
108	// error: no mantissa
109	{},
110	{s: "?"},
111	{base: 10},
112	{base: 36},
113	{s: "?", base: 10},
114	{s: "0x"},
115	{s: "345", base: 2},
116
117	// error: incorrect use of decimal point
118	{s: ".0"},
119	{s: ".0", base: 10},
120	{s: ".", base: 0},
121	{s: "0x.0"},
122
123	// no errors
124	{"0", 0, false, nil, 10, 1, true, 0},
125	{"0", 10, false, nil, 10, 1, true, 0},
126	{"0", 36, false, nil, 36, 1, true, 0},
127	{"1", 0, false, nat{1}, 10, 1, true, 0},
128	{"1", 10, false, nat{1}, 10, 1, true, 0},
129	{"0 ", 0, false, nil, 10, 1, true, ' '},
130	{"08", 0, false, nil, 10, 1, true, '8'},
131	{"08", 10, false, nat{8}, 10, 2, true, 0},
132	{"018", 0, false, nat{1}, 8, 1, true, '8'},
133	{"0b1", 0, false, nat{1}, 2, 1, true, 0},
134	{"0b11000101", 0, false, nat{0xc5}, 2, 8, true, 0},
135	{"03271", 0, false, nat{03271}, 8, 4, true, 0},
136	{"10ab", 0, false, nat{10}, 10, 2, true, 'a'},
137	{"1234567890", 0, false, nat{1234567890}, 10, 10, true, 0},
138	{"xyz", 36, false, nat{(33*36+34)*36 + 35}, 36, 3, true, 0},
139	{"xyz?", 36, false, nat{(33*36+34)*36 + 35}, 36, 3, true, '?'},
140	{"0x", 16, false, nil, 16, 1, true, 'x'},
141	{"0xdeadbeef", 0, false, nat{0xdeadbeef}, 16, 8, true, 0},
142	{"0XDEADBEEF", 0, false, nat{0xdeadbeef}, 16, 8, true, 0},
143
144	// no errors, decimal point
145	{"0.", 0, false, nil, 10, 1, true, '.'},
146	{"0.", 10, true, nil, 10, 0, true, 0},
147	{"0.1.2", 10, true, nat{1}, 10, -1, true, '.'},
148	{".000", 10, true, nil, 10, -3, true, 0},
149	{"12.3", 10, true, nat{123}, 10, -1, true, 0},
150	{"012.345", 10, true, nat{12345}, 10, -3, true, 0},
151}
152
153func TestScanBase(t *testing.T) {
154	for _, a := range natScanTests {
155		r := strings.NewReader(a.s)
156		x, b, count, err := nat(nil).scan(r, a.base, a.frac)
157		if err == nil && !a.ok {
158			t.Errorf("scan%+v\n\texpected error", a)
159		}
160		if err != nil {
161			if a.ok {
162				t.Errorf("scan%+v\n\tgot error = %s", a, err)
163			}
164			continue
165		}
166		if x.cmp(a.x) != 0 {
167			t.Errorf("scan%+v\n\tgot z = %v; want %v", a, x, a.x)
168		}
169		if b != a.b {
170			t.Errorf("scan%+v\n\tgot b = %d; want %d", a, b, a.base)
171		}
172		if count != a.count {
173			t.Errorf("scan%+v\n\tgot count = %d; want %d", a, count, a.count)
174		}
175		next, _, err := r.ReadRune()
176		if err == io.EOF {
177			next = 0
178			err = nil
179		}
180		if err == nil && next != a.next {
181			t.Errorf("scan%+v\n\tgot next = %q; want %q", a, next, a.next)
182		}
183	}
184}
185
186var pi = "3" +
187	"14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651" +
188	"32823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461" +
189	"28475648233786783165271201909145648566923460348610454326648213393607260249141273724587006606315588174881520920" +
190	"96282925409171536436789259036001133053054882046652138414695194151160943305727036575959195309218611738193261179" +
191	"31051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798" +
192	"60943702770539217176293176752384674818467669405132000568127145263560827785771342757789609173637178721468440901" +
193	"22495343014654958537105079227968925892354201995611212902196086403441815981362977477130996051870721134999999837" +
194	"29780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083" +
195	"81420617177669147303598253490428755468731159562863882353787593751957781857780532171226806613001927876611195909" +
196	"21642019893809525720106548586327886593615338182796823030195203530185296899577362259941389124972177528347913151" +
197	"55748572424541506959508295331168617278558890750983817546374649393192550604009277016711390098488240128583616035" +
198	"63707660104710181942955596198946767837449448255379774726847104047534646208046684259069491293313677028989152104" +
199	"75216205696602405803815019351125338243003558764024749647326391419927260426992279678235478163600934172164121992" +
200	"45863150302861829745557067498385054945885869269956909272107975093029553211653449872027559602364806654991198818" +
201	"34797753566369807426542527862551818417574672890977772793800081647060016145249192173217214772350141441973568548" +
202	"16136115735255213347574184946843852332390739414333454776241686251898356948556209921922218427255025425688767179" +
203	"04946016534668049886272327917860857843838279679766814541009538837863609506800642251252051173929848960841284886" +
204	"26945604241965285022210661186306744278622039194945047123713786960956364371917287467764657573962413890865832645" +
205	"99581339047802759009946576407895126946839835259570982582262052248940772671947826848260147699090264013639443745" +
206	"53050682034962524517493996514314298091906592509372216964615157098583874105978859597729754989301617539284681382" +
207	"68683868942774155991855925245953959431049972524680845987273644695848653836736222626099124608051243884390451244" +
208	"13654976278079771569143599770012961608944169486855584840635342207222582848864815845602850601684273945226746767" +
209	"88952521385225499546667278239864565961163548862305774564980355936345681743241125150760694794510965960940252288" +
210	"79710893145669136867228748940560101503308617928680920874760917824938589009714909675985261365549781893129784821" +
211	"68299894872265880485756401427047755513237964145152374623436454285844479526586782105114135473573952311342716610" +
212	"21359695362314429524849371871101457654035902799344037420073105785390621983874478084784896833214457138687519435" +
213	"06430218453191048481005370614680674919278191197939952061419663428754440643745123718192179998391015919561814675" +
214	"14269123974894090718649423196156794520809514655022523160388193014209376213785595663893778708303906979207734672" +
215	"21825625996615014215030680384477345492026054146659252014974428507325186660021324340881907104863317346496514539" +
216	"05796268561005508106658796998163574736384052571459102897064140110971206280439039759515677157700420337869936007" +
217	"23055876317635942187312514712053292819182618612586732157919841484882916447060957527069572209175671167229109816" +
218	"90915280173506712748583222871835209353965725121083579151369882091444210067510334671103141267111369908658516398" +
219	"31501970165151168517143765761835155650884909989859982387345528331635507647918535893226185489632132933089857064" +
220	"20467525907091548141654985946163718027098199430992448895757128289059232332609729971208443357326548938239119325" +
221	"97463667305836041428138830320382490375898524374417029132765618093773444030707469211201913020330380197621101100" +
222	"44929321516084244485963766983895228684783123552658213144957685726243344189303968642624341077322697802807318915" +
223	"44110104468232527162010526522721116603966655730925471105578537634668206531098965269186205647693125705863566201" +
224	"85581007293606598764861179104533488503461136576867532494416680396265797877185560845529654126654085306143444318" +
225	"58676975145661406800700237877659134401712749470420562230538994561314071127000407854733269939081454664645880797" +
226	"27082668306343285878569830523580893306575740679545716377525420211495576158140025012622859413021647155097925923" +
227	"09907965473761255176567513575178296664547791745011299614890304639947132962107340437518957359614589019389713111" +
228	"79042978285647503203198691514028708085990480109412147221317947647772622414254854540332157185306142288137585043" +
229	"06332175182979866223717215916077166925474873898665494945011465406284336639379003976926567214638530673609657120" +
230	"91807638327166416274888800786925602902284721040317211860820419000422966171196377921337575114959501566049631862" +
231	"94726547364252308177036751590673502350728354056704038674351362222477158915049530984448933309634087807693259939" +
232	"78054193414473774418426312986080998886874132604721569516239658645730216315981931951673538129741677294786724229" +
233	"24654366800980676928238280689964004824354037014163149658979409243237896907069779422362508221688957383798623001" +
234	"59377647165122893578601588161755782973523344604281512627203734314653197777416031990665541876397929334419521541" +
235	"34189948544473456738316249934191318148092777710386387734317720754565453220777092120190516609628049092636019759" +
236	"88281613323166636528619326686336062735676303544776280350450777235547105859548702790814356240145171806246436267" +
237	"94561275318134078330336254232783944975382437205835311477119926063813346776879695970309833913077109870408591337"
238
239// Test case for BenchmarkScanPi.
240func TestScanPi(t *testing.T) {
241	var x nat
242	z, _, _, err := x.scan(strings.NewReader(pi), 10, false)
243	if err != nil {
244		t.Errorf("scanning pi: %s", err)
245	}
246	if s := string(z.utoa(10)); s != pi {
247		t.Errorf("scanning pi: got %s", s)
248	}
249}
250
251func TestScanPiParallel(t *testing.T) {
252	const n = 2
253	c := make(chan int)
254	for i := 0; i < n; i++ {
255		go func() {
256			TestScanPi(t)
257			c <- 0
258		}()
259	}
260	for i := 0; i < n; i++ {
261		<-c
262	}
263}
264
265func BenchmarkScanPi(b *testing.B) {
266	for i := 0; i < b.N; i++ {
267		var x nat
268		x.scan(strings.NewReader(pi), 10, false)
269	}
270}
271
272func BenchmarkStringPiParallel(b *testing.B) {
273	var x nat
274	x, _, _, _ = x.scan(strings.NewReader(pi), 0, false)
275	if string(x.utoa(10)) != pi {
276		panic("benchmark incorrect: conversion failed")
277	}
278	b.RunParallel(func(pb *testing.PB) {
279		for pb.Next() {
280			x.utoa(10)
281		}
282	})
283}
284
285func BenchmarkScan(b *testing.B) {
286	const x = 10
287	for _, base := range []int{2, 8, 10, 16} {
288		for _, y := range []Word{10, 100, 1000, 10000, 100000} {
289			if isRaceBuilder && y > 1000 {
290				continue
291			}
292			b.Run(fmt.Sprintf("%d/Base%d", y, base), func(b *testing.B) {
293				b.StopTimer()
294				var z nat
295				z = z.expWW(x, y)
296
297				s := z.utoa(base)
298				if t := itoa(z, base); !bytes.Equal(s, t) {
299					b.Fatalf("scanning: got %s; want %s", s, t)
300				}
301				b.StartTimer()
302
303				for i := 0; i < b.N; i++ {
304					z.scan(bytes.NewReader(s), base, false)
305				}
306			})
307		}
308	}
309}
310
311func BenchmarkString(b *testing.B) {
312	const x = 10
313	for _, base := range []int{2, 8, 10, 16} {
314		for _, y := range []Word{10, 100, 1000, 10000, 100000} {
315			if isRaceBuilder && y > 1000 {
316				continue
317			}
318			b.Run(fmt.Sprintf("%d/Base%d", y, base), func(b *testing.B) {
319				b.StopTimer()
320				var z nat
321				z = z.expWW(x, y)
322				z.utoa(base) // warm divisor cache
323				b.StartTimer()
324
325				for i := 0; i < b.N; i++ {
326					_ = z.utoa(base)
327				}
328			})
329		}
330	}
331}
332
333func BenchmarkLeafSize(b *testing.B) {
334	for n := 0; n <= 16; n++ {
335		b.Run(fmt.Sprint(n), func(b *testing.B) { LeafSizeHelper(b, 10, n) })
336	}
337	// Try some large lengths
338	for _, n := range []int{32, 64} {
339		b.Run(fmt.Sprint(n), func(b *testing.B) { LeafSizeHelper(b, 10, n) })
340	}
341}
342
343func LeafSizeHelper(b *testing.B, base, size int) {
344	b.StopTimer()
345	originalLeafSize := leafSize
346	resetTable(cacheBase10.table[:])
347	leafSize = size
348	b.StartTimer()
349
350	for d := 1; d <= 10000; d *= 10 {
351		b.StopTimer()
352		var z nat
353		z = z.expWW(Word(base), Word(d)) // build target number
354		_ = z.utoa(base)                 // warm divisor cache
355		b.StartTimer()
356
357		for i := 0; i < b.N; i++ {
358			_ = z.utoa(base)
359		}
360	}
361
362	b.StopTimer()
363	resetTable(cacheBase10.table[:])
364	leafSize = originalLeafSize
365	b.StartTimer()
366}
367
368func resetTable(table []divisor) {
369	if table != nil && table[0].bbb != nil {
370		for i := 0; i < len(table); i++ {
371			table[i].bbb = nil
372			table[i].nbits = 0
373			table[i].ndigits = 0
374		}
375	}
376}
377
378func TestStringPowers(t *testing.T) {
379	var p Word
380	for b := 2; b <= 16; b++ {
381		for p = 0; p <= 512; p++ {
382			x := nat(nil).expWW(Word(b), p)
383			xs := x.utoa(b)
384			xs2 := itoa(x, b)
385			if !bytes.Equal(xs, xs2) {
386				t.Errorf("failed at %d ** %d in base %d: %s != %s", b, p, b, xs, xs2)
387			}
388		}
389		if b >= 3 && testing.Short() {
390			break
391		}
392	}
393}
394