How to use Len method of main Package

Best Mock code snippet using main.Len

variables_test.go

Source:variables_test.go Github

copy

Full Screen

...345 }346 })347}348type varArray []*proc.Variable349// Len is part of sort.Interface.350func (s varArray) Len() int {351 return len(s)352}353// Swap is part of sort.Interface.354func (s varArray) Swap(i, j int) {355 s[i], s[j] = s[j], s[i]356}357// Less is part of sort.Interface. It is implemented by calling the "by" closure in the sorter.358func (s varArray) Less(i, j int) bool {359 return s[i].Name < s[j].Name360}361func TestLocalVariables(t *testing.T) {362 testcases := []struct {363 fn func(*proc.EvalScope, proc.LoadConfig) ([]*proc.Variable, error)364 output []varTest365 }{366 {(*proc.EvalScope).LocalVariables,367 []varTest{368 {"a1", true, "\"foofoofoofoofoofoo\"", "", "string", nil},369 {"a10", true, "\"ofo\"", "", "string", nil},370 {"a11", true, "[3]main.FooBar [{Baz: 1, Bur: \"a\"},{Baz: 2, Bur: \"b\"},{Baz: 3, Bur: \"c\"}]", "", "[3]main.FooBar", nil},371 {"a12", true, "[]main.FooBar len: 2, cap: 2, [{Baz: 4, Bur: \"d\"},{Baz: 5, Bur: \"e\"}]", "", "[]main.FooBar", nil},372 {"a13", true, "[]*main.FooBar len: 3, cap: 3, [*{Baz: 6, Bur: \"f\"},*{Baz: 7, Bur: \"g\"},*{Baz: 8, Bur: \"h\"}]", "", "[]*main.FooBar", nil},373 {"a2", true, "6", "", "int", nil},374 {"a3", true, "7.23", "", "float64", nil},375 {"a4", true, "[2]int [1,2]", "", "[2]int", nil},376 {"a5", true, "[]int len: 5, cap: 5, [1,2,3,4,5]", "", "[]int", nil},377 {"a6", true, "main.FooBar {Baz: 8, Bur: \"word\"}", "", "main.FooBar", nil},378 {"a7", true, "*main.FooBar {Baz: 5, Bur: \"strum\"}", "", "*main.FooBar", nil},379 {"a8", true, "main.FooBar2 {Bur: 10, Baz: \"feh\"}", "", "main.FooBar2", nil},380 {"a9", true, "*main.FooBar nil", "", "*main.FooBar", nil},381 {"b1", true, "true", "", "bool", nil},382 {"b2", true, "false", "", "bool", nil},383 {"ba", true, "[]int len: 200, cap: 200, [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,...+136 more]", "", "[]int", nil},384 {"c128", true, "(2 + 3i)", "", "complex128", nil},385 {"c64", true, "(1 + 2i)", "", "complex64", nil},386 {"f", true, "main.barfoo", "", "func()", nil},387 {"f32", true, "1.2", "", "float32", nil},388 {"i32", true, "[2]int32 [1,2]", "", "[2]int32", nil},389 {"i8", true, "1", "", "int8", nil},390 {"ms", true, "main.Nest {Level: 0, Nest: *main.Nest {Level: 1, Nest: *(*main.Nest)…", "", "main.Nest", nil},391 {"neg", true, "-1", "", "int", nil},392 {"u16", true, "65535", "", "uint16", nil},393 {"u32", true, "4294967295", "", "uint32", nil},394 {"u64", true, "18446744073709551615", "", "uint64", nil},395 {"u8", true, "255", "", "uint8", nil},396 {"up", true, "5", "", "uintptr", nil}}},397 {(*proc.EvalScope).FunctionArguments,398 []varTest{399 {"bar", true, "main.FooBar {Baz: 10, Bur: \"lorem\"}", "", "main.FooBar", nil},400 {"baz", true, "\"bazburzum\"", "", "string", nil}}},401 }402 protest.AllowRecording(t)403 withTestProcess("testvariables", t, func(p proc.Process, fixture protest.Fixture) {404 err := proc.Continue(p)405 assertNoError(err, t, "Continue() returned an error")406 for _, tc := range testcases {407 var scope *proc.EvalScope408 var err error409 if testBackend == "rr" {410 var frame proc.Stackframe411 frame, err = findFirstNonRuntimeFrame(p)412 if err == nil {413 scope = proc.FrameToScope(p.BinInfo(), p.CurrentThread(), nil, frame)414 }415 } else {416 scope, err = proc.GoroutineScope(p.CurrentThread())417 }418 assertNoError(err, t, "scope")419 vars, err := tc.fn(scope, pnormalLoadConfig)420 assertNoError(err, t, "LocalVariables() returned an error")421 sort.Sort(varArray(vars))422 if len(tc.output) != len(vars) {423 t.Fatalf("Invalid variable count. Expected %d got %d.", len(tc.output), len(vars))424 }425 for i, variable := range vars {426 assertVariable(t, variable, tc.output[i])427 }428 }429 })430}431func TestEmbeddedStruct(t *testing.T) {432 protest.AllowRecording(t)433 withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {434 testcases := []varTest{435 {"b.val", true, "-314", "-314", "int", nil},436 {"b.A.val", true, "-314", "-314", "int", nil},437 {"b.a.val", true, "42", "42", "int", nil},438 {"b.ptr.val", true, "1337", "1337", "int", nil},439 {"b.C.s", true, "\"hello\"", "\"hello\"", "string", nil},440 {"b.s", true, "\"hello\"", "\"hello\"", "string", nil},441 {"b2", true, "main.B {A: main.A {val: 42}, C: *main.C nil, a: main.A {val: 47}, ptr: *main.A nil}", "main.B {A: (*main.A)(0x…", "main.B", nil},442 }443 assertNoError(proc.Continue(p), t, "Continue()")444 ver, _ := goversion.Parse(runtime.Version())445 if ver.Major >= 0 && !ver.AfterOrEqual(goversion.GoVersion{1, 9, -1, 0, 0, ""}) {446 // on go < 1.9 embedded fields had different names447 for i := range testcases {448 if testcases[i].name == "b2" {449 testcases[i].value = "main.B {main.A: main.A {val: 42}, *main.C: *main.C nil, a: main.A {val: 47}, ptr: *main.A nil}"450 testcases[i].alternate = "main.B {main.A: (*main.A)(0x…"451 }452 }453 }454 for _, tc := range testcases {455 variable, err := evalVariable(p, tc.name, pnormalLoadConfig)456 if tc.err == nil {457 assertNoError(err, t, fmt.Sprintf("EvalVariable(%s) returned an error", tc.name))458 assertVariable(t, variable, tc)459 variable, err = evalVariable(p, tc.name, pshortLoadConfig)460 assertNoError(err, t, fmt.Sprintf("EvalVariable(%s, pshortLoadConfig) returned an error", tc.name))461 assertVariable(t, variable, tc.alternateVarTest())462 } else {463 if tc.err.Error() != err.Error() {464 t.Fatalf("Unexpected error. Expected %s got %s", tc.err.Error(), err.Error())465 }466 }467 }468 })469}470func TestComplexSetting(t *testing.T) {471 withTestProcess("testvariables", t, func(p proc.Process, fixture protest.Fixture) {472 err := proc.Continue(p)473 assertNoError(err, t, "Continue() returned an error")474 h := func(setExpr, value string) {475 assertNoError(setVariable(p, "c128", setExpr), t, "SetVariable()")476 variable, err := evalVariable(p, "c128", pnormalLoadConfig)477 assertNoError(err, t, "EvalVariable()")478 if s := api.ConvertVar(variable).SinglelineString(); s != value {479 t.Fatalf("Wrong value of c128: \"%s\", expected \"%s\" after setting it to \"%s\"", s, value, setExpr)480 }481 }482 h("3.2i", "(0 + 3.2i)")483 h("1.1", "(1.1 + 0i)")484 h("1 + 3.3i", "(1 + 3.3i)")485 h("complex(1.2, 3.4)", "(1.2 + 3.4i)")486 })487}488func TestEvalExpression(t *testing.T) {489 testcases := []varTest{490 // slice/array/string subscript491 {"s1[0]", false, "\"one\"", "\"one\"", "string", nil},492 {"s1[1]", false, "\"two\"", "\"two\"", "string", nil},493 {"s1[2]", false, "\"three\"", "\"three\"", "string", nil},494 {"s1[3]", false, "\"four\"", "\"four\"", "string", nil},495 {"s1[4]", false, "\"five\"", "\"five\"", "string", nil},496 {"s1[5]", false, "", "", "string", fmt.Errorf("index out of bounds")},497 {"a1[0]", false, "\"one\"", "\"one\"", "string", nil},498 {"a1[1]", false, "\"two\"", "\"two\"", "string", nil},499 {"a1[2]", false, "\"three\"", "\"three\"", "string", nil},500 {"a1[3]", false, "\"four\"", "\"four\"", "string", nil},501 {"a1[4]", false, "\"five\"", "\"five\"", "string", nil},502 {"a1[5]", false, "", "", "string", fmt.Errorf("index out of bounds")},503 {"str1[0]", false, "48", "48", "byte", nil},504 {"str1[1]", false, "49", "49", "byte", nil},505 {"str1[2]", false, "50", "50", "byte", nil},506 {"str1[10]", false, "48", "48", "byte", nil},507 {"str1[11]", false, "", "", "byte", fmt.Errorf("index out of bounds")},508 // slice/array/string reslicing509 {"a1[2:4]", false, "[]string len: 2, cap: 2, [\"three\",\"four\"]", "[]string len: 2, cap: 2, [...]", "[]string", nil},510 {"s1[2:4]", false, "[]string len: 2, cap: 2, [\"three\",\"four\"]", "[]string len: 2, cap: 2, [...]", "[]string", nil},511 {"str1[2:4]", false, "\"23\"", "\"23\"", "string", nil},512 {"str1[0:11]", false, "\"01234567890\"", "\"01234567890\"", "string", nil},513 {"str1[:3]", false, "\"012\"", "\"012\"", "string", nil},514 {"str1[3:]", false, "\"34567890\"", "\"34567890\"", "string", nil},515 {"str1[0:12]", false, "", "", "string", fmt.Errorf("index out of bounds")},516 {"str1[5:3]", false, "", "", "string", fmt.Errorf("index out of bounds")},517 // NaN and Inf floats518 {"pinf", false, "+Inf", "+Inf", "float64", nil},519 {"ninf", false, "-Inf", "-Inf", "float64", nil},520 {"nan", false, "NaN", "NaN", "float64", nil},521 // pointers522 {"*p2", false, "5", "5", "int", nil},523 {"p2", true, "*5", "(*int)(0x…", "*int", nil},524 {"p3", true, "*int nil", "*int nil", "*int", nil},525 {"*p3", false, "", "", "int", fmt.Errorf("nil pointer dereference")},526 // channels527 {"ch1", true, "chan int 4/10", "chan int 4/10", "chan int", nil},528 {"chnil", true, "chan int nil", "chan int nil", "chan int", nil},529 {"ch1+1", false, "", "", "", fmt.Errorf("can not convert 1 constant to chan int")},530 // maps531 {"m1[\"Malone\"]", false, "main.astruct {A: 2, B: 3}", "main.astruct {A: 2, B: 3}", "main.astruct", nil},532 {"m2[1].B", false, "11", "11", "int", nil},533 {"m2[c1.sa[2].B-4].A", false, "10", "10", "int", nil},534 {"m2[*p1].B", false, "11", "11", "int", nil},535 {"m3[as1]", false, "42", "42", "int", nil},536 {"mnil[\"Malone\"]", false, "", "", "", fmt.Errorf("key not found")},537 {"m1[80:]", false, "", "", "", fmt.Errorf("map index out of bounds")},538 // interfaces539 {"err1", true, "error(*main.astruct) *{A: 1, B: 2}", "error(*main.astruct) 0x…", "error", nil},540 {"err2", true, "error(*main.bstruct) *{a: main.astruct {A: 1, B: 2}}", "error(*main.bstruct) 0x…", "error", nil},541 {"errnil", true, "error nil", "error nil", "error", nil},542 {"iface1", true, "interface {}(*main.astruct) *{A: 1, B: 2}", "interface {}(*main.astruct) 0x…", "interface {}", nil},543 {"iface1.A", false, "1", "1", "int", nil},544 {"iface1.B", false, "2", "2", "int", nil},545 {"iface2", true, "interface {}(string) \"test\"", "interface {}(string) \"test\"", "interface {}", nil},546 {"iface3", true, "interface {}(map[string]go/constant.Value) []", "interface {}(map[string]go/constant.Value) []", "interface {}", nil},547 {"iface4", true, "interface {}([]go/constant.Value) [4]", "interface {}([]go/constant.Value) [...]", "interface {}", nil},548 {"ifacenil", true, "interface {} nil", "interface {} nil", "interface {}", nil},549 {"err1 == err2", false, "false", "false", "", nil},550 {"err1 == iface1", false, "", "", "", fmt.Errorf("mismatched types \"error\" and \"interface {}\"")},551 {"errnil == nil", false, "true", "true", "", nil},552 {"errtypednil == nil", false, "false", "false", "", nil},553 {"nil == errnil", false, "true", "true", "", nil},554 {"err1.(*main.astruct)", false, "*main.astruct {A: 1, B: 2}", "(*main.astruct)(0x…", "*main.astruct", nil},555 {"err1.(*main.bstruct)", false, "", "", "", fmt.Errorf("interface conversion: error is *main.astruct, not *main.bstruct")},556 {"errnil.(*main.astruct)", false, "", "", "", fmt.Errorf("interface conversion: error is nil, not *main.astruct")},557 {"const1", true, "go/constant.Value(go/constant.int64Val) 3", "go/constant.Value(go/constant.int64Val) 3", "go/constant.Value", nil},558 // combined expressions559 {"c1.pb.a.A", true, "1", "1", "int", nil},560 {"c1.sa[1].B", false, "3", "3", "int", nil},561 {"s2[5].B", false, "12", "12", "int", nil},562 {"s2[c1.sa[2].B].A", false, "11", "11", "int", nil},563 {"s2[*p2].B", false, "12", "12", "int", nil},564 // constants565 {"1.1", false, "1.1", "1.1", "", nil},566 {"10", false, "10", "10", "", nil},567 {"1 + 2i", false, "(1 + 2i)", "(1 + 2i)", "", nil},568 {"true", false, "true", "true", "", nil},569 {"\"test\"", false, "\"test\"", "\"test\"", "", nil},570 // binary operators571 {"i2 + i3", false, "5", "5", "int", nil},572 {"i2 - i3", false, "-1", "-1", "int", nil},573 {"i3 - i2", false, "1", "1", "int", nil},574 {"i2 * i3", false, "6", "6", "int", nil},575 {"i2/i3", false, "0", "0", "int", nil},576 {"f1/2.0", false, "1.5", "1.5", "float64", nil},577 {"i2 << 2", false, "8", "8", "int", nil},578 // unary operators579 {"-i2", false, "-2", "-2", "int", nil},580 {"+i2", false, "2", "2", "int", nil},581 {"^i2", false, "-3", "-3", "int", nil},582 // comparison operators583 {"i2 == i3", false, "false", "false", "", nil},584 {"i2 == 2", false, "true", "true", "", nil},585 {"i2 == 2", false, "true", "true", "", nil},586 {"i2 == 3", false, "false", "false", "", nil},587 {"i2 != i3", false, "true", "true", "", nil},588 {"i2 < i3", false, "true", "true", "", nil},589 {"i2 <= i3", false, "true", "true", "", nil},590 {"i2 > i3", false, "false", "false", "", nil},591 {"i2 >= i3", false, "false", "false", "", nil},592 {"i2 >= 2", false, "true", "true", "", nil},593 {"str1 == \"01234567890\"", false, "true", "true", "", nil},594 {"str1 < \"01234567890\"", false, "false", "false", "", nil},595 {"str1 < \"11234567890\"", false, "true", "true", "", nil},596 {"str1 > \"00234567890\"", false, "true", "true", "", nil},597 {"str1 == str1", false, "true", "true", "", nil},598 {"c1.pb.a == *(c1.sa[0])", false, "true", "true", "", nil},599 {"c1.pb.a != *(c1.sa[0])", false, "false", "false", "", nil},600 {"c1.pb.a == *(c1.sa[1])", false, "false", "false", "", nil},601 {"c1.pb.a != *(c1.sa[1])", false, "true", "true", "", nil},602 {`longstr == "not this"`, false, "false", "false", "", nil},603 // builtins604 {"cap(parr)", false, "4", "4", "", nil},605 {"len(parr)", false, "4", "4", "", nil},606 {"cap(p1)", false, "", "", "", fmt.Errorf("invalid argument p1 (type *int) for cap")},607 {"len(p1)", false, "", "", "", fmt.Errorf("invalid argument p1 (type *int) for len")},608 {"cap(a1)", false, "5", "5", "", nil},609 {"len(a1)", false, "5", "5", "", nil},610 {"cap(s3)", false, "6", "6", "", nil},611 {"len(s3)", false, "0", "0", "", nil},612 {"cap(nilslice)", false, "0", "0", "", nil},613 {"len(nilslice)", false, "0", "0", "", nil},614 {"cap(ch1)", false, "10", "10", "", nil},615 {"len(ch1)", false, "4", "4", "", nil},616 {"cap(chnil)", false, "0", "0", "", nil},617 {"len(chnil)", false, "0", "0", "", nil},618 {"len(m1)", false, "41", "41", "", nil},619 {"len(mnil)", false, "0", "0", "", nil},620 {"imag(cpx1)", false, "2", "2", "", nil},621 {"real(cpx1)", false, "1", "1", "", nil},622 {"imag(3i)", false, "3", "3", "", nil},623 {"real(4)", false, "4", "4", "", nil},624 // nil625 {"nil", false, "nil", "nil", "", nil},626 {"nil+1", false, "", "", "", fmt.Errorf("operator + can not be applied to \"nil\"")},627 {"fn1", false, "main.afunc", "main.afunc", "main.functype", nil},628 {"fn2", false, "nil", "nil", "main.functype", nil},629 {"nilslice", false, "[]int len: 0, cap: 0, nil", "[]int len: 0, cap: 0, nil", "[]int", nil},630 {"fn1 == fn2", false, "", "", "", fmt.Errorf("can not compare func variables")},631 {"fn1 == nil", false, "false", "false", "", nil},632 {"fn1 != nil", false, "true", "true", "", nil},633 {"fn2 == nil", false, "true", "true", "", nil},634 {"fn2 != nil", false, "false", "false", "", nil},635 {"c1.sa == nil", false, "false", "false", "", nil},636 {"c1.sa != nil", false, "true", "true", "", nil},637 {"c1.sa[0] == nil", false, "false", "false", "", nil},638 {"c1.sa[0] != nil", false, "true", "true", "", nil},639 {"nilslice == nil", false, "true", "true", "", nil},640 {"nil == nilslice", false, "true", "true", "", nil},641 {"nilslice != nil", false, "false", "false", "", nil},642 {"nilptr == nil", false, "true", "true", "", nil},643 {"nilptr != nil", false, "false", "false", "", nil},644 {"p1 == nil", false, "false", "false", "", nil},645 {"p1 != nil", false, "true", "true", "", nil},646 {"ch1 == nil", false, "false", "false", "", nil},647 {"chnil == nil", false, "true", "true", "", nil},648 {"ch1 == chnil", false, "", "", "", fmt.Errorf("can not compare chan variables")},649 {"m1 == nil", false, "false", "false", "", nil},650 {"mnil == m1", false, "", "", "", fmt.Errorf("can not compare map variables")},651 {"mnil == nil", false, "true", "true", "", nil},652 {"nil == 2", false, "", "", "", fmt.Errorf("can not compare int to nil")},653 {"2 == nil", false, "", "", "", fmt.Errorf("can not compare int to nil")},654 // errors655 {"&3", false, "", "", "", fmt.Errorf("can not take address of \"3\"")},656 {"*3", false, "", "", "", fmt.Errorf("expression \"3\" (int) can not be dereferenced")},657 {"&(i2 + i3)", false, "", "", "", fmt.Errorf("can not take address of \"(i2 + i3)\"")},658 {"i2 + p1", false, "", "", "", fmt.Errorf("mismatched types \"int\" and \"*int\"")},659 {"i2 + f1", false, "", "", "", fmt.Errorf("mismatched types \"int\" and \"float64\"")},660 {"i2 << f1", false, "", "", "", fmt.Errorf("shift count type float64, must be unsigned integer")},661 {"i2 << -1", false, "", "", "", fmt.Errorf("shift count type int, must be unsigned integer")},662 {"i2 << i3", false, "", "", "int", fmt.Errorf("shift count type int, must be unsigned integer")},663 {"*(i2 + i3)", false, "", "", "", fmt.Errorf("expression \"(i2 + i3)\" (int) can not be dereferenced")},664 {"i2.member", false, "", "", "", fmt.Errorf("i2 (type int) is not a struct")},665 {"fmt.Println(\"hello\")", false, "", "", "", fmt.Errorf("no type entry found, use 'types' for a list of valid types")},666 {"*nil", false, "", "", "", fmt.Errorf("nil can not be dereferenced")},667 {"!nil", false, "", "", "", fmt.Errorf("operator ! can not be applied to \"nil\"")},668 {"&nil", false, "", "", "", fmt.Errorf("can not take address of \"nil\"")},669 {"nil[0]", false, "", "", "", fmt.Errorf("expression \"nil\" (nil) does not support indexing")},670 {"nil[2:10]", false, "", "", "", fmt.Errorf("can not slice \"nil\" (type nil)")},671 {"nil.member", false, "", "", "", fmt.Errorf("nil (type nil) is not a struct")},672 {"(map[string]main.astruct)(0x4000)", false, "", "", "", fmt.Errorf("can not convert \"0x4000\" to map[string]main.astruct")},673 // typecasts674 {"uint(i2)", false, "2", "2", "uint", nil},675 {"int8(i2)", false, "2", "2", "int8", nil},676 {"int(f1)", false, "3", "3", "int", nil},677 {"complex128(f1)", false, "(3 + 0i)", "(3 + 0i)", "complex128", nil},678 {"uint8(i4)", false, "32", "32", "uint8", nil},679 {"uint8(i5)", false, "253", "253", "uint8", nil},680 {"int8(i5)", false, "-3", "-3", "int8", nil},681 {"int8(i6)", false, "12", "12", "int8", nil},682 {"string(byteslice[0])", false, `"t"`, `"t"`, "string", nil},683 {"string(runeslice[0])", false, `"t"`, `"t"`, "string", nil},684 // misc685 {"i1", true, "1", "1", "int", nil},686 {"mainMenu", true, `main.Menu len: 3, cap: 3, [{Name: "home", Route: "/", Active: 1},{Name: "About", Route: "/about", Active: 1},{Name: "Login", Route: "/login", Active: 1}]`, `main.Menu len: 3, cap: 3, [...]`, "main.Menu", nil},687 {"mainMenu[0]", false, `main.Item {Name: "home", Route: "/", Active: 1}`, `main.Item {Name: "home", Route: "/", Active: 1}`, "main.Item", nil},688 {"sd", false, "main.D {u1: 0, u2: 0, u3: 0, u4: 0, u5: 0, u6: 0}", "main.D {u1: 0, u2: 0, u3: 0,...+3 more}", "main.D", nil},689 {"ifacearr", false, "[]error len: 2, cap: 2, [*main.astruct {A: 0, B: 0},nil]", "[]error len: 2, cap: 2, [...]", "[]error", nil},690 {"efacearr", false, `[]interface {} len: 3, cap: 3, [*main.astruct {A: 0, B: 0},"test",nil]`, "[]interface {} len: 3, cap: 3, [...]", "[]interface {}", nil},691 {"zsslice", false, `[]struct {} len: 3, cap: 3, [{},{},{}]`, `[]struct {} len: 3, cap: 3, [...]`, "[]struct {}", nil},692 {"zsvmap", false, `map[string]struct {} ["testkey": {}, ]`, `map[string]struct {} [...]`, "map[string]struct {}", nil},693 {"tm", false, "main.truncatedMap {v: []map[string]main.astruct len: 1, cap: 1, [[...]]}", "main.truncatedMap {v: []map[string]main.astruct len: 1, cap: 1, [...]}", "main.truncatedMap", nil},694 {"emptyslice", false, `[]string len: 0, cap: 0, []`, `[]string len: 0, cap: 0, []`, "[]string", nil},695 {"emptymap", false, `map[string]string []`, `map[string]string []`, "map[string]string", nil},696 {"mnil", false, `map[string]main.astruct nil`, `map[string]main.astruct nil`, "map[string]main.astruct", nil},697 // conversions between string/[]byte/[]rune (issue #548)698 {"runeslice", true, `[]int32 len: 4, cap: 4, [116,232,115,116]`, `[]int32 len: 4, cap: 4, [...]`, "[]int32", nil},699 {"byteslice", true, `[]uint8 len: 5, cap: 5, [116,195,168,115,116]`, `[]uint8 len: 5, cap: 5, [...]`, "[]uint8", nil},700 {"[]byte(str1)", false, `[]uint8 len: 11, cap: 11, [48,49,50,51,52,53,54,55,56,57,48]`, `[]uint8 len: 11, cap: 11, [48,49,50,51,52,53,54,55,56,57,48]`, "[]uint8", nil},701 {"[]uint8(str1)", false, `[]uint8 len: 11, cap: 11, [48,49,50,51,52,53,54,55,56,57,48]`, `[]uint8 len: 11, cap: 11, [48,49,50,51,52,53,54,55,56,57,48]`, "[]uint8", nil},702 {"[]rune(str1)", false, `[]int32 len: 11, cap: 11, [48,49,50,51,52,53,54,55,56,57,48]`, `[]int32 len: 11, cap: 11, [48,49,50,51,52,53,54,55,56,57,48]`, "[]int32", nil},703 {"[]int32(str1)", false, `[]int32 len: 11, cap: 11, [48,49,50,51,52,53,54,55,56,57,48]`, `[]int32 len: 11, cap: 11, [48,49,50,51,52,53,54,55,56,57,48]`, "[]int32", nil},704 {"string(byteslice)", false, `"tèst"`, `""`, "string", nil},705 {"[]int32(string(byteslice))", false, `[]int32 len: 4, cap: 4, [116,232,115,116]`, `[]int32 len: 0, cap: 0, nil`, "[]int32", nil},706 {"string(runeslice)", false, `"tèst"`, `""`, "string", nil},707 {"[]byte(string(runeslice))", false, `[]uint8 len: 5, cap: 5, [116,195,168,115,116]`, `[]uint8 len: 0, cap: 0, nil`, "[]uint8", nil},708 {"*(*[5]byte)(uintptr(&byteslice[0]))", false, `[5]uint8 [116,195,168,115,116]`, `[5]uint8 [...]`, "[5]uint8", nil},709 {"string(bytearray)", false, `"tèst"`, `""`, "string", nil},710 {"string(runearray)", false, `"tèst"`, `""`, "string", nil},711 {"string(str1)", false, `"01234567890"`, `"01234567890"`, "string", nil},712 // access to channel field members713 {"ch1.qcount", false, "4", "4", "uint", nil},714 {"ch1.dataqsiz", false, "10", "10", "uint", nil},715 {"ch1.buf", false, `*[10]int [1,4,3,2,0,0,0,0,0,0]`, `(*[10]int)(…`, "*[10]int", nil},716 {"ch1.buf[0]", false, "1", "1", "int", nil},717 // shortcircuited logical operators718 {"nilstruct != nil && nilstruct.A == 1", false, "false", "false", "", nil},719 {"nilstruct == nil || nilstruct.A == 1", false, "true", "true", "", nil},720 {"afunc", true, `main.afunc`, `main.afunc`, `func()`, nil},721 {"main.afunc2", true, `main.afunc2`, `main.afunc2`, `func()`, nil},722 {"s2[0].Error", false, "main.(*astruct).Error", "main.(*astruct).Error", "func() string", nil},723 {"s2[0].NonPointerRecieverMethod", false, "main.astruct.NonPointerRecieverMethod", "main.astruct.NonPointerRecieverMethod", "func()", nil},724 {"as2.Error", false, "main.(*astruct).Error", "main.(*astruct).Error", "func() string", nil},725 {"as2.NonPointerRecieverMethod", false, "main.astruct.NonPointerRecieverMethod", "main.astruct.NonPointerRecieverMethod", "func()", nil},726 {`iface2map.(data)`, false, "…", "…", "map[string]interface {}", nil},727 }728 ver, _ := goversion.Parse(runtime.Version())729 if ver.Major >= 0 && !ver.AfterOrEqual(goversion.GoVersion{1, 7, -1, 0, 0, ""}) {730 for i := range testcases {731 if testcases[i].name == "iface3" {732 testcases[i].value = "interface {}(*map[string]go/constant.Value) *[]"733 testcases[i].alternate = "interface {}(*map[string]go/constant.Value) 0x…"734 }735 }736 }737 protest.AllowRecording(t)738 withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {739 assertNoError(proc.Continue(p), t, "Continue() returned an error")740 for _, tc := range testcases {741 variable, err := evalVariable(p, tc.name, pnormalLoadConfig)742 if err != nil && err.Error() == "evaluating methods not supported on this version of Go" {743 // this type of eval is unsupported with the current version of Go.744 continue745 }746 if tc.err == nil {747 assertNoError(err, t, fmt.Sprintf("EvalExpression(%s) returned an error", tc.name))748 assertVariable(t, variable, tc)749 variable, err := evalVariable(p, tc.name, pshortLoadConfig)750 assertNoError(err, t, fmt.Sprintf("EvalExpression(%s, pshortLoadConfig) returned an error", tc.name))751 assertVariable(t, variable, tc.alternateVarTest())752 } else {753 if err == nil {754 t.Fatalf("Expected error %s, got no error (%s)", tc.err.Error(), tc.name)755 }756 if tc.err.Error() != err.Error() {757 t.Fatalf("Unexpected error. Expected %s got %s", tc.err.Error(), err.Error())758 }759 }760 }761 })762}763func TestEvalAddrAndCast(t *testing.T) {764 protest.AllowRecording(t)765 withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {766 assertNoError(proc.Continue(p), t, "Continue() returned an error")767 c1addr, err := evalVariable(p, "&c1", pnormalLoadConfig)768 assertNoError(err, t, "EvalExpression(&c1)")769 c1addrstr := api.ConvertVar(c1addr).SinglelineString()770 t.Logf("&c1 → %s", c1addrstr)771 if !strings.HasPrefix(c1addrstr, "(*main.cstruct)(0x") {772 t.Fatalf("Invalid value of EvalExpression(&c1) \"%s\"", c1addrstr)773 }774 aaddr, err := evalVariable(p, "&(c1.pb.a)", pnormalLoadConfig)775 assertNoError(err, t, "EvalExpression(&(c1.pb.a))")776 aaddrstr := api.ConvertVar(aaddr).SinglelineString()777 t.Logf("&(c1.pb.a) → %s", aaddrstr)778 if !strings.HasPrefix(aaddrstr, "(*main.astruct)(0x") {779 t.Fatalf("invalid value of EvalExpression(&(c1.pb.a)) \"%s\"", aaddrstr)780 }781 a, err := evalVariable(p, "*"+aaddrstr, pnormalLoadConfig)782 assertNoError(err, t, fmt.Sprintf("EvalExpression(*%s)", aaddrstr))783 t.Logf("*%s → %s", aaddrstr, api.ConvertVar(a).SinglelineString())784 assertVariable(t, a, varTest{aaddrstr, false, "main.astruct {A: 1, B: 2}", "", "main.astruct", nil})785 })786}787func TestMapEvaluation(t *testing.T) {788 protest.AllowRecording(t)789 withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {790 assertNoError(proc.Continue(p), t, "Continue() returned an error")791 m1v, err := evalVariable(p, "m1", pnormalLoadConfig)792 assertNoError(err, t, "EvalVariable()")793 m1 := api.ConvertVar(m1v)794 t.Logf("m1 = %v", m1.MultilineString(""))795 if m1.Type != "map[string]main.astruct" {796 t.Fatalf("Wrong type: %s", m1.Type)797 }798 if len(m1.Children)/2 != 41 {799 t.Fatalf("Wrong number of children: %d", len(m1.Children)/2)800 }801 found := false802 for i := range m1.Children {803 if i%2 == 0 && m1.Children[i].Value == "Malone" {804 found = true805 }806 }807 if !found {808 t.Fatalf("Could not find Malone")809 }810 m1sliced, err := evalVariable(p, "m1[10:]", pnormalLoadConfig)811 assertNoError(err, t, "EvalVariable(m1[10:])")812 if len(m1sliced.Children)/2 != int(m1.Len-10) {813 t.Fatalf("Wrong number of children (after slicing): %d", len(m1sliced.Children)/2)814 }815 })816}817func TestUnsafePointer(t *testing.T) {818 protest.AllowRecording(t)819 withTestProcess("testvariables2", t, func(p proc.Process, fixture protest.Fixture) {820 assertNoError(proc.Continue(p), t, "Continue() returned an error")821 up1v, err := evalVariable(p, "up1", pnormalLoadConfig)822 assertNoError(err, t, "EvalVariable(up1)")823 up1 := api.ConvertVar(up1v)824 if ss := up1.SinglelineString(); !strings.HasPrefix(ss, "unsafe.Pointer(") {825 t.Fatalf("wrong value for up1: %s", ss)826 }...

Full Screen

Full Screen

test.go

Source:test.go Github

copy

Full Screen

1package main2import "fmt"3func main() {4 /* -------- array -------- */5 // array: 'specifies a length' and an element type6 // The type [n]T is an array of n values of type T7 // ex. type [2]int is defferent than type [4]int8 var a1 [3]int // declaration9 // By default an array is zero-valued10 fmt.Println(a1)11 a1[0] = 112 a1[1] = 213 a1[2] = 414 fmt.Println(a1)15 var a2 = [3]int{1, 2, 4} // declare and initialize16 fmt.Println(a2)17 var a3 = [...]int{1, 2, 4}18 fmt.Println(a3)19 var a4 [2][3]int20 a4[0][0] = 521 a4[0][1] = 422 a4[0][2] = 323 a4[1][0] = 224 a4[1][1] = 125 a4[1][2] = 026 fmt.Println(a4)27 var a5 = [2][3]int{28 {5, 4, 3},29 {2, 1, 0}, // MUST have comma30 // if it wouldn’t be there, Go would have added a semicolon(;)31 // by the rule which would have CRASHED the program32 }33 fmt.Println(a5)34 /* -------- slice -------- */35 // slice: array-like type, but slice has no specified length36 s := []int{0, 1, 2, 3, 4, 5}37 s = s[2:5]38 fmt.Println(s) // [2 3 4]39 s = s[1:]40 fmt.Println(s) // [3 4]41 s = append(s, 2)42 fmt.Println(s) // [3 4 2]43 s = append(s, 8, 9, 10)44 fmt.Println(s) // [3 4 2 8 9 10]45 // declare a slice, len = 0, cap = 346 //47 // cap tells you the capacity of the underlying array48 // len tells you how many items are in the array.49 //50 // ex.51 // s := []int{0, 1, 2, 3, 4, 5}52 //53 // [ptr][len][cap]54 // | [ 6 ][ 6 ]55 // |56 // | [0][1][2][3][4][5]57 // +--^58 // len - - - - - - (6)59 // cap - - - - - - (6)60 //61 // s = s[1:3]62 //63 // [ptr][len][cap]64 // | [ 2 ][ 5 ]65 // |66 // | [0][1][2][3][4][5]67 // +-----^68 // len - - (2)69 // cap - - - - - (5)70 fmt.Println(len(s), cap(s)) // 6 671 s = s[1:3] // includes the first element, but excludes the last one, [1,3)72 fmt.Println(len(s), cap(s)) // 2 573 slice := make([]int, 0, 3)74 for i := 1; i <= 15; i++ {75 slice = append(slice, i)76 fmt.Println(len(slice), cap(slice))77 /*78 1 379 2 380 3 381 4 682 5 683 6 684 7 1285 8 1286 9 1287 10 1288 11 1289 12 1290 13 2491 14 2492 15 2493 */94 }95 fmt.Println(slice)96 // slice... -> replace to [1 2 3 ... 13 14 15]97 fmt.Println(len(s), cap(s)) // 6 698 fmt.Println(len(slice), cap(slice)) // 15 2499 s = append(s, slice...)100 fmt.Println(len(s), cap(s)) // 21 22101 fmt.Println(s) // [3 4 2 8 9 10 1 2 3 ... 13 14 15]102 source := []int{0, 1, 2}103 target := make([]int, len(source), cap(source)*2)104 // function copy returns the number of elements copied,105 // which will be the minimum of len(dst) and len(src)106 copy(target, source)107 fmt.Println(len(target), cap(target)) // 3 6108 fmt.Println(target) // [0 1 2]109 copy(target, s)110 fmt.Println(len(target), cap(target)) // 3 6111 fmt.Println(target) // [3 4 2]112 /* -------- map -------- */113 // maps keys to values114 // zero value of map is nil115 // nil map has no keys, nor can keys be added116 // make function returns a map of the given type, initialized and ready for use117}118/*119package main120import "fmt"121func main() {122 s := []int{2, 3, 5, 7, 11, 13}123 printSlice(s)124 // Slice the slice to give it zero length.125 s = s[:0]126 printSlice(s)127 // Extend its length.128 s = s[:4]129 printSlice(s)130 // Drop its first two values.131 s = s[2:]132 printSlice(s)133 }134 func printSlice(s []int) {135 fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)136 }137*/138/* nil slice139// By default ptr pointer to nil, len and cap is zero140package main141import "fmt"142func main() {143 var s []int144 fmt.Println(s, len(s), cap(s))145 if s == nil {146 fmt.Println("nil!")147 }148 }149*/150/* slice with make151package main152import "fmt"153func main() {154 a := make([]int, 5)155 printSlice("a", a)156 b := make([]int, 0, 5)157 printSlice("b", b)158 c := b[:2]159 printSlice("c", c)160 d := c[2:5]161 printSlice("d", d)162 }163 func printSlice(s string, x []int) {164 fmt.Printf("%s len=%d cap=%d %v\n",165 s, len(x), cap(x), x)166 }167*/168/* slices of slices169// tic-tac-toe170package main171import (172 "fmt"173 "strings"174 )175 func main() {176 // Create a tic-tac-toe board.177 board := [][]string{178 []string{"_", "_", "_"},179 []string{"_", "_", "_"},180 []string{"_", "_", "_"},181 }182 // The players take turns.183 board[0][0] = "X"184 board[2][2] = "O"185 board[1][2] = "X"186 board[1][0] = "O"187 board[0][2] = "X"188 for i := 0; i < len(board); i++ {189 fmt.Printf("%s\n", strings.Join(board[i], " "))190 }191 }192*/193/* append194package main195import "fmt"196func main() {197 var s []int198 printSlice(s)199 // append works on nil slices.200 s = append(s, 0)201 printSlice(s)202 // The slice grows as needed.203 s = append(s, 1)204 printSlice(s)205 // We can add more than one element at a time.206 s = append(s, 2, 3, 4) // cap: 2, If the backing array of s is too small to fit all the given values a bigger array will be allocated. (capXn) => 6207 // The returned slice will point to the newly allocated array.208 printSlice(s)209 }210 func printSlice(s []int) {211 fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)212 }213*/214/* Map intro215ickage main216import "fmt"217type Vertex struct {218 Lat, Long float64219 }220 var m map[string]Vertex221 func main() {222 m = make(map[string]Vertex)223 m["Bell Labs"] = Vertex{224 40.68433, -74.39967,225 }226 fmt.Println(m["Bell Labs"])227 }228*/229/* Map230package main231import "fmt"232type Vertex struct {233 Lat, Long float64234 }235 var m = map[string]Vertex{236 "Bell Labs": Vertex{237 40.68433, -74.39967,238 },239 "Google": Vertex{240 37.42202, -122.08408,241 },242 }243 func main() {244 fmt.Println(m)245 }246*/247/* Map 2248package main249import "fmt"250type Vertex struct {251 Lat, Long float64252 }253 var m = map[string]Vertex{254 "Bell Labs": {40.68433, -74.39967},255 "Google": {37.42202, -122.08408},256 }257 func main() {258 fmt.Println(m)259 }260*/261/* Mutating Map262package main263import "fmt"264func main() {265 m := make(map[string]int)266 m["Answer"] = 42267 fmt.Println("The value:", m["Answer"])268 m["Answer"] = 48269 fmt.Println("The value:", m["Answer"])270 delete(m, "Answer")271 fmt.Println("The value:", m["Answer"])272 v, ok := m["Answer"]273 fmt.Println("The value:", v, "Present?", ok)274 }275*/276/* Mutating Map 2277package main278func main() {279 tickers := map[string]string{280 "GOOG": "Google Inc",281 "MSFT": "Microsoft",282 "FB": "FaceBook",283 "AMZN": "Amazon",284 }285 // map 키 체크286 val, exists := tickers["MSFT"]287 if !exists {288 println("No MSFT ticker")289 }290 }291*/292/* Mutating Map 3293package main294import "fmt"295func main() {296 myMap := map[string]string{297 "A": "Apple",298 "B": "Banana",299 "C": "Charlie",300 }301 // for range 문을 사용하여 모든 맵 요소 출력302 // Map은 unordered 이므로 순서는 무작위303 for key, val := range myMap {304 fmt.Println(key, val)305 }306 }307*/...

Full Screen

Full Screen

slice.go

Source:slice.go Github

copy

Full Screen

1package main2import "fmt"3func main() {4 /* -------- slice -------- */5 // slice: array-like type, but slice has no specified length6 s := []int{0, 1, 2, 3, 4, 5}7 s = s[2:5]8 fmt.Println(s) // [2 3 4]9 s = s[1:]10 fmt.Println(s) // [3 4]11 s = append(s, 2)12 fmt.Println(s) // [3 4 2]13 s = append(s, 8, 9, 10)14 fmt.Println(s) // [3 4 2 8 9 10]15 // declare a slice, len = 0, cap = 316 //17 // cap tells you the capacity of the underlying array18 // len tells you how many items are in the array.19 //20 // ex.21 // s := []int{0, 1, 2, 3, 4, 5}22 //23 // [ptr][len][cap]24 // | [ 6 ][ 6 ]25 // |26 // | [0][1][2][3][4][5]27 // +--^28 // len - - - - - - (6)29 // cap - - - - - - (6)30 //31 // s = s[1:3]32 //33 // [ptr][len][cap]34 // | [ 2 ][ 5 ]35 // |36 // | [0][1][2][3][4][5]37 // +-----^38 // len - - (2)39 // cap - - - - - (5)40 fmt.Println(len(s), cap(s)) // 6 641 s = s[1:3] // includes the first element, but excludes the last one, [1,3)42 fmt.Println(len(s), cap(s)) // 2 543 slice := make([]int, 0, 3)44 for i := 1; i <= 15; i++ {45 slice = append(slice, i)46 fmt.Println(len(slice), cap(slice))47 /*48 1 349 2 350 3 351 4 652 5 653 6 654 7 1255 8 1256 9 1257 10 1258 11 1259 12 1260 13 2461 14 2462 15 2463 */64 }65 fmt.Println(slice)66 // slice... -> replace to [1 2 3 ... 13 14 15]67 fmt.Println(len(s), cap(s)) // 6 668 fmt.Println(len(slice), cap(slice)) // 15 2469 s = append(s, slice...)70 fmt.Println(len(s), cap(s)) // 21 2271 fmt.Println(s) // [3 4 2 8 9 10 1 2 3 ... 13 14 15]72 source := []int{0, 1, 2}73 target := make([]int, len(source), cap(source)*2)74 // function copy returns the number of elements copied,75 // which will be the minimum of len(dst) and len(src)76 copy(target, source)77 fmt.Println(len(target), cap(target)) // 3 678 fmt.Println(target) // [0 1 2]79 copy(target, s)80 fmt.Println(len(target), cap(target)) // 3 681 fmt.Println(target) // [3 4 2]82}83/*84package main85import "fmt"86func main() {87 s := []int{2, 3, 5, 7, 11, 13}88 printSlice(s)89 // Slice the slice to give it zero length.90 s = s[:0]91 printSlice(s)92 // Extend its length.93 s = s[:4]94 printSlice(s)95 // Drop its first two values.96 s = s[2:]97 printSlice(s)98 }99 func printSlice(s []int) {100 fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)101 }102*/103/* nil slice104// By default ptr pointer to nil, len and cap is zero105package main106import "fmt"107func main() {108 var s []int109 fmt.Println(s, len(s), cap(s))110 if s == nil {111 fmt.Println("nil!")112 }113 }114*/115/* slice with make116package main117import "fmt"118func main() {119 a := make([]int, 5)120 printSlice("a", a)121 b := make([]int, 0, 5)122 printSlice("b", b)123 c := b[:2]124 printSlice("c", c)125 d := c[2:5]126 printSlice("d", d)127 }128 func printSlice(s string, x []int) {129 fmt.Printf("%s len=%d cap=%d %v\n",130 s, len(x), cap(x), x)131 }132*/133/* slices of slices134// tic-tac-toe135package main136import (137 "fmt"138 "strings"139 )140 func main() {141 // Create a tic-tac-toe board.142 board := [][]string{143 []string{"_", "_", "_"},144 []string{"_", "_", "_"},145 []string{"_", "_", "_"},146 }147 // The players take turns.148 board[0][0] = "X"149 board[2][2] = "O"150 board[1][2] = "X"151 board[1][0] = "O"152 board[0][2] = "X"153 for i := 0; i < len(board); i++ {154 fmt.Printf("%s\n", strings.Join(board[i], " "))155 }156 }157*/158/* append159package main160import "fmt"161func main() {162 var s []int163 printSlice(s)164 // append works on nil slices.165 s = append(s, 0)166 printSlice(s)167 // The slice grows as needed.168 s = append(s, 1)169 printSlice(s)170 // We can add more than one element at a time.171 s = append(s, 2, 3, 4) // cap: 2, If the backing array of s is too small to fit all the given values a bigger array will be allocated. (capXn) => 6172 // The returned slice will point to the newly allocated array.173 printSlice(s)174 }175 func printSlice(s []int) {176 fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)177 }178*/179/* Map intro180ickage main181import "fmt"182type Vertex struct {183 Lat, Long float64184 }185 var m map[string]Vertex186 func main() {187 m = make(map[string]Vertex)188 m["Bell Labs"] = Vertex{189 40.68433, -74.39967,190 }191 fmt.Println(m["Bell Labs"])192 }193*/...

Full Screen

Full Screen

rabin_karp.go

Source:rabin_karp.go Github

copy

Full Screen

1package rabinkarp2import (3 "math"4)5const defaultBase = 266// exponent get the value(base^exponent) and store the value in the result,7// e.g., result[2]=base^2, result[1]=base^1, result[0]=base^08func exponent(base, exponent int) (result []int) {9 result = make([]int, exponent+1)10 for i := range result {11 result[i] = int(math.Pow(float64(base), float64(i)))12 }13 return result14}15func rkSearch(main string, pattern string) bool {16 lenMain := len(main)17 lenPattern := len(pattern)18 exponent := exponent(defaultBase, lenPattern)19 // store the hash of main string20 hashMain := make([]int, lenMain-lenPattern+1)21 // store the hash of pattern22 hashPattern := 023 // calculate the hash of pattern and hashMain[0]24 for i := range pattern {25 idx := lenPattern - 1 - i26 hashPattern += exponent[idx] * int(pattern[i]-'a')27 hashMain[0] += exponent[idx] * int(main[i]-'a')28 }29 // calculate the hash of hashMain[1:]30 for i := 1; i < lenMain-lenPattern+1; i++ {31 hashMain[i] = defaultBase*(hashMain[i-1]-exponent[lenPattern-1]*int(main[i-1]-'a')) + exponent[0]*int(main[i+lenPattern-1]-'a')32 }33 // compare the hash of main and pattern34 for i := range hashMain {35 if hashPattern == hashMain[i] {36 return true37 }38 }39 return false40}41// rkSearchMatrixString search pattern from matrix string,42// h[0][0] represent the hash of s[0][0] -> s[1][2],43// h[0][1] represent the hash of s[0][1] -> s[1][3],44// h[1][0] represent the hash of s[1][0] -> s[2][2],45// r=lenPatternRow, c=lenPatternColumn,46// e.g., if pattern=47// {"d", "a", "b"},48// {"e", "f", "a"},49// r=2, c=3,50// h[i][j]=10^(r-1)*(26^(c-1)*(s[i][j]-'a')+26^(c-2)*(s[i][j+1]-'a')+...+26^0*(s[i][j+c-1]-'a'))+51// 10^(r-2)*(26^(c-1)*(s[i+1][j]-'a')+26^(c-2)*(s[i+1][j+1]-'a')+...+26^0*(s[i+1][j+c-1]-'a'))+...52// 10^0*(26^(c-1)*(s[i+r-1][j]-'a')+26^(c-2)*(s[i+r-1][j+1]-'a')+...+26^0*(s[i+r-1][j+c-1]-'a'))53// h[i][j+1]=54// 26*(h[i][j]-10^(r-1)*26^(c-1)*(s[i][j]-'a')-10^(r-2)*26^(c-1)*(s[i+1][j]-'a')-...-10^0*26^(c-1)*(s[i+r-1][j]-'a'))+55// 10^(r-1)*26^0*(s[i][j+c]-'a')+10^(r-2)*26^0*(s[i+1][j+c]-'a')+...+10^0*26^0*(s[i+r-1][j+c]-'a')56// h[i+1][j]=57// 10*h[i][j]-10^(r)*(26^(c-1)*(s[i][j]-'a')+26^(c-2)*(s[i][j+1]-'a')+...+26^0*(s[i][j+c-1]-'a'))+58// 10^0*(26^(c-1)*(s[i+r][j]-'a')+26^(c-2)*(s[i+r][j+1]-'a')+...+26^0*(s[i+r][j+c-1]-'a'))59func rkSearchMatrixString(main, pattern [][]string) bool {60 lenMainRow := len(main)61 lenMainColumn := len(main[0])62 lenPatternRow := len(pattern)63 lenPatternColumn := len(pattern[0])64 if 0 == lenMainRow || 0 == lenPatternRow {65 return false66 }67 if lenMainRow < lenPatternRow || lenMainColumn < lenPatternColumn {68 return false69 }70 exponent26 := exponent(defaultBase, lenPatternColumn)71 exponent10 := exponent(10, lenPatternRow)72 // store the hash of main string73 hashMain := make([][]int, lenMainRow-lenPatternRow+1)74 for i := range hashMain {75 hashMain[i] = make([]int, lenMainColumn-lenPatternColumn+1)76 }77 // store the hash of pattern78 hashPattern := 079 // calculate the hash of pattern and hashMain[0][0]80 for i := range pattern {81 tmpPattern := 082 tmpMain := 083 for j := range pattern[i] {84 idxColumn := lenPatternColumn - 1 - j85 tmpPattern += exponent26[idxColumn] * int([]byte(pattern[i][j])[0]-'a')86 tmpMain += exponent26[idxColumn] * int([]byte(main[i][j])[0]-'a')87 }88 idxRow := lenPatternRow - 1 - i89 hashPattern += exponent10[idxRow] * tmpPattern90 hashMain[0][0] += exponent10[idxRow] * tmpMain91 }92 // calculate the hash of hashMain[1:][0]93 for i := 1; i <= lenMainRow-lenPatternRow; i++ {94 tmp := 095 idxColumn := lenPatternColumn - 196 for j := 0; j <= lenPatternColumn-1; j++ {97 tmp += exponent26[idxColumn]*int([]byte(main[i-1+lenPatternRow][j])[0]-'a') -98 exponent10[lenPatternRow]*(exponent26[idxColumn]*int([]byte(main[i-1][j])[0]-'a'))99 idxColumn--100 }101 hashMain[i][0] = 10*hashMain[i-1][0] + tmp102 }103 // calculate the hash of hashMain[i][j]104 for i := 0; i <= lenMainRow-lenPatternRow; i++ {105 for j := 1; j <= lenMainColumn-lenPatternColumn; j++ {106 tmp := 0107 idxRow := lenPatternRow - 1108 for k := i; k <= i+lenPatternRow-1; k++ {109 tmp += exponent10[idxRow]*int([]byte(main[k][j+lenPatternColumn-1])[0]-'a') -110 exponent26[lenPatternColumn]*exponent10[idxRow]*int([]byte(main[k][j-1])[0]-'a')111 idxRow--112 }113 hashMain[i][j] = 26*hashMain[i][j-1] + tmp114 }115 }116 for i := range hashMain {117 for j := range hashMain[i] {118 if hashPattern == hashMain[i][j] {119 return true120 }121 }122 }123 return false124}...

Full Screen

Full Screen

brute_force.go

Source:brute_force.go Github

copy

Full Screen

1package bruteforce2// aaaaaab3// aab4func bfSearch(main, sub string) bool {5 lenMain := len(main)6 lenSub := len(sub)7 for i := 0; i <= lenMain-lenSub; i++ {8 j := 09 idx := i10 for j < lenSub {11 if main[idx] != sub[j] {12 break13 }14 idx++15 j++16 }17 if j == lenSub {18 return true19 }20 }21 return false22}23//BF search pattern24func bfSearch1(main string, pattern string) bool {25 //defensive26 if len(main) == 0 || len(pattern) == 0 || len(main) < len(pattern) {27 return false28 }29 for i := 0; i <= len(main)-len(pattern); i++ {30 subStr := main[i : i+len(pattern)]31 if subStr == pattern {32 return true33 }34 }35 return false36}37// bfSearchMatrixString search pattern from matrix string38func bfSearchMatrixString(main, pattern [][]string) bool {39 lenMainRow := len(main)40 lenMainColumn := len(main[0])41 lenPatternRow := len(pattern)42 lenPatternColumn := len(pattern[0])43 if 0 == lenMainRow || 0 == lenPatternRow {44 return false45 }46 if lenMainRow < lenPatternRow || lenMainColumn < lenPatternColumn {47 return false48 }49 for i := 0; i <= lenMainRow-lenPatternRow; i++ {50 for j := 0; j <= lenMainColumn-lenPatternColumn; j++ {51 sub := truncate(main, i, i+lenPatternRow-1, j, j+lenPatternColumn-1)52 if isEqual(sub, pattern) {53 return true54 }55 }56 }57 return false58}59// truncate truncate the string from a,60// e.g., a=61// {"d", "a", "b", "c", "d"},62// {"e", "f", "a", "d", "g"},63// {"c", "c", "a", "f", "h"},64// {"d", "e", "f", "c", "i"},65// if rowStart=0, rowEnd=1, columnStart=0, columnEnd =2, result=66// {"d", "a", "b"},67// {"e", "f", "a"},68func truncate(a [][]string, rowStart, rowEnd, columnStart, columnEnd int) (result [][]string) {69 if 0 == len(a) || rowEnd < rowStart || columnEnd < columnStart || len(a) < rowEnd+1 || len(a[0]) < columnEnd+1 {70 return nil71 }72 for i := rowStart; i <= rowEnd; i++ {73 result = append(result, a[i][columnStart:columnEnd+1])74 }75 return result76}77// isEqual return true if first==second, else return false78func isEqual(first, second [][]string) bool {79 if 0 == len(first) && 0 == len(second) {80 return false81 }82 if len(first) != len(second) {83 return false84 }85 for i := range first {86 if !isSliceEqual(first[i], second[i]) {87 return false88 }89 }90 return true91}92// isSliceEqual return true if first==second, else return false93func isSliceEqual(first, second []string) bool {94 if 0 == len(first) && 0 == len(second) {95 return false96 }97 if len(first) != len(second) {98 return false99 }100 for i := range first {101 if first[i] != second[i] {102 return false103 }104 }105 return true106}...

Full Screen

Full Screen

slice_02.go

Source:slice_02.go Github

copy

Full Screen

1package main2import (3 "encoding/json"4 "fmt"5 "time"6)7func func1() {8 n := 10000009 sl1 := make([]int, 0)10 start1 := time.Now().UnixMicro()11 for i := 0; i < n; i++ {12 sl1 = append(sl1, i)13 }14 end1 := time.Now().UnixMicro()15 fmt.Println(end1 - start1) //674216 sl2 := make([]int, 0, n)17 start2 := time.Now().UnixMicro()18 for i := 0; i < n; i++ {19 sl2 = append(sl2, i)20 }21 end2 := time.Now().UnixMicro()22 fmt.Println(end2 - start2) //154423}24func func2(a []int) {25 a[1] = 1026 fmt.Printf("func2 a =%v,pointer =%p,len = %d, cap = %d\n", a, &a, len(a), cap(a))27}28func func3(a []int) {29 fmt.Printf(" f2 append before a =%v,pointer =%p,len = %d, cap = %d\n", a, &a, len(a), cap(a))30 a = append(a, 5)31 fmt.Printf(" f2 append after a =%v,pointer =%p,len = %d, cap = %d\n", a, &a, len(a), cap(a))32}33func func4(a []int) {34 fmt.Printf(" f2 append before a =%v,pointer =%p,len = %d, cap = %d\n", a, &a, len(a), cap(a))35 a = append(a, 5)36 fmt.Printf(" f2 append after a =%v,pointer =%p,len = %d, cap = %d\n", a, &a, len(a), cap(a))37}38func main() {39 //func1()40 //-------------------------------------41 //a := []int{1, 2, 3, 4}42 //fmt.Printf(" main a =%v,pointer =%p,len = %d, cap = %d\n", a, &a, len(a), cap(a))43 //func2(a)44 //fmt.Printf(" main a =%v,pointer =%p,len = %d, cap = %d\n", a, &a, len(a), cap(a))45 //-------------------------------------46 //b := make([]int, 4, 4)47 //fmt.Printf(" main b =%v,pointer =%p,len = %d, cap = %d\n", b, &b, len(b), cap(b))48 //func3(b)49 //fmt.Printf(" main b =%v,pointer =%p,len = %d, cap = %d\n", b[0:4], &b, len(b), cap(b))50 //-------------------------------------51 //c := make([]int, 0, 4)52 //fmt.Printf(" main c =%v,pointer =%p,len = %d, cap = %d\n", c, &c, len(c), cap(c))53 //func4(c)54 //fmt.Printf(" main b =%v,pointer =%p,len = %d, cap = %d\n", c, &c, len(c), cap(c))55 //fmt.Printf(" main b =%v,pointer =%p,len = %d, cap = %d\n", c[0:4], &c, len(c), cap(c))56 //--------------------------57 var d1 []int58 d2 := make([]int, 0)59 json1, err := json.Marshal(d1)60 if err != nil {61 fmt.Println(err)62 } else {63 fmt.Println(string(json1))64 }65 json2, err := json.Marshal(d2)66 if err != nil {67 fmt.Println(err)68 } else {69 fmt.Println(string(json2))70 }71}...

Full Screen

Full Screen

string.go

Source:string.go Github

copy

Full Screen

1package main2func bf(mainString, patternString string) bool {3 mainStrLen := len(mainString)4 patternStrLen := len(patternString)5 if mainStrLen < patternStrLen {6 return false7 }8 for i := 0; i < mainStrLen-patternStrLen+1; i++ {9 subStr := mainString[i : patternStrLen+i]10 if subStr == patternString {11 return true12 }13 }14 return false15}16var squreMap = make(map[int]uint32)17func initSqureNum() {18 squreMap[0] = 119 for i := 1; i <= 26; i++ {20 if i == 1 {21 squreMap[i] = 2622 } else {23 squreMap[i] = squreMap[i-1] * 2624 }25 }26}27func hash(str string) uint32 {28 var result uint3229 strLen := len(str)30 for index, rune := range str {31 result += (uint32(rune%97) + 1) * squreMap[strLen-index-1]32 }33 return result34}35func rk(mainString, patternString string) bool {36 mainStrLen := len(mainString)37 patternStrLen := len(patternString)38 if mainStrLen < patternStrLen {39 return false40 }41 var subStrHash uint3242 patternStrHash := hash(patternString)43 for i := 0; i < mainStrLen-patternStrLen+1; i++ {44 subStr := mainString[i : patternStrLen+i]45 subStrHash = hash(subStr)46 if subStrHash == patternStrHash {47 return true48 }49 }50 return false51}52// func main() {53// mainString := "acdefg"54// patternString := "cdeg"55// fmt.Println("bf result: ", bf(mainString, patternString))56// initSqureNum()57// fmt.Println("rk result: ", rk(mainString, patternString))58// }...

Full Screen

Full Screen

Len

Using AI Code Generation

copy

Full Screen

1import "fmt"2func main() {3 fmt.Println("Hello, World!")4}5import "fmt"6func main() {7 fmt.Println("Hello, World!")8}9import "fmt"10func main() {11 fmt.Println("Hello, World!")12}13import "fmt"14func main() {15 fmt.Println("Hello, World!")16}17import "fmt"18func main() {19 fmt.Println("Hello, World!")20}21import "fmt"22func main() {23 fmt.Println("Hello, World!")24}25import "fmt"26func main() {27 fmt.Println("Hello, World!")28}29import "fmt"30func main() {31 fmt.Println("Hello, World!")32}33import "fmt"34func main() {35 fmt.Println("Hello, World!")36}37import "fmt"38func main() {39 fmt.Println("Hello, World!")40}41import "fmt"42func main() {43 fmt.Println("Hello, World!")44}45import "fmt"46func main() {47 fmt.Println("Hello, World!")48}49import "fmt"50func main() {51 fmt.Println("Hello, World!")52}53import "fmt"54func main() {55 fmt.Println("Hello,

Full Screen

Full Screen

Len

Using AI Code Generation

copy

Full Screen

1import "fmt"2func main() {3 fmt.Println("Hello, playground")4}5import "fmt"6func main() {7 fmt.Println("Hello, playground")8}9import "fmt"10func main() {11 fmt.Println("Hello, playground")12}13import "fmt"14func main() {15 fmt.Println("Hello, playground")16}17import "fmt"18func main() {19 fmt.Println("Hello, playground")20}21import "fmt"22func main() {23 fmt.Println("Hello, playground")24}25import "fmt"26func main() {27 fmt.Println("Hello, playground")28}29import "fmt"30func main() {31 fmt.Println("Hello, playground")32}33import "fmt"34func main() {35 fmt.Println("Hello, playground")36}37import "fmt"38func main() {39 fmt.Println("Hello, playground")40}41import "fmt"42func main() {43 fmt.Println("Hello, playground")44}45import "fmt"46func main() {47 fmt.Println("Hello, playground")48}49import "fmt"50func main() {51 fmt.Println("Hello, playground")52}53import "fmt"54func main() {55 fmt.Println("Hello,

Full Screen

Full Screen

Len

Using AI Code Generation

copy

Full Screen

1import "fmt"2func main() {3 var s1 = []int{1, 2, 3, 4, 5}4 var s2 = []int{6, 7, 8}5 fmt.Println("s1 length is", len(s1))6 fmt.Println("s2 length is", len(s2))7}8import "fmt"9func main() {10 var s1 = []int{1, 2, 3, 4, 5}11 var s2 = []int{6, 7, 8}12 s3 := append(s1, s2...)13 fmt.Println("s3 is", s3)14}15import "fmt"16func main() {17 var s1 = []int{1, 2, 3, 4, 5}18 var s2 = []int{6, 7, 8}19 copy(s1, s2)20 fmt.Println("s1 is", s1)21}22import "fmt"23func main() {24 var s1 = []int{1, 2, 3, 4, 5}25 var s2 = []int{6, 7, 8}26 s3 := append(s1, s2...)27 fmt.Println("s1 length is", len(s1))28 fmt.Println("s2 length is", len(s2))29 fmt.Println("s3 length is", len(s3))30 fmt.Println("s1 capacity is", cap(s1))31 fmt.Println("s2 capacity is", cap(s2))32 fmt.Println("s3 capacity is", cap(s3))33}

Full Screen

Full Screen

Len

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println(strings.Count(s, "l"))4 fmt.Println(strings.Count(s, "lo"))5 fmt.Println(strings.Count(s, ""))6 fmt.Println(strings.Count(s, "o"))7}8func Count(s, substr string) int9import (10func main() {11 fmt.Println(strings.Count(s, "l"))12 fmt.Println(strings.Count(s, "lo"))13 fmt.Println(strings.Count(s, ""))14 fmt.Println(strings.Count(s, "o"))15}16func Fields(s string) []string17import (18func main() {19 fmt.Println(strings.Fields(s))20}21func HasPrefix(s, prefix string) bool22import (23func main() {24 fmt.Println(strings.HasPrefix(s, "He"))25 fmt.Println(strings.HasPrefix(s, "Wo"))26}

Full Screen

Full Screen

Len

Using AI Code Generation

copy

Full Screen

1import "fmt"2func main() {3 fmt.Println("Hello, playground")4 fmt.Println(p.First)5 fmt.Println(p.Last)6 fmt.Println(p.Age)7 fmt.Println(p.Len())8}9import "fmt"10func main() {11 fmt.Println("Hello, playground")12 fmt.Println(p.First)13 fmt.Println(p.Last)14 fmt.Println(p.Age)15 fmt.Println(p.Len())16}17import "fmt"18func main() {19 fmt.Println("Hello, playground")20 fmt.Println(p.First)21 fmt.Println(p.Last)22 fmt.Println(p.Age)23 fmt.Println(p.Len())24}25import "fmt"26type Person struct {27}28func (p Person) Len() int {29 return len(p.First) + len(p.Last)30}31func main() {32 fmt.Println("Hello, playground")33 fmt.Println(p.First)34 fmt.Println(p.Last)35 fmt.Println(p.Age)36 fmt.Println(p.Len())37}38import "fmt"39type Person struct {40}41func (p *Person) Len() int {42 return len(p.First) + len(p.Last)43}44func main() {45 fmt.Println("Hello, playground")46 fmt.Println(p.First)47 fmt.Println(p.Last)48 fmt.Println(p.Age)49 fmt.Println(p.Len())50}51import "fmt"52type Person struct {53}54func (p Person) Len() int {55 return len(p.First) + len(p.Last)56}57func main() {58 fmt.Println("

Full Screen

Full Screen

Len

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Length of string s1 is: ", len(s1))4 fmt.Println("Length of string s2 is: ", len(s2))5}6import (7func main() {8 fmt.Println("Index of string s2 in s1 is: ", s1.Index(s2))9}10import (11func main() {12 fmt.Println("Index of byte s2 in s1 is: ", s1.IndexByte(s2))13}14import (15func main() {16 fmt.Println("Index of rune s2 in s1 is: ", s1.IndexRune(s2))17}

Full Screen

Full Screen

Len

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println(obj.Len())4}5import (6func main() {7 fmt.Println(obj.Len())8}9import (10func Len() int {11}12func main() {13 fmt.Println(Len())14}15import (16func Len() int {17}18func main() {19 fmt.Println(Len())20}21import (22func Len() int {

Full Screen

Full Screen

Len

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Name:", p.Name)4 fmt.Println("Age:", p.Age)5 fmt.Println("Length of Name:", p.Len())6}7import (8type Person struct {9}10func (p Person) Len() int {11 return len(p.Name)12}13func main() {14 fmt.Println("Name:", p.Name)15 fmt.Println("Age:", p.Age)16 fmt.Println("Length of Name:", p.Len())17}

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful