Best Go-testdeep code snippet using json.getRune
lex.go
Source:lex.go  
...136	if !j.skipWs() {137		return 0138	}139	j.lastTokenPos = j.pos140	r, _ := j.getRune()141	switch r {142	case '"':143		firstPos := j.pos.incHoriz(1)144		s, ok := j.parseString()145		if !ok {146			return 0147		}148		return j.analyzeStringContent(s, firstPos, lval)149	case 'r': // raw string, aka r!str! or r<str> (ws possible bw r & start delim)150		if !j.skipWs() {151			j.fatal("cannot find r start delimiter")152			return 0153		}154		firstPos := j.pos.incHoriz(1)155		s, ok := j.parseRawString()156		if !ok {157			return 0158		}159		return j.analyzeStringContent(s, firstPos, lval)160	case 'n': // null161		if j.remain() >= 4 && bytes.Equal(j.buf[j.pos.bpos+1:j.pos.bpos+4], []byte(`ull`)) {162			j.skip(3)163			lval.value = nil164			return NULL165		}166	case 't': // true167		if j.remain() >= 4 && bytes.Equal(j.buf[j.pos.bpos+1:j.pos.bpos+4], []byte(`rue`)) {168			j.skip(3)169			lval.value = true170			return TRUE171		}172	case 'f': // false173		if j.remain() >= 5 && bytes.Equal(j.buf[j.pos.bpos+1:j.pos.bpos+5], []byte(`alse`)) { //nolint: misspell174			j.skip(4)175			lval.value = false176			return FALSE177		}178	case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',179		'+', '.': // '+' & '.' are not normally accepted by JSON spec180		n, ok := j.parseNumber()181		if !ok {182			return 0183		}184		lval.value = n185		return NUMBER186	case '$':187		var dollarToken string188		end := bytes.IndexAny(j.buf[j.pos.bpos+1:], delimiters)189		if end >= 0 {190			dollarToken = string(j.buf[j.pos.bpos+1 : j.pos.bpos+1+end])191		} else {192			dollarToken = string(j.buf[j.pos.bpos+1:])193		}194		if dollarToken == "" {195			return '$'196		}197		token, value := j.parseDollarToken(dollarToken, j.pos, false)198		if token == OPERATOR {199			lval.string = value.(string)200			return OPERATOR201		}202		lval.value = value203		j.moveHoriz(1+len(dollarToken), 1+utf8.RuneCountInString(dollarToken))204		return token205	default:206		if r >= 'A' && r <= 'Z' {207			operator, ok := j.parseOperator()208			if !ok {209				return 0210			}211			j.pushPos(j.lastTokenPos)212			lval.string = operator213			return OPERATOR214		}215	}216	return int(r)217}218func hex(b []byte) (rune, bool) {219	var r rune220	for i := 0; i < 4; i++ {221		r <<= 4222		switch {223		case b[i] >= '0' && b[i] <= '9':224			r += rune(b[i]) - '0'225		case b[i] >= 'a' && b[i] <= 'f':226			r += rune(b[i]) - 'a' + 10227		case b[i] >= 'A' && b[i] <= 'F':228			r += rune(b[i]) - 'A' + 10229		default:230			return 0, false231		}232	}233	return r, true234}235func (j *json) parseString() (string, bool) {236	// j.buf[j.pos.bpos] == '"' â caller responsibility237	var b *strings.Builder238	from := j.pos.bpos + 1239	savePos := j.pos240	appendBuffer := func(r rune) {241		if b == nil {242			b = &strings.Builder{}243			b.Write(j.buf[from : j.pos.bpos-1])244		}245		b.WriteRune(r)246	}247str:248	for {249		r, ok := j.getRune()250		if !ok {251			break252		}253		switch r {254		case '"':255			if b == nil {256				return string(j.buf[from:j.pos.bpos]), true257			}258			return b.String(), true259		case '\\':260			r, ok := j.getRune()261			if !ok {262				break str263			}264			switch r {265			case '"', '\\', '/':266				appendBuffer(r)267			case 'b':268				appendBuffer('\b')269			case 'f':270				appendBuffer('\f')271			case 'n':272				appendBuffer('\n')273			case 'r':274				appendBuffer('\r')275			case 't':276				appendBuffer('\t')277			case 'u':278				if j.remain() >= 5 {279					r, ok = hex(j.buf[j.pos.bpos+1 : j.pos.bpos+5])280					if ok {281						appendBuffer(r)282						j.pos = j.pos.incHoriz(4)283						break284					}285				}286				fallthrough287			default:288				j.fatal("invalid escape sequence")289				return "", false290			}291		default: //nolint: gocritic292			if r < ' ' || r > utf8.MaxRune {293				j.fatal("invalid character in string")294				return "", false295			}296			fallthrough297		case '\n', '\r', '\t': // not normally accepted by JSON spec298			if b != nil {299				b.WriteRune(r)300			}301		}302	}303	j.fatal("unterminated string", savePos)304	return "", false305}306func (j *json) parseRawString() (string, bool) {307	// j.buf[j.pos.bpos] == first non-ws rune after 'r' â caller responsibility308	savePos := j.pos309	startDelim, _ := j.getRune() // cannot fail, caller called j.skipWs()310	var endDelim rune311	switch startDelim {312	case '(':313		endDelim = ')'314	case '{':315		endDelim = '}'316	case '[':317		endDelim = ']'318	case '<':319		endDelim = '>'320	default:321		if startDelim == '_' ||322			(!unicode.IsPunct(startDelim) && !unicode.IsSymbol(startDelim)) {323			j.fatal(fmt.Sprintf("invalid r delimiter %q, should be either a punctuation or a symbol rune, excluding '_'",324				startDelim))325			return "", false326		}327		endDelim = startDelim328	}329	from := j.pos.bpos + j.curSize330	for innerDelim := 0; ; {331		r, ok := j.getRune()332		if !ok {333			break334		}335		switch r {336		case startDelim:337			if startDelim == endDelim {338				return string(j.buf[from:j.pos.bpos]), true339			}340			innerDelim++341		case endDelim:342			if innerDelim == 0 {343				return string(j.buf[from:j.pos.bpos]), true344			}345			innerDelim--346		case '\n', '\r', '\t': // accept these raw bytes347		default:348			if r < ' ' || r > utf8.MaxRune {349				j.fatal("invalid character in raw string")350				return "", false351			}352		}353	}354	j.fatal("unterminated raw string", savePos)355	return "", false356}357// analyzeStringContent checks whether s contains $ prefix or not. If358// yes, it tries to parse it.359func (j *json) analyzeStringContent(s string, strPos Position, lval *yySymType) int {360	if len(s) <= 1 || !strings.HasPrefix(s, "$") {361		lval.string = s362		return STRING363	}364	// Double $$ at start of strings escape a $365	if strings.HasPrefix(s[1:], "$") {366		lval.string = s[1:]367		return STRING368	}369	// Check for placeholder ($1 or $name) or operator call as $^Empty370	// or $^Re(q<\d+>)371	token, value := j.parseDollarToken(s[1:], strPos, true)372	// in string, j.parseDollarToken can never return an OPERATOR373	// token. In case an operator is embedded in string, a SUB_PARSER is374	// returned instead.375	lval.value = value376	return token377}378const (379	numInt = 1 << iota380	numFloat381	numGoExt382)383var numBytes = [...]uint8{384	'+': numInt, '-': numInt,385	'0': numInt,386	'1': numInt,387	'2': numInt,388	'3': numInt,389	'4': numInt,390	'5': numInt,391	'6': numInt,392	'7': numInt,393	'8': numInt,394	'9': numInt,395	'_': numGoExt,396	// bases 2, 8, 16397	'b': numInt, 'B': numInt, 'o': numInt, 'O': numInt, 'x': numInt, 'X': numInt,398	'a': numInt, 'A': numInt,399	'c': numInt, 'C': numInt,400	'd': numInt, 'D': numInt,401	'e': numInt | numFloat, 'E': numInt | numFloat,402	'f': numInt, 'F': numInt,403	// floats404	'.': numFloat, 'p': numFloat, 'P': numFloat,405}406func (j *json) parseNumber() (float64, bool) {407	// j.buf[j.pos.bpos] == '[-+0-9.]' â caller responsibility408	numKind := numBytes[j.buf[j.pos.bpos]]409	i := j.pos.bpos + 1410	for l := len(j.buf); i < l; i++ {411		b := int(j.buf[i])412		if b >= len(numBytes) || numBytes[b] == 0 {413			break414		}415		numKind |= numBytes[b]416	}417	s := string(j.buf[j.pos.bpos:i])418	var (419		f   float64420		err error421	)422	// Differentiate float/int parsing to accept old octal notation:423	// 0600 â 384 as int64, but 600 as float64424	if (numKind & numFloat) != 0 {425		// strconv.ParseFloat does not handle "_"426		var bf *big.Float427		bf, _, err = new(big.Float).Parse(s, 0)428		if err == nil {429			f, _ = bf.Float64()430		}431	} else { // numInt and/or numGoExt432		var int int64433		int, err = strconv.ParseInt(s, 0, 64)434		if err == nil {435			f = float64(int)436		}437	}438	if err != nil {439		j.fatal("invalid number")440		return 0, false441	}442	j.curSize = 0443	j.pos = j.pos.incHoriz(i - j.pos.bpos)444	return f, true445}446// parseDollarToken parses a $123 or $tag or $^Operator or447// $^Operator(PARAMSâ¦) token. dollarToken is never empty, does not448// contain '$' and dollarPos is the '$' position.449func (j *json) parseDollarToken(dollarToken string, dollarPos Position, inString bool) (int, any) {450	firstRune, _ := utf8.DecodeRuneInString(dollarToken)451	// Test for $123452	if firstRune >= '0' && firstRune <= '9' {453		np, err := strconv.ParseUint(dollarToken, 10, 64)454		if err != nil {455			j.error("invalid numeric placeholder", dollarPos)456			return PLACEHOLDER, nil // continue parsing457		}458		if np == 0 {459			j.error(460				fmt.Sprintf(`invalid numeric placeholder "$%s", it should start at "$1"`, dollarToken),461				dollarPos)462			return PLACEHOLDER, nil // continue parsing463		}464		if numParams := len(j.opts.Placeholders); np > uint64(numParams) {465			switch numParams {466			case 0:467				j.error(468					fmt.Sprintf(`numeric placeholder "$%s", but no params given`, dollarToken),469					dollarPos)470			case 1:471				j.error(472					fmt.Sprintf(`numeric placeholder "$%s", but only one param given`, dollarToken),473					dollarPos)474			default:475				j.error(476					fmt.Sprintf(`numeric placeholder "$%s", but only %d params given`,477						dollarToken, numParams),478					dollarPos)479			}480			return PLACEHOLDER, nil // continue parsing481		}482		return PLACEHOLDER, j.opts.Placeholders[np-1]483	}484	// Test for operator call $^Operator or $^Operator(â¦)485	if firstRune == '^' {486		nextRune, _ := utf8.DecodeRuneInString(dollarToken[1:])487		if nextRune < 'A' || nextRune > 'Z' {488			j.error(`$^ must be followed by an operator name`, dollarPos)489			if inString {490				return SUB_PARSER, nil // continue parsing491			}492			return OPERATOR, "" // continue parsing493		}494		if inString {495			jr := json{496				buf: []byte(dollarToken[1:]),497				pos: Position{498					Pos:  dollarPos.Pos + 2,499					Line: dollarPos.Line,500					Col:  dollarPos.Col + 2,501				},502				opts: j.opts,503			}504			if !jr.parse() {505				j.errs = append(j.errs, jr.errs...)506				return SUB_PARSER, nil // continue parsing507			}508			return SUB_PARSER, jr.value509		}510		j.moveHoriz(2)511		j.lastTokenPos = j.pos512		operator, ok := j.parseOperator()513		if !ok {514			return OPERATOR, ""515		}516		j.pushPos(j.lastTokenPos)517		return OPERATOR, operator518	}519	// Test for $tag520	err := util.CheckTag(dollarToken)521	if err != nil {522		j.error(523			fmt.Sprintf(`bad placeholder "$%s"`, dollarToken),524			dollarPos)525		return PLACEHOLDER, nil // continue parsing526	}527	op, ok := j.opts.PlaceholdersByName[dollarToken]528	if !ok {529		j.error(530			fmt.Sprintf(`unknown placeholder "$%s"`, dollarToken),531			dollarPos)532		// continue parsing533	}534	return PLACEHOLDER, op535}536func (j *json) parseOperator() (string, bool) {537	// j.buf[j.pos.bpos] == '[A-Z]' â caller responsibility538	i := j.pos.bpos + 1539	l := len(j.buf)540	for ; i < l; i++ {541		if bytes.ContainsAny(j.buf[i:i+1], delimiters) {542			break543		}544		if r := j.buf[i]; (r < 'A' || r > 'Z') && (r < 'a' || r > 'z') {545			j.fatal(fmt.Sprintf(`invalid operator name %q`, string(j.buf[j.pos.bpos:i+1])))546			j.moveHoriz(i - j.pos.bpos)547			return "", false548		}549	}550	s := string(j.buf[j.pos.bpos:i])551	j.moveHoriz(i - j.pos.bpos)552	return s, true553}554func (j *json) skipWs() bool {555ws:556	for {557		r, ok := j.getRune()558		if !ok {559			return false560		}561		switch r {562		case ' ', '\n', '\r', '\t':563		case '/':564			if j.remain() < 2 {565				break ws566			}567			switch j.buf[j.pos.bpos+1] {568			case '/': // comment till eol569				j.curSize = 0570				if end := indexAfterEol(j.buf[j.pos.bpos+2:]); end >= 0 {571					lineLen := 2 + utf8.RuneCount(j.buf[j.pos.bpos+2:j.pos.bpos+2+end])572					j.pos.Pos += lineLen573					j.pos.Line++574					j.pos.Col = 0575					j.pos.bpos += 2 + end576					continue ws577				}578				lineLen := 2 + utf8.RuneCount(j.buf[j.pos.bpos+2:])579				j.pos.Pos += lineLen580				j.pos.Col += lineLen581				j.pos.bpos = len(j.buf) // till eof582				return false583			case '*': // multi-lines comment584				j.curSize = 0585				if end := bytes.Index(j.buf[j.pos.bpos+2:], []byte("*/")); end >= 0 {586					comment := j.buf[j.pos.bpos+2 : j.pos.bpos+2+end]587					commentLen := 4 + utf8.RuneCount(comment)588					// Count \r\n as only one rune589					if crnl := bytes.Count(comment, []byte("\r\n")); crnl > 0 {590						commentLen -= crnl591					}592					j.pos.Pos += commentLen593					j.pos.bpos += 4 + end594					nLines := countEol(comment)595					if nLines > 0 {596						j.pos.Line += nLines597						j.pos.Col = len(comment) - bytes.LastIndexAny(comment, "\r\n") + 1598					} else {599						j.pos.Col += commentLen600					}601					continue ws602				}603				j.fatal("multi-lines comment not terminated")604				return false605			default:606				break ws607			}608		default:609			break ws610		}611	}612	j.curSize = 0613	return true614}615// indexAfterEol returns the index of the byte just after the first616// instance of an end-of-line ('\n' alone, '\r' alone or "\r\n") in617// buf, or -1 if no end-of-line is found.618func indexAfterEol(buf []byte) int {619	// new line for:620	// - \n alone621	// - \r\n622	// - \r alone623	for i, b := range buf {624		switch b {625		case '\n':626			return i + 1627		case '\r':628			if i+1 == len(buf) || buf[i+1] != '\n' {629				return i + 1630			}631			return i + 2632		}633	}634	return -1635}636// countEol returns the number of end-of-line ('\n' alone, '\r' alone637// or "\r\n") occurrences in buf.638func countEol(buf []byte) int {639	// new line for:640	// - \n alone641	// - \r\n642	// - \r alone643	num := 0644	for {645		eol := indexAfterEol(buf)646		if eol < 0 {647			return num648		}649		buf = buf[eol:]650		num++651	}652}653func (j *json) getRune() (rune, bool) {654	if j.curSize > 0 {655		// new line for:656		// - \n alone657		// - \r\n (+ consider it as one rune)658		// - \r alone659		switch j.buf[j.pos.bpos] {660		case '\n':661			if j.pos.bpos > 0 && j.buf[j.pos.bpos-1] == '\r' {662				// \r\n â already handled663				break664			}665			fallthrough666		case '\r':667			j.pos.Line++...pointer_test.go
Source:pointer_test.go  
1package pointer2import (3	"encoding/json"4	"errors"5	"fmt"6	"testing"7	"time"8)9/*10Order as in spec:11	bool byte complex64 complex128 error float32 float6412	int int8 int16 int32 int64 rune string13	uint uint8 uint16 uint32 uint64 uintptr14	time.Duration time.Time15*/16func TestBool(t *testing.T) {17	var x bool18	if *ToBool(x) != x {19		t.Errorf("*ToBool(%v)", x)20	}21	if ToBoolOrNil(x) != nil {22		t.Errorf("ToBoolOrNil(%v)", x)23	}24	if GetBool(nil) != x {25		t.Errorf("GetBool(%v)", nil)26	}27	x = true28	if *ToBool(x) != x {29		t.Errorf("*ToBool(%v)", x)30	}31	if *ToBoolOrNil(x) != x {32		t.Errorf("*ToBoolOrNil(%v)", x)33	}34	if GetBool(&x) != x {35		t.Errorf("GetBool(%v)", &x)36	}37}38func TestByte(t *testing.T) {39	var x byte40	if *ToByte(x) != x {41		t.Errorf("*ToByte(%v)", x)42	}43	if ToByteOrNil(x) != nil {44		t.Errorf("ToByteOrNil(%v)", x)45	}46	if GetByte(nil) != x {47		t.Errorf("GetByte(%v)", nil)48	}49	x = 4250	if *ToByte(x) != x {51		t.Errorf("*ToByte(%v)", x)52	}53	if *ToByteOrNil(x) != x {54		t.Errorf("*ToByteOrNil(%v)", x)55	}56	if GetByte(&x) != x {57		t.Errorf("GetByte(%v)", &x)58	}59}60func TestComplex64(t *testing.T) {61	var x complex6462	if *ToComplex64(x) != x {63		t.Errorf("*ToComplex64(%v)", x)64	}65	if ToComplex64OrNil(x) != nil {66		t.Errorf("ToComplex64OrNil(%v)", x)67	}68	if GetComplex64(nil) != x {69		t.Errorf("GetComplex64(%v)", nil)70	}71	x = 4272	if *ToComplex64(x) != x {73		t.Errorf("*ToComplex64(%v)", x)74	}75	if *ToComplex64OrNil(x) != x {76		t.Errorf("*ToComplex64OrNil(%v)", x)77	}78	if GetComplex64(&x) != x {79		t.Errorf("GetComplex64(%v)", &x)80	}81}82func TestComplex128(t *testing.T) {83	var x complex12884	if *ToComplex128(x) != x {85		t.Errorf("*ToComplex128(%v)", x)86	}87	if ToComplex128OrNil(x) != nil {88		t.Errorf("ToComplex128OrNil(%v)", x)89	}90	if GetComplex128(nil) != x {91		t.Errorf("GetComplex128(%v)", nil)92	}93	x = 4294	if *ToComplex128(x) != x {95		t.Errorf("*ToComplex128(%v)", x)96	}97	if *ToComplex128OrNil(x) != x {98		t.Errorf("*ToComplex128OrNil(%v)", x)99	}100	if GetComplex128(&x) != x {101		t.Errorf("GetComplex128(%v)", &x)102	}103}104func TestError(t *testing.T) {105	var x error106	if *ToError(x) != x {107		t.Errorf("*ToError(%v)", x)108	}109	if ToErrorOrNil(x) != nil {110		t.Errorf("ToErrorOrNil(%v)", x)111	}112	if GetError(nil) != x {113		t.Errorf("GetError(%v)", nil)114	}115	x = errors.New("error")116	if *ToError(x) != x {117		t.Errorf("*ToError(%v)", x)118	}119	if *ToErrorOrNil(x) != x {120		t.Errorf("*ToErrorOrNil(%v)", x)121	}122	if GetError(&x) != x {123		t.Errorf("GetError(%v)", &x)124	}125}126func TestFloat32(t *testing.T) {127	var x float32128	if *ToFloat32(x) != x {129		t.Errorf("*ToFloat32(%v)", x)130	}131	if ToFloat32OrNil(x) != nil {132		t.Errorf("ToFloat32OrNil(%v)", x)133	}134	if GetFloat32(nil) != x {135		t.Errorf("GetFloat32(%v)", nil)136	}137	x = 42138	if *ToFloat32(x) != x {139		t.Errorf("*ToFloat32(%v)", x)140	}141	if *ToFloat32OrNil(x) != x {142		t.Errorf("*ToFloat32OrNil(%v)", x)143	}144	if GetFloat32(&x) != x {145		t.Errorf("GetFloat32(%v)", &x)146	}147}148func TestFloat64(t *testing.T) {149	var x float64150	if *ToFloat64(x) != x {151		t.Errorf("*ToFloat64(%v)", x)152	}153	if ToFloat64OrNil(x) != nil {154		t.Errorf("ToFloat64OrNil(%v)", x)155	}156	if GetFloat64(nil) != x {157		t.Errorf("GetFloat64(%v)", nil)158	}159	x = 42160	if *ToFloat64(x) != x {161		t.Errorf("*ToFloat64(%v)", x)162	}163	if *ToFloat64OrNil(x) != x {164		t.Errorf("*ToFloat64OrNil(%v)", x)165	}166	if GetFloat64(&x) != x {167		t.Errorf("GetFloat64(%v)", &x)168	}169}170func TestInt(t *testing.T) {171	var x int172	if *ToInt(x) != x {173		t.Errorf("*ToInt(%v)", x)174	}175	if ToIntOrNil(x) != nil {176		t.Errorf("ToIntOrNil(%v)", x)177	}178	if GetInt(nil) != x {179		t.Errorf("GetInt(%v)", nil)180	}181	x = 42182	if *ToInt(x) != x {183		t.Errorf("*ToInt(%v)", x)184	}185	if *ToIntOrNil(x) != x {186		t.Errorf("*ToIntOrNil(%v)", x)187	}188	if GetInt(&x) != x {189		t.Errorf("GetInt(%v)", &x)190	}191}192func TestInt8(t *testing.T) {193	var x int8194	if *ToInt8(x) != x {195		t.Errorf("*ToInt8(%v)", x)196	}197	if ToInt8OrNil(x) != nil {198		t.Errorf("ToInt8OrNil(%v)", x)199	}200	if GetInt8(nil) != x {201		t.Errorf("GetInt8(%v)", nil)202	}203	x = 42204	if *ToInt8(x) != x {205		t.Errorf("*ToInt8(%v)", x)206	}207	if *ToInt8OrNil(x) != x {208		t.Errorf("*ToInt8OrNil(%v)", x)209	}210	if GetInt8(&x) != x {211		t.Errorf("GetInt8(%v)", &x)212	}213}214func TestInt16(t *testing.T) {215	var x int16216	if *ToInt16(x) != x {217		t.Errorf("*ToInt16(%v)", x)218	}219	if ToInt16OrNil(x) != nil {220		t.Errorf("ToInt16OrNil(%v)", x)221	}222	if GetInt16(nil) != x {223		t.Errorf("GetInt16(%v)", nil)224	}225	x = 42226	if *ToInt16(x) != x {227		t.Errorf("*ToInt16(%v)", x)228	}229	if *ToInt16OrNil(x) != x {230		t.Errorf("*ToInt16OrNil(%v)", x)231	}232	if GetInt16(&x) != x {233		t.Errorf("GetInt16(%v)", &x)234	}235}236func TestInt32(t *testing.T) {237	var x int32238	if *ToInt32(x) != x {239		t.Errorf("*ToInt32(%v)", x)240	}241	if ToInt32OrNil(x) != nil {242		t.Errorf("ToInt32OrNil(%v)", x)243	}244	if GetInt32(nil) != x {245		t.Errorf("GetInt32(%v)", nil)246	}247	x = 42248	if *ToInt32(x) != x {249		t.Errorf("*ToInt32(%v)", x)250	}251	if *ToInt32OrNil(x) != x {252		t.Errorf("*ToInt32OrNil(%v)", x)253	}254	if GetInt32(&x) != x {255		t.Errorf("GetInt32(%v)", &x)256	}257}258func TestInt64(t *testing.T) {259	var x int64260	if *ToInt64(x) != x {261		t.Errorf("*ToInt64(%v)", x)262	}263	if ToInt64OrNil(x) != nil {264		t.Errorf("ToInt64OrNil(%v)", x)265	}266	if GetInt64(nil) != x {267		t.Errorf("GetInt64(%v)", nil)268	}269	x = 42270	if *ToInt64(x) != x {271		t.Errorf("*ToInt64(%v)", x)272	}273	if *ToInt64OrNil(x) != x {274		t.Errorf("*ToInt64OrNil(%v)", x)275	}276	if GetInt64(&x) != x {277		t.Errorf("GetInt64(%v)", &x)278	}279}280func TestRune(t *testing.T) {281	var x rune282	if *ToRune(x) != x {283		t.Errorf("*ToRune(%v)", x)284	}285	if ToRuneOrNil(x) != nil {286		t.Errorf("ToRuneOrNil(%v)", x)287	}288	if GetRune(nil) != x {289		t.Errorf("GetRune(%v)", nil)290	}291	x = 'x'292	if *ToRune(x) != x {293		t.Errorf("*ToRune(%v)", x)294	}295	if *ToRuneOrNil(x) != x {296		t.Errorf("*ToRuneOrNil(%v)", x)297	}298	if GetRune(&x) != x {299		t.Errorf("GetRune(%v)", &x)300	}301}302func TestString(t *testing.T) {303	var x string304	if *ToString(x) != x {305		t.Errorf("*ToString(%v)", x)306	}307	if ToStringOrNil(x) != nil {308		t.Errorf("ToStringOrNil(%v)", x)309	}310	if GetString(nil) != x {311		t.Errorf("GetString(%v)", nil)312	}313	x = "x"314	if *ToString(x) != x {315		t.Errorf("*ToString(%v)", x)316	}317	if *ToStringOrNil(x) != x {318		t.Errorf("*ToStringOrNil(%v)", x)319	}320	if GetString(&x) != x {321		t.Errorf("GetString(%v)", &x)322	}323}324func TestUint(t *testing.T) {325	var x uint326	if *ToUint(x) != x {327		t.Errorf("*ToUint(%v)", x)328	}329	if ToUintOrNil(x) != nil {330		t.Errorf("ToUintOrNil(%v)", x)331	}332	if GetUint(nil) != x {333		t.Errorf("GetUint(%v)", nil)334	}335	x = 42336	if *ToUint(x) != x {337		t.Errorf("*ToUint(%v)", x)338	}339	if *ToUintOrNil(x) != x {340		t.Errorf("*ToUintOrNil(%v)", x)341	}342	if GetUint(&x) != x {343		t.Errorf("GetUint(%v)", &x)344	}345}346func TestUint8(t *testing.T) {347	var x uint8348	if *ToUint8(x) != x {349		t.Errorf("*ToUint8(%v)", x)350	}351	if ToUint8OrNil(x) != nil {352		t.Errorf("ToUint8OrNil(%v)", x)353	}354	if GetUint8(nil) != x {355		t.Errorf("GetUint8(%v)", nil)356	}357	x = 42358	if *ToUint8(x) != x {359		t.Errorf("*ToUint8(%v)", x)360	}361	if *ToUint8OrNil(x) != x {362		t.Errorf("*ToUint8OrNil(%v)", x)363	}364	if GetUint8(&x) != x {365		t.Errorf("GetUint8(%v)", &x)366	}367}368func TestUint16(t *testing.T) {369	var x uint16370	if *ToUint16(x) != x {371		t.Errorf("*ToUint16(%v)", x)372	}373	if ToUint16OrNil(x) != nil {374		t.Errorf("ToUint16OrNil(%v)", x)375	}376	if GetUint16(nil) != x {377		t.Errorf("GetUint16(%v)", nil)378	}379	x = 42380	if *ToUint16(x) != x {381		t.Errorf("*ToUint16(%v)", x)382	}383	if *ToUint16OrNil(x) != x {384		t.Errorf("*ToUint16OrNil(%v)", x)385	}386	if GetUint16(&x) != x {387		t.Errorf("GetUint16(%v)", &x)388	}389}390func TestUint32(t *testing.T) {391	var x uint32392	if *ToUint32(x) != x {393		t.Errorf("*ToUint32(%v)", x)394	}395	if ToUint32OrNil(x) != nil {396		t.Errorf("ToUint32OrNil(%v)", x)397	}398	if GetUint32(nil) != x {399		t.Errorf("GetUint32(%v)", nil)400	}401	x = 42402	if *ToUint32(x) != x {403		t.Errorf("*ToUint32(%v)", x)404	}405	if *ToUint32OrNil(x) != x {406		t.Errorf("*ToUint32OrNil(%v)", x)407	}408	if GetUint32(&x) != x {409		t.Errorf("GetUint32(%v)", &x)410	}411}412func TestUint64(t *testing.T) {413	var x uint64414	if *ToUint64(x) != x {415		t.Errorf("*ToUint64(%v)", x)416	}417	if ToUint64OrNil(x) != nil {418		t.Errorf("ToUint64OrNil(%v)", x)419	}420	if GetUint64(nil) != x {421		t.Errorf("GetUint64(%v)", nil)422	}423	x = 42424	if *ToUint64(x) != x {425		t.Errorf("*ToUint64(%v)", x)426	}427	if *ToUint64OrNil(x) != x {428		t.Errorf("*ToUint64OrNil(%v)", x)429	}430	if GetUint64(&x) != x {431		t.Errorf("GetUint64(%v)", &x)432	}433}434func TestUintptr(t *testing.T) {435	var x uintptr436	if *ToUintptr(x) != x {437		t.Errorf("*ToUintptr(%v)", x)438	}439	if ToUintptrOrNil(x) != nil {440		t.Errorf("ToUintptrOrNil(%v)", x)441	}442	if GetUintptr(nil) != x {443		t.Errorf("GetUintptr(%v)", nil)444	}445	x = 42446	if *ToUintptr(x) != x {447		t.Errorf("*ToUintptr(%v)", x)448	}449	if *ToUintptrOrNil(x) != x {450		t.Errorf("*ToUintptrOrNil(%v)", x)451	}452	if GetUintptr(&x) != x {453		t.Errorf("GetUintptr(%v)", &x)454	}455}456func TestDuration(t *testing.T) {457	var x time.Duration458	if *ToDuration(x) != x {459		t.Errorf("*ToDuration(%v)", x)460	}461	if ToDurationOrNil(x) != nil {462		t.Errorf("ToDurationOrNil(%v)", x)463	}464	if GetDuration(nil) != x {465		t.Errorf("GetDuration(%v)", nil)466	}467	x = time.Second468	if *ToDuration(x) != x {469		t.Errorf("*ToDuration(%v)", x)470	}471	if *ToDurationOrNil(x) != x {472		t.Errorf("*ToDurationOrNil(%v)", x)473	}474	if GetDuration(&x) != x {475		t.Errorf("GetDuration(%v)", &x)476	}477}478func TestTime(t *testing.T) {479	var x time.Time480	if *ToTime(x) != x {481		t.Errorf("*ToTime(%v)", x)482	}483	if ToTimeOrNil(x) != nil {484		t.Errorf("ToTimeOrNil(%v)", x)485	}486	if GetTime(nil) != x {487		t.Errorf("GetTime(%v)", nil)488	}489	x = time.Date(2014, 6, 25, 12, 24, 40, 0, time.UTC)490	if *ToTime(x) != x {491		t.Errorf("*ToTime(%v)", x)492	}493	if *ToTimeOrNil(x) != x {494		t.Errorf("*ToTimeOrNil(%v)", x)495	}496	if GetTime(&x) != x {497		t.Errorf("GetTime(%v)", &x)498	}499}500func Example() {501	const (502		defaultName = "some name"503	)504	// Stuff contains optional fields.505	type Stuff struct {506		Name    *string507		Comment *string508		Value   *int64509		Time    *time.Time510	}511	b, _ := json.Marshal(&Stuff{512		Name:    ToString(defaultName),                                   // can't say &defaultName513		Comment: ToString("not yet"),                                     // can't say &"not yet"514		Value:   ToInt64(42),                                             // can't say &42 or &int64(42)515		Time:    ToTime(time.Date(2014, 6, 25, 12, 24, 40, 0, time.UTC)), // can't say &time.Date(â¦)516	})517	fmt.Printf("%s", b)518	// Output: {"Name":"some name","Comment":"not yet","Value":42,"Time":"2014-06-25T12:24:40Z"}519}...apis.go
Source:apis.go  
...143	ctx.SetUserValue("_envelope_data", r)144	return145}146*/147func getRune(mode, input string) (rune, error) {148	var (149		u    int64150		r    rune151		size int152		err  error153	)154	switch mode {155	case "u":156		u, err = strconv.ParseInt(input, 16, 32)157		r = rune(u)158	case "d":159		u, err = strconv.ParseInt(input, 10, 32)160		r = rune(u)161	case "c":162		u, _ := url.QueryUnescape(input)163		r, size = utf8.DecodeRuneInString(u)164		if size == 0 {165			err = errors.New("Invalid input")166		}167	default:168		err = errors.New("Invalid mode")169	}170	return r, err171}172func apiUnihan(ctx *fasthttp.RequestCtx) {173	var (174		mode  = ctx.UserValue("mode").(string)175		input = ctx.UserValue("input").(string)176		r     rune177		h     *unihan.HanCharacter178		err   error179	)180	r, err = getRune(mode, input)181	h, err = unihan.Query(r)182	if err != nil || h == nil {183		ctx.SetUserValue("_envelope_code", 10404)184		ctx.SetUserValue("_envelope_message", "Unihan does not exists")185		ctx.SetStatusCode(fasthttp.StatusNotFound)186		return187	}188	ctx.SetUserValue("_envelope_data", h)189	return190}191func apiStroke(ctx *fasthttp.RequestCtx) {192	var (193		mode  = ctx.UserValue("mode").(string)194		input = ctx.UserValue("input").(string)195		r     rune196		h     *unihan.HanCharacter197		err   error198	)199	r, err = getRune(mode, input)200	h, err = unihan.Query(r)201	if err != nil || h == nil {202		ctx.SetUserValue("_envelope_code", 10404)203		ctx.SetUserValue("_envelope_message", "Unihan does not exists")204		ctx.SetStatusCode(fasthttp.StatusNotFound)205		return206	}207	ks, us, s, _ := h.QueryStroke()208	ctx.SetUserValue("_envelope_data", map[string]int{209		"stroke":         s,210		"unicode_stroke": us,211		"kangxi_stroke":  ks,212	})213	return214}215func apiTraditional(ctx *fasthttp.RequestCtx) {216	var (217		mode  = ctx.UserValue("mode").(string)218		input = ctx.UserValue("input").(string)219		r     rune220		h     *unihan.HanCharacter221		err   error222	)223	r, err = getRune(mode, input)224	h, err = unihan.Query(r)225	if err != nil || h == nil {226		ctx.SetUserValue("_envelope_code", 10404)227		ctx.SetUserValue("_envelope_message", "Unihan does not exists")228		ctx.SetStatusCode(fasthttp.StatusNotFound)229		return230	}231	tsi, _ := h.QueryTraditional()232	ctx.SetUserValue("_envelope_data", tsi)233}234/*235 * Local variables:236 * tab-width: 4237 * c-basic-offset: 4...getRune
Using AI Code Generation
1import (2func main() {3	var jsonBlob = []byte(`[4    {"Name": "Platypus", "Order": "Monotremata"},5    {"Name": "Quoll",    "Order": "Dasyuromorphia"}6	type Animal struct {7	}8	err := json.Unmarshal(jsonBlob, &animals)9	if err != nil {10		fmt.Println("error:", err)11	}12	fmt.Printf("%+v13}14[ {Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia} ]15import (16func main() {17	var jsonBlob = []byte(`[18    {"Name": "Platypus", "Order": "Monotremata"},19    {"Name": "Quoll",    "Order": "Dasyuromorphia"}20	type Animal struct {21	}22	err := json.Unmarshal(jsonBlob, &animals)23	if err != nil {24		fmt.Println("error:", err)25	}26	fmt.Printf("%+v27	fmt.Println(string(jsonBlob))28	fmt.Println("The Unicode code point at the specified index is:", jsonBlob[1])29}30[ {Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia} ]31    {"Name": "Platypus", "Order": "Monotremata"},32    {"Name": "Quoll",    "Order": "Dasyuromorphia"}getRune
Using AI Code Generation
1import (2func main() {3    for len(s) > 0 {4        r, size := utf8.DecodeRuneInString(s)5        fmt.Printf("%c %v6    }7}8Your name to display (optional):9Your name to display (optional):10Syntax: func (enc *Encoder) getRune(index int) (rune, int)11import (12func main() {13    for len(s) > 0 {14        r, size := json.getRune(s)15        fmt.Printf("%c %v16    }17}18Your name to display (optional):getRune
Using AI Code Generation
1import (2func main() {3    var r = json.GetRune(s, 1)4    fmt.Println(r)5}6func (s String) Append(a ...String) String7func (s String) AppendByte(a byte) String8func (s String) AppendRune(a rune) String9func (s String) AppendString(a string) String10func (s String) Compare(t String) int11func (s String) Contains(substr String) bool12func (s String) ContainsAny(chars String) bool13func (s String) ContainsRune(r rune) bool14func (s String) Count(sep String) int15func (s String) EqualFold(t String) bool16func (s String) HasPrefix(prefix String) bool17func (s String) HasSuffix(suffix String) bool18func (s String) Index(sep String) int19func (s String) IndexAny(chars String) int20func (s String) IndexByte(c byte) int21func (s String) IndexFunc(f func(rune) bool) int22func (s String) IndexRune(r rune) int23func (s String) LastIndex(sep String) int24func (s String) LastIndexAny(chars String) int25func (s String) LastIndexByte(c byte) int26func (s String) LastIndexFunc(f func(rune) bool) int27func (s String) Repeat(count int) String28func (s String) Replace(old, new String, n int) String29func (s String) Split(sep String) []String30func (s String) SplitAfter(sep String) []String31func (s String) SplitAfterN(sep String, n int) []String32func (s String) SplitN(sep String, n int) []String33func (s String) Title() String34func (s String) ToLower() String35func (sgetRune
Using AI Code Generation
1import "fmt"2import "encoding/json"3func main() {4    for _, r := range str {5        result = append(result, r)6    }7    fmt.Println(result)8    fmt.Println(string(result))9}10import "fmt"11import "encoding/json"12func main() {13    for _, r := range str {14        result = append(result, r)15    }16    fmt.Println(result)17    fmt.Println(string(result))18}19import "fmt"20import "encoding/json"21func main() {22    for _, r := range str {23        result = append(result, r)24    }25    fmt.Println(result)26    fmt.Println(string(result))27}getRune
Using AI Code Generation
1import (2func main() {3    f, err := os.Open("test.json")4    if err != nil {5        fmt.Println(err)6    }7    defer f.Close()8    r := json.NewDecoder(f)9    for {10        c, err := r.ReadRune()11        if err == io.EOF {12        }13        if err != nil {14            fmt.Println(err)15        }16        fmt.Println(string(c))17    }18}19{20{21}22}getRune
Using AI Code Generation
1func getRune() rune {2    r = json.GetRune()3}4func putRune(r rune) {5    json.PutRune(r)6}7func getChar() byte {8    c = json.GetChar()9}10func putChar(c byte) {11    json.PutChar(c)12}13func getBool() bool {14    b = json.GetBool()15}16func putBool(b bool) {17    json.PutBool(b)18}19func getFloat() float64 {20    f = json.GetFloat()21}22func putFloat(f float64) {23    json.PutFloat(f)24}25func getInt() int64 {26    i = json.GetInt()27}28func putInt(i int64) {29    json.PutInt(i)30}31func getString() string {32    s = json.GetString()33}getRune
Using AI Code Generation
1json.getRune(0);2return 0;3}4You have to import the package for the getRune method:5import kotlin.text.getRune6import kotlin.text.getRune7fun main(args: Array<String>) {8    println(json.getRune(0))9}10If you want to use the method in a class, you could also use an import statement:11import kotlin.text.getRune12class MyClass {13    fun myMethod(json: String): Int {14        return json.getRune(0)15    }16}Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
