func TestUnmarshal(t *testing.T) {
	for i, tt := range unmarshalTests {
		var scan Scanner
		in := []byte(tt.in)
		if err := checkValid(in, &scan); err != nil {
			if !reflect.DeepEqual(err, tt.err) {
				t.Errorf("#%d: checkValid: %#v", i, err)
				continue
			}
		}
		if tt.ptr == nil {
			continue
		}

		// v = new(right-type)
		v := reflect.New(reflect.TypeOf(tt.ptr).Elem())
		dec := NewDecoder(bytes.NewReader(in))
		if tt.useNumber {
			dec.UseNumber()
		}
		if err := dec.Decode(v.Interface()); !reflect.DeepEqual(err, tt.err) {
			t.Errorf("#%d: %v, want %v", i, err, tt.err)
			continue
		} else if err != nil {
			continue
		}
		if !reflect.DeepEqual(v.Elem().Interface(), tt.out) {
			t.Errorf("#%d: mismatch\nhave: %#+v\nwant: %#+v", i, v.Elem().Interface(), tt.out)
			data, _ := Marshal(v.Elem().Interface())
			println(string(data))
			data, _ = Marshal(tt.out)
			println(string(data))
			continue
		}

		// Check round trip.
		if tt.err == nil {
			enc, err := Marshal(v.Interface())
			if err != nil {
				t.Errorf("#%d: error re-marshaling: %v", i, err)
				continue
			}
			vv := reflect.New(reflect.TypeOf(tt.ptr).Elem())
			dec = NewDecoder(bytes.NewReader(enc))
			if tt.useNumber {
				dec.UseNumber()
			}
			if err := dec.Decode(vv.Interface()); err != nil {
				t.Errorf("#%d: error re-unmarshaling %#q: %v", i, enc, err)
				continue
			}
			if !reflect.DeepEqual(v.Elem().Interface(), vv.Elem().Interface()) {
				t.Errorf("#%d: mismatch\nhave: %#+v\nwant: %#+v", i, v.Elem().Interface(), vv.Elem().Interface())
				t.Errorf("     In: %q", strings.Map(noSpace, string(in)))
				t.Errorf("Marshal: %q", strings.Map(noSpace, string(enc)))
				continue
			}
		}
	}
}
Example #2
0
// splitList splits a comma-separated list into a slice of strings, accounting
// for escape characters.
func splitList(source string) (results []string) {
	var (
		isEscaped, hasEscape bool
		lastIndex, index     int
	)
	for ; index < len(source); index++ {
		if isEscaped {
			isEscaped = false
			continue
		}
		switch source[index] {
		case '\\':
			isEscaped = true
			hasEscape = true

		case ',':
			result := source[lastIndex:index]
			if hasEscape {
				result = strings.Map(removeEscape, result)
				hasEscape = false
			}
			results = append(results, result)
			lastIndex = index + 1
		}
	}
	if lastIndex < index {
		result := source[lastIndex:]
		if hasEscape {
			result = strings.Map(removeEscape, result)
		}
		results = append(results, result)
	}
	return results
}
Example #3
0
func (desc *FileDescriptorSet) FindExtension(packageName string, typeName string, fieldName string) (extPackageName string, field *FieldDescriptorProto) {
	parent := desc.GetMessage(packageName, typeName)
	if parent == nil {
		return "", nil
	}
	if !parent.IsExtendable() {
		return "", nil
	}
	extendee := "." + packageName + "." + typeName
	for _, file := range desc.GetFile() {
		for _, ext := range file.GetExtension() {
			if strings.Map(dotToUnderscore, file.GetPackage()) == strings.Map(dotToUnderscore, packageName) {
				if !(ext.GetExtendee() == typeName || ext.GetExtendee() == extendee) {
					continue
				}
			} else {
				if ext.GetExtendee() != extendee {
					continue
				}
			}
			if ext.GetName() == fieldName {
				return file.GetPackage(), ext
			}
		}
	}
	return "", nil
}
Example #4
0
File: out.go Project: Harvey-OS/go
// Return the package prefix when using gccgo.
func (p *Package) gccgoSymbolPrefix() string {
	if !*gccgo {
		return ""
	}

	clean := func(r rune) rune {
		switch {
		case 'A' <= r && r <= 'Z', 'a' <= r && r <= 'z',
			'0' <= r && r <= '9':
			return r
		}
		return '_'
	}

	if *gccgopkgpath != "" {
		return strings.Map(clean, *gccgopkgpath)
	}
	if *gccgoprefix == "" && p.PackageName == "main" {
		return "main"
	}
	prefix := strings.Map(clean, *gccgoprefix)
	if prefix == "" {
		prefix = "go"
	}
	return prefix + "." + p.PackageName
}
Example #5
0
func ShouldContainModuloWhiteSpace(haystack interface{}, expectedNeedle ...interface{}) string {
	if fail := need(1, expectedNeedle); fail != success {
		return fail
	}

	value, valueIsString := haystack.(string)
	expecNeedle, expecIsString := expectedNeedle[0].(string)

	if !valueIsString || !expecIsString {
		return fmt.Sprintf(shouldBothBeStrings, reflect.TypeOf(haystack), reflect.TypeOf(expectedNeedle[0]))
	}

	elimWs := func(r rune) rune {
		if r == ' ' || r == '\t' || r == '\n' {
			return -1 // drop the rune
		}
		return r
	}

	h := strings.Map(elimWs, value)
	n := strings.Map(elimWs, expecNeedle)

	if strings.Contains(h, n) {
		return success
	}

	return fmt.Sprintf(shouldContainModuloWS, value, expecNeedle)
}
Example #6
0
func getFieldNumber(descriptorSet *descriptor.FileDescriptorSet, rootPkg string, rootMsg string, msg *descriptor.DescriptorProto, fieldNum int32) *descriptor.FieldDescriptorProto {
	for _, f := range msg.GetField() {
		if f.GetNumber() == fieldNum {
			return f
		}
	}
	if !msg.IsExtendable() {
		return nil
	}
	extendee := "." + rootPkg + "." + rootMsg
	for _, file := range descriptorSet.GetFile() {
		for _, ext := range file.GetExtension() {
			if strings.Map(dotToUnderscore, file.GetPackage()) == strings.Map(dotToUnderscore, rootPkg) {
				if !(ext.GetExtendee() == rootMsg || ext.GetExtendee() == extendee) {
					continue
				}
			} else {
				if ext.GetExtendee() != extendee {
					continue
				}
			}
			if ext.GetNumber() == fieldNum {
				return ext
			}
		}
	}
	return nil
}
Example #7
0
func (n Name) String() (s string) {
	s = strings.TrimLeft(string(n), "0123456789")

	valid := func(r rune) rune {
		if r >= '0' && r <= '9' {
			return r
		}
		if r >= 'a' && r <= 'z' {
			return r
		}
		if r >= 'A' && r <= 'Z' {
			return r
		}
		if r == '_' || r == '-' {
			return '_'
		}
		return -1
	}
	s = strings.Map(valid, s)

	if len(s) == 0 {
		return "_" + strings.Map(valid, string(n))
	}
	return strings.Title(s)
}
Example #8
0
func TestFault(t *testing.T) {
	f := &Fault{Code: 4, Message: "Too many parameters."}
	buf := bytes.NewBuffer(nil)
	err := Marshal(buf, "", f)
	if err != nil {
		t.Fatal(fmt.Sprintf("error marshalling Fault: %s", err))
	}
	t.Logf("marshalled fault: %s", buf.Bytes())

	repl := func(r rune) rune {
		switch r {
		case ' ', '\t', '\n', '\r':
			return -1
		}
		return r
	}
	f1S := strings.Map(repl, buf.String())
	f2S := strings.Map(repl, xmlFault)
	if f1S != f2S {
		t.Errorf("fatal != constant\n%s\n!=\n%s", f1S, f2S)
	}

	_, _, f2, err := Unmarshal(bytes.NewBuffer(buf.Bytes()))
	if err != nil {
		t.Fatalf("cannot unmarshal previously marshalled fault (\n%s\n):%s",
			buf, err)
	}
	if f2.String() != f.String() {
		t.Errorf("f1=%s != f2=%s", f, f2)
	}
}
Example #9
0
// SignPolicy return the proper signature and other parameters needed to
// generate a valid Cloudfront Signed URL.
// For canned policies this is: Expires, Signature, Key-Pair-Id
// For custom policies this is: Policy, Signature, Key-Pair-Id
//
// More information:
//   http://goo.gl/pvA97e
// Command line equivalent:
//   cat policy | openssl sha1 -sign cloudfront-keypair.pem | openssl base64 | tr '+=/' '-_~'
func SignPolicy(privateKey PrivateKey, policy PolicySigner, keyPairID string) (string, error) {
	signature, err := policy.signWithPrivateKey(privateKey)
	if err != nil {
		return "", fmt.Errorf("Cannot sign policy: %v", err)
	}

	encoding := base64.NewEncoding(encodeCloudFront)
	paddingMap := func(r rune) rune {
		switch r {
		case '=':
			return '_'
		default:
			return r
		}
	}

	switch policy.(type) {
	case CannedPolicy:
		return fmt.Sprintf("Expires=%d&Signature=%s&Key-Pair-Id=%s",
			policy.(CannedPolicy).ExpiresAt.Unix(),
			strings.Map(paddingMap, encoding.EncodeToString(signature)),
			keyPairID,
		), nil
	case CustomPolicy:
		return fmt.Sprintf("Policy=%s&Signature=%s&Key-Pair-Id=%s",
			strings.Map(paddingMap, encoding.EncodeToString([]byte(policy.String()))),
			strings.Map(paddingMap, encoding.EncodeToString(signature)),
			keyPairID,
		), nil
	}
	return "", nil
}
Example #10
0
func (l *LibSuite) TestLetterOnlyMapFunction(c *C) {
	var input string = "ABC123"
	var output string = strings.Map(letterOnlyMapF, input)
	c.Assert(output, Equals, "ABC")
	input = "abc123"
	output = strings.Map(letterOnlyMapF, input)
	c.Assert(output, Equals, "ABC")
}
Example #11
0
// ToUpper takes the given string and upper cases it based on the
// current CASEMAPPING setting given by the server.
func (s *State) ToUpper(name string) string {
	switch *s.ISupport("CASEMAPPING") {
	case "ascii":
		return strings.Map(ASCIIToUpper, name)
	case "strict-rfc1459":
		return strings.Map(StrictRFC1459ToUpper, name)
	}

	return strings.Map(RFC1459ToUpper, name)
}
Example #12
0
func compare(solution, output string) string {
	switch {
	case solution == output:
		return "Accepted"
	case strings.Map(keepNum, solution) == strings.Map(keepNum, output):
		return "Presentation Error"
	default:
		return "Wrong Answer"
	}
}
Example #13
0
File: lib.go Project: 06linux/xlsx
// getCoordsFromCellIDString returns the zero based cartesian
// coordinates from a cell name in Excel format, e.g. the cellIDString
// "A1" returns 0, 0 and the "B3" return 1, 2.
func getCoordsFromCellIDString(cellIDString string) (x, y int, error error) {
	var letterPart string = strings.Map(letterOnlyMapF, cellIDString)
	y, error = strconv.Atoi(strings.Map(intOnlyMapF, cellIDString))
	if error != nil {
		return x, y, error
	}
	y -= 1 // Zero based
	x = lettersToNumeric(letterPart)
	return x, y, error
}
Example #14
0
File: main.go Project: noxiouz/gorb
func invokeFunc(vs, rs string, ports []gdc.APIPort, fn portAction) []error {
	n := 0
	e := []error{}

	for _, binding := range ports {
		if binding.PrivatePort == 0 || binding.PublicPort == 0 {
			// There is a bug in GDC where unexported ports will have PrivatePort
			// set to zero, instead of PublicPort. So checking both, just in case.
			continue
		}

		if binding.IP == "0.0.0.0" {
			// Rewrite "catch-all" host to a real host's IP address.
			binding.IP = hostIPs[0].String()
		}

		// Mangle the VS name.
		vsID := fmt.Sprintf("%s-%d-%s", strings.Map(func(r rune) rune {
			switch r {
			case '/', ':':
				return '-'
			default:
				return r
			}
		}, vs), binding.PrivatePort, binding.Type)

		// Mangle the RS name.
		rsID := fmt.Sprintf("%s-%d-%s", strings.Map(func(r rune) rune {
			switch r {
			case '/', ':':
				return '-'
			default:
				return r
			}
		}, rs), binding.PublicPort, binding.Type)

		// There must be leading slash in the swarm event stream for node names that needs
		// to be trimmed now that it has been munged
		rsID = strings.Trim(rsID, "-")

		if err := fn(vsID, rsID, binding); err == nil {
			n++
		} else {
			e = append(e, err)
		}
	}

	if n == 0 {
		log.Warnf("no public ports were processed for [%s]", path.Join(vs, rs))
	}

	return e
}
Example #15
0
func TestLetterOnlyMapFunction(t *testing.T) {
	var input string = "ABC123"
	var output string = strings.Map(letterOnlyMapF, input)
	if output != "ABC" {
		t.Error("Expected output == 'ABC' but got ", output)
	}
	input = "abc123"
	output = strings.Map(letterOnlyMapF, input)
	if output != "ABC" {
		t.Error("Expected output == 'ABC' but got ", output)
	}
}
Example #16
0
// GetGame attempts to populates the Game from data sources in oder.
func (r *ROM) GetGame(data []ds.DS, opts *GameOpts) error {
	if opts == nil {
		opts = &GameOpts{}
	}
	var err error
	var id string
	var prettyName string
	var game *ds.Game
	files := []string{r.Path}
	if r.Cue {
		files = append(files, r.Bins...)
	}
Loop:
	for _, file := range files {
		for _, source := range data {
			prettyName = source.GetName(file)
			id, err = source.GetID(file)
			if err != nil {
				continue
			}
			game, err = source.GetGame(id)
			if err != nil {
				continue
			}
			break Loop
		}
	}
	if game == nil {
		if err == ds.NotFoundErr {
			r.NotFound = true
		}
		if err != ds.NotFoundErr || !opts.AddNotFound {
			return err
		}
		game = &ds.Game{GameTitle: r.BaseName}
	}
	if !opts.NoPrettyName && prettyName != "" {
		game.GameTitle = prettyName
	}
	if opts.UseFilename {
		game.GameTitle = r.BaseName
	}
	if !opts.NoStripUnicode {
		game.Overview = strings.Map(stripChars, game.Overview)
		game.GameTitle = strings.Map(stripChars, game.GameTitle)
	}
	if opts.OverviewLen != 0 && opts.OverviewLen > 0 && len(game.Overview) > opts.OverviewLen+3 {
		game.Overview = game.Overview[:opts.OverviewLen] + "..."
	}
	r.Game = game
	return nil
}
Example #17
0
func (desc *FileDescriptorSet) GetEnum(packageName string, typeName string) *EnumDescriptorProto {
	for _, file := range desc.GetFile() {
		if strings.Map(dotToUnderscore, file.GetPackage()) != strings.Map(dotToUnderscore, packageName) {
			continue
		}
		for _, enum := range file.GetEnumType() {
			if enum.GetName() == typeName {
				return enum
			}
		}
	}
	return nil
}
Example #18
0
func main() {
	fmt.Printf("%f\n", hypot(2.0, 2.0))

	theSum := sum(1, 2)
	fmt.Printf("theSum: %d\n", theSum)

	f := square
	fmt.Printf("square(%d) is %d\n", 3, f(3))

	fmt.Println(strings.Map(add1, "HAL-9000")) // "IBM.:111"
	fmt.Println(strings.Map(add1, "VMS"))      // "WNT"
	fmt.Println(strings.Map(add1, "Admix"))    // "Benjy"
}
Example #19
0
// Map returns a copy of the the string s with all its characters modified according to the mapping
// function if mapping returns a negative value, the character is dropped from the string with no replacement
func Map(mapping func(rune) rune, s string) string {
	rot13 := func(r rune) rune {
		switch {
		case r >= 'A' && r < 'Z':
			return 'A' + (r-'A'+13)%26
		case r >= 'a' && r <= 'z':
			return 'a' + (r-'a'+13)%26
		}
		return r
	}

	fmt.Println(strings.Map(rot13, "'Twas brillig and the slithy gopher...")) // 'Gjnf oevyyvt naq fyvgul tbcure...
	return strings.Map(mapping, s)
}
Example #20
0
func TestIntOnlyMapFunction(t *testing.T) {
	var input string = "ABC123"
	var output string = strings.Map(intOnlyMapF, input)
	if output != "123" {
		t.Error("Expected output == '123' but got ", output)
	}
}
Example #21
0
func Generate(input string, table string) string {
	output := strings.Map(func(r rune) rune {
		switch {
		case r == ' ', r == '-':
			return '-'
		case r == '_', unicode.IsLetter(r), unicode.IsDigit(r):
			return r
		default:
			return -1
		}
	}, strings.ToLower(strings.TrimSpace(input)))
	// Maximum of 75 characters for slugs right now
	maxLength := 75
	if len([]rune(output)) > maxLength {
		runes := []rune(output)[:maxLength]
		// Try to cut at '-' until length of (maxLength - (maxLength / 2)) characters
		for i := (maxLength - 1); i > (maxLength - (maxLength / 2)); i-- {
			if runes[i] == '-' {
				runes = runes[:i]
				break
			}
		}
		output = string(runes)
	}
	// Don't allow a few specific slugs that are used by the blog
	if table == "posts" && (output == "rss" || output == "tag" || output == "author" || output == "page" || output == "admin") {
		output = generateUniqueSlug(output, table, 2)
	} else if table == "tags" || table == "navigation" { // We want duplicate tag and navigation slugs
		return output
	}
	return generateUniqueSlug(output, table, 1)
}
Example #22
0
// Section 12.2.5.4.22.
func afterAfterFramesetIM(p *parser) bool {
	switch p.tok.Type {
	case CommentToken:
		p.doc.AppendChild(&Node{
			Type: CommentNode,
			Data: p.tok.Data,
		})
	case TextToken:
		// Ignore all text but whitespace.
		s := strings.Map(func(c rune) rune {
			switch c {
			case ' ', '\t', '\n', '\f', '\r':
				return c
			}
			return -1
		}, p.tok.Data)
		if s != "" {
			p.tok.Data = s
			return inBodyIM(p)
		}
	case StartTagToken:
		switch p.tok.DataAtom {
		case a.Html:
			return inBodyIM(p)
		case a.Noframes:
			return inHeadIM(p)
		}
	case DoctypeToken:
		return inBodyIM(p)
	default:
		// Ignore the token.
	}
	return true
}
Example #23
0
File: out.go Project: jnwhiteh/go
// writeOutput creates stubs for a specific source file to be compiled by 6g
// (The comments here say 6g and 6c but the code applies to the 8 and 5 tools too.)
func (p *Package) writeOutput(f *File, srcfile string) {
	base := srcfile
	if strings.HasSuffix(base, ".go") {
		base = base[0 : len(base)-3]
	}
	base = strings.Map(slashToUnderscore, base)
	fgo1 := creat("_obj/" + base + ".cgo1.go")
	fgcc := creat("_obj/" + base + ".cgo2.c")

	p.GoFiles = append(p.GoFiles, base+".cgo1.go")
	p.GccFiles = append(p.GccFiles, base+".cgo2.c")

	// Write Go output: Go input with rewrites of C.xxx to _C_xxx.
	fmt.Fprintf(fgo1, "// Created by cgo - DO NOT EDIT\n\n")
	fmt.Fprintf(fgo1, "//line %s:1\n", srcfile)
	printer.Fprint(fgo1, fset, f.AST)

	// While we process the vars and funcs, also write 6c and gcc output.
	// Gcc output starts with the preamble.
	fmt.Fprintf(fgcc, "%s\n", f.Preamble)
	fmt.Fprintf(fgcc, "%s\n", gccProlog)

	for _, n := range f.Name {
		if n.FuncType != nil {
			p.writeOutputFunc(fgcc, n)
		}
	}

	fgo1.Close()
	fgcc.Close()
}
Example #24
0
// NormalizeName normalizes to lowercase and Unicode Normalization Form C
// (NFC).
func NormalizeName(name string) string {
	lower := strings.Map(normalize.ToLower, name)
	if isASCII(lower) {
		return lower
	}
	return norm.NFC.String(lower)
}
Example #25
0
func main() {
	data, err := os.Open(os.Args[1])
	if err != nil {
		log.Fatal(err)
	}
	defer data.Close()
	scanner := bufio.NewScanner(data)
	for scanner.Scan() {
		maph := func(r rune) rune {
			if strings.Contains("0123456789", string(r)) {
				return r
			} else if strings.Contains("abcdefghij", string(r)) {
				return r - 'a' + '0'
			}
			return -1
		}
		t := strings.Map(maph, scanner.Text())

		if len(t) == 0 {
			fmt.Println("NONE")
		} else {
			fmt.Println(t)
		}
	}
}
Example #26
0
func (f *Faker) numerify(in string) string {
	return recGsub(numerifyPattern, in, func(s string) string {
		return strings.Map(func(r rune) rune {
			return rune(48 + rand.Intn(9))
		}, s)
	})
}
Example #27
0
// LimitedSepIdentifier builds an identifier out of multiple parts,
// all as lowercase strings and concatenated with the separator
// Non letters and digits are exchanged with dashes and
// reduced to a maximum of one each. If limit is true only
// 'a' to 'z' and '0' to '9' are allowed.
func LimitedSepIdentifier(sep string, limit bool, parts ...interface{}) string {
	iparts := make([]string, 0)
	for _, p := range parts {
		tmp := strings.Map(func(r rune) rune {
			// Check letter and digit.
			if unicode.IsLetter(r) || unicode.IsDigit(r) {
				lcr := unicode.ToLower(r)
				if limit {
					// Only 'a' to 'z' and '0' to '9'.
					if lcr <= unicode.MaxASCII {
						return lcr
					} else {
						return ' '
					}
				} else {
					// Every char is allowed.
					return lcr
				}
			}
			return ' '
		}, fmt.Sprintf("%v", p))
		// Only use non-empty identifier parts.
		if ipart := strings.Join(strings.Fields(tmp), "-"); len(ipart) > 0 {
			iparts = append(iparts, ipart)
		}
	}
	return strings.Join(iparts, sep)
}
Example #28
0
// GetElastiCacheEndpoints queries the ElastiCache Auto Discovery service
// for a list of memcached nodes in the cache cluster, using the given seed
// node.
func GetElastiCacheEndpoints(configEndpoint string) ([]string, error) {
	c, err := net.Dial("tcp", configEndpoint)
	if err != nil {
		return nil, err
	}
	defer c.Close()

	// http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/AutoDiscovery.AddingToYourClientLibrary.html
	reader, writer := bufio.NewReader(c), bufio.NewWriter(c)
	writer.Write([]byte("config get cluster\r\n"))
	writer.Flush()

	reader.ReadString('\n')
	reader.ReadString('\n')
	line, err := reader.ReadString('\n')
	if err != nil {
		return nil, err
	}

	hosts := strings.Split(line, " ")
	if len(hosts) == 0 {
		return nil, ErrNoElastiCache
	}

	endpoints := make([]string, 0, len(hosts))
	for _, v := range hosts {
		authority := strings.Split(strings.Map(dropSpace, v), "|")
		if len(authority) < 3 {
			continue
		}
		endpoints = append(endpoints, fmt.Sprintf("%s:%s", authority[1], authority[2]))
	}
	return endpoints, nil
}
Example #29
0
func tolerate(str string) string {
	return strings.Map(
		func(c rune) rune {
			switch c {
			case '\\':
				return '\'
			case '|':
				return '|'
			case '/':
				return '/'
			case '<':
				return '<'
			case '>':
				return '>'
			case '"':
				return '"'
			case ':':
				return ':'
			case '*':
				return '*'
			case '?':
				return '?'
			}
			return c
		}, strings.TrimSpace(str))
}
Example #30
0
// Section 12.2.5.4.22.
func afterAfterFramesetIM(p *parser) bool {
	switch p.tok.Type {
	case CommentToken:
		p.addChild(&Node{
			Type: CommentNode,
			Data: p.tok.Data,
		})
	case TextToken:
		// Ignore all text but whitespace.
		s := strings.Map(func(c rune) rune {
			switch c {
			case ' ', '\t', '\n', '\f', '\r':
				return c
			}
			return -1
		}, p.tok.Data)
		if s != "" {
			p.reconstructActiveFormattingElements()
			p.addText(s)
		}
	case StartTagToken:
		switch p.tok.Data {
		case "html":
			return inBodyIM(p)
		case "noframes":
			return inHeadIM(p)
		}
	default:
		// Ignore the token.
	}
	return true
}