Golang fmt.Sscanf类(方法)实例源码

下面列出了Golang fmt.Sscanf 类(方法)源码代码实例,从而了解它的用法。

作者:yufeng10    项目:goleveld   
func (p *file) parse(name string) bool {
	var num uint64
	var tail string
	_, err := fmt.Sscanf(name, "%d.%s", &num, &tail)
	if err == nil {
		switch tail {
		case "log":
			p.t = TypeLog
		case "sst":
			p.t = TypeTable
		case "dbtmp":
			p.t = TypeTemp
		default:
			return false
		}
		p.num = num
		return true
	}
	n, _ := fmt.Sscanf(name, "MANIFEST-%d%s", &num, &tail)
	if n == 1 {
		p.t = TypeManifest
		p.num = num
		return true
	}

	return false
}

作者:gbi    项目:screencastinato   
func (ttyfd TTY) readCursorPosition() (int, int) {
	ttyfd.write(READ_CURSOR_POSITION)
	var chr byte
	var nb []byte = make([]byte, 0)
	var x, y int

	chr, _, _ = ttyfd.Readchr()
	if chr != ESC_CHR {
		return 0, 0 // something failed !
	}
	chr, _, _ = ttyfd.Readchr()
	if chr != '[' {
		return 0, 0 // something failed !
	}

	for chr != ';' {
		chr, _, _ = ttyfd.Readchr()
		nb = append(nb, chr)
	}
	fmt.Sscanf(string(nb), "%d", &x)
	nb = make([]byte, 0)
	for chr != 'R' {
		chr, _, _ = ttyfd.Readchr()
		nb = append(nb, chr)
	}
	fmt.Sscanf(string(nb), "%d", &y)
	return x, y

}

作者:mpdroo    项目:smtp   
/*
The "put" command is for any process that wants to insert a job into the queue.
It comprises a command line followed by the job body:

put <pri> <delay> <ttr> <bytes>\r\n
<data>\r\n

It inserts a job into the client's currently used tube (see the "use" command
below).

 - <pri> is an integer < 2**32. Jobs with smaller priority values will be
   scheduled before jobs with larger priorities. The most urgent priority is 0;
   the least urgent priority is 4,294,967,295.

 - <delay> is an integer number of seconds to wait before putting the job in
   the ready queue. The job will be in the "delayed" state during this time.

 - <ttr> -- time to run -- is an integer number of seconds to allow a worker
   to run this job. This time is counted from the moment a worker reserves
   this job. If the worker does not delete, release, or bury the job within
   <ttr> seconds, the job will time out and the server will release the job.
   The minimum ttr is 1. If the client sends 0, the server will silently
   increase the ttr to 1.

 - <bytes> is an integer indicating the size of the job body, not including the
   trailing "\r\n". This value must be less than max-job-size (default: 2**16).

 - <data> is the job body -- a sequence of bytes of length <bytes> from the
   previous line.

After sending the command line and body, the client waits for a reply, which
may be:

 - "INSERTED <id>\r\n" to indicate success.

   - <id> is the integer id of the new job

 - "BURIED <id>\r\n" if the server ran out of memory trying to grow the
   priority queue data structure.

   - <id> is the integer id of the new job

 - "EXPECTED_CRLF\r\n" The job body must be followed by a CR-LF pair, that is,
   "\r\n". These two bytes are not counted in the job size given by the client
   in the put command line.

 - "JOB_TOO_BIG\r\n" The client has requested to put a job with a body larger
   than max-job-size bytes.

 - "DRAINING\r\n" This means that the server has been put into "drain mode"
   and is no longer accepting new jobs. The client should try another server
   or disconnect and try again later.
*/
func (this *BeanstalkdClient) Put(priority uint32, delay, ttr time.Duration, data []byte) (id uint64, err error) {
	cmd := fmt.Sprintf("put %d %d %d %d\r\n", priority, uint64(delay.Seconds()), uint64(ttr.Seconds()), len(data))
	cmd = cmd + string(data) + string(crnl)

	_, reply, err := this.sendReply(cmd)

	if err != nil {
		return 0, err
	}

	switch {
	case strings.Index(reply, "INSERTED") == 0:
		var id uint64
		_, perr := fmt.Sscanf(reply, "INSERTED %d\r\n", &id)
		return id, perr
	case strings.Index(reply, "BURIED") == 0:
		var id uint64
		_, perr := fmt.Sscanf(reply, "BURIED %d\r\n", &id)
		return id, perr
	case reply == "EXPECTED_CRLF\r\n":
		return 0, errExpectedCrlf
	case reply == "JOB_TOO_BIG\r\n":
		return 0, errJobTooBig
	case reply == "DRAINING\r\n":
		return 0, errDraining
	default:
		return 0, this.parseError(reply)
	}

}

作者:pombredann    项目:ba   
func BlockStorageFactory(opts map[string]string) (res Storage, err error) {
	op := &BlockStorageOptions{"data", 2, 32, 32}
	var ok bool
	var tmp string

	if tmp, ok = opts["root"]; ok {
		op.Root = tmp
	}
	if tmp, ok = opts["split"]; ok {
		if _, err = fmt.Sscanf(tmp, "%d", op.Split); err != nil {
			return
		}
	}
	if tmp, ok = opts["max-files"]; ok {
		if _, err = fmt.Sscanf(tmp, "%d", op.MaxFiles); err != nil {
			return
		}
	}
	if tmp, ok = opts["pool"]; ok {
		if _, err = fmt.Sscanf(tmp, "%d", op.PoolSize); err != nil {
			return
		}
	}

	res = NewBlockStorage(op)
	return
}

作者:elasticdo    项目:go-option   
// Example custom option callback
func MyParseCallback(spec *options.OptionSpec, option string, argument *string) {
	if argument != nil {
		switch spec.GetCanonical(option) {
		case "input-encoding":
			in = *argument
		case "output-encoding":
			out = *argument
		case "repeat":
			fmt.Sscanf(*argument, "%d", &r)
		case "cookie-chance":
			fmt.Sscanf(*argument, "%f", &c)
			cInt = int64(c * 1000)
		default:
			spec.PrintUsageAndExit("Unknown option: " + option)
		}
	} else {
		switch spec.GetCanonical(option) {
		case "number":
			n = true
		case "escape":
			e = true
		case "verbose":
			v++
		default:
			if option == "help" {
				spec.PrintUsageAndExit("") // No error
			} else {
				spec.PrintUsageAndExit("Unknown option: " + option)
			}
		}
	}
}

作者:Gloria    项目:docke   
func ParseRelease(release string) (*KernelVersionInfo, error) {
	var (
		kernel, major, minor, parsed int
		flavor, partial              string
	)

	// Ignore error from Sscanf to allow an empty flavor.  Instead, just
	// make sure we got all the version numbers.
	parsed, _ = fmt.Sscanf(release, "%d.%d%s", &kernel, &major, &partial)
	if parsed < 2 {
		return nil, errors.New("Can't parse kernel version " + release)
	}

	// sometimes we have 3.12.25-gentoo, but sometimes we just have 3.12-1-amd64
	parsed, _ = fmt.Sscanf(partial, ".%d%s", &minor, &flavor)
	if parsed < 1 {
		flavor = partial
	}

	return &KernelVersionInfo{
		Kernel: kernel,
		Major:  major,
		Minor:  minor,
		Flavor: flavor,
	}, nil
}

作者:robvanmieghe    项目:Si   
// LoadString loads a hex representation (including checksum) of an unlock hash
// into an unlock hash object. An error is returned if the string is invalid or
// fails the checksum.
func (uh *UnlockHash) LoadString(strUH string) error {
	// Check the length of strUH.
	if len(strUH) != crypto.HashSize*2+UnlockHashChecksumSize*2 {
		return ErrUnlockHashWrongLen
	}

	// Decode the unlock hash.
	var byteUnlockHash []byte
	var checksum []byte
	_, err := fmt.Sscanf(strUH[:crypto.HashSize*2], "%x", &byteUnlockHash)
	if err != nil {
		return err
	}

	// Decode and verify the checksum.
	_, err = fmt.Sscanf(strUH[crypto.HashSize*2:], "%x", &checksum)
	if err != nil {
		return err
	}
	expectedChecksum := crypto.HashBytes(byteUnlockHash)
	if !bytes.Equal(expectedChecksum[:UnlockHashChecksumSize], checksum) {
		return ErrInvalidUnlockHashChecksum
	}

	copy(uh[:], byteUnlockHash[:])
	return nil
}

作者:nikai3    项目:ce-challenge   
func main() {
	data, err := os.Open(os.Args[1])
	if err != nil {
		log.Fatal(err)
	}
	defer data.Close()

	var (
		n, id  int
		x, y   float64
		places []place
		path   []int
	)
	scanner := bufio.NewScanner(data)
	for scanner.Scan() {
		t := strings.Fields(scanner.Text())
		fmt.Sscan(t[0], &id)
		fmt.Sscanf(t[len(t)-2], "(%f,", &x)
		fmt.Sscanf(t[len(t)-1], "%f)", &y)
		places = append(places, place{id, x, y})
		path = append(path, n)
		n++
	}
	shortestPath, _ := findPath(path, []int{}, 0, tour(places, path), len(path), places)
	for _, i := range shortestPath {
		fmt.Println(places[i].id)
	}
}

作者:gite    项目:codeforces-an   
func main() {

	var n int
	fmt.Scanf("%d\n", &n)
	re := regexp.MustCompile("(R\\d+C\\d+)|(([A-Z]+)(\\d+))")

	for i := 0; i < n; i++ {

		var k string
		fmt.Scanf("%s\n", &k)

		ss := re.FindStringSubmatch(k)

		if len(ss[1]) > 0 {
			var a, b int
			fmt.Sscanf(ss[1], "R%dC%d", &a, &b)
			fmt.Printf("%s%d\n", itos(b), a)
		}

		if len(ss[2]) > 0 {
			a := ss[3]
			var b int
			fmt.Sscanf(ss[4], "%d", &b)
			fmt.Printf("R%dC%d\n", b, stoi(a))
		}
	}

}

作者:shawshinin    项目:Codingam   
func main() {
	cgreader.RunStaticPrograms(
		cgreader.GetFileList("../../input/horse_dual_%d.txt", 3),
		cgreader.GetFileList("../../output/horse_dual_%d.txt", 3),
		true,
		func(input <-chan string, output chan string) {
			var n int
			fmt.Sscanf(<-input, "%d", &n)

			horses := make([]int, n)
			for i := range horses {
				fmt.Sscanf(<-input, "%d", &horses[i])
			}

			sort.Sort(intArray(horses))

			D := math.MaxInt32
			for i := 1; i < n; i++ {
				x := horses[i-1] - horses[i]

				if x < 0 {
					x *= -1
				}

				if x < D {
					D = x
				}
			}

			output <- fmt.Sprintf("%d", D)
		})
}

作者:cdshan    项目:minimeg   
func ParseKeyEvent(arg string) (*KeyEvent, error) {
	var key string
	var down bool

	_, err := fmt.Sscanf(arg, _KeyEventFmt, &down, &key)
	if err != nil {
		return nil, err
	}

	m := &KeyEvent{}

	m.Key, err = xStringToKeysym(key)
	if err != nil {
		fmt.Println(err.Error())
		_, err = fmt.Sscanf(key, "%U", &m.Key)
		if err != nil {
			fmt.Println(err.Error())
			return nil, fmt.Errorf("unknown key: `%s`", key)
		}
	}

	if down {
		m.DownFlag = 1
	}

	return m, nil
}

作者:aarzill    项目:chad   
func IntBytes(arg string) (bool, int, []byte) {
	if !BytesRE.MatchString(arg) {
		return false, -1, nil
	}

	r := make([]byte, 0)

	for _, segment := range strings.Split(arg, " ", -1) {
		var n byte

		switch len(segment) {
		case 2:
			_, err := fmt.Sscanf(segment, "%x", &n)
			if err != nil {
				return false, -1, nil
			}
			r = append(r, n)
		case 4:
			_, err := fmt.Sscanf(segment[0:2], "%x", &n)
			if err != nil {
				return false, -1, nil
			}
			r = append(r, n)
			_, err = fmt.Sscanf(segment[2:], "%x", &n)
			if err != nil {
				return false, -1, nil
			}
			r = append(r, n)
		default:
			return false, -1, nil
		}
	}

	return true, -1, r
}

作者:qeedqua    项目:misc_utilitie   
func lsusb(path string) error {
	f, err := os.Open(path)
	if err != nil {
		return nil
	}
	defer f.Close()

	var bus, dev, pid, vid, i int
	s := bufio.NewScanner(f)
	for s.Scan() {
		line := s.Text()
		n1, _ := fmt.Sscanf(line, "BUSNUM=%d\n", &bus)
		n2, _ := fmt.Sscanf(line, "DEVNUM=%d\n", &dev)
		n3, _ := fmt.Sscanf(line, "PRODUCT=%x/%x\n", &pid, &vid)
		if n1 != 0 || n2 != 0 || n3 != 0 {
			i++
		}
		if i == 3 {
			devices = append(devices, Device{bus, dev, pid, vid})
			break
		}
	}

	return nil
}

作者:joshi    项目:lochnes   
// WatchdogEnabled checks whether the service manager expects watchdog keep-alive notifications and
// returns the timeout value in µs. A timeout value of 0 signifies no notifications are expected.
func WatchdogEnabled() (time.Duration, error) {
	spid := os.Getenv("WATCHDOG_PID")
	if spid != "" {
		pid := 0
		n, err := fmt.Sscanf(spid, "%d", &pid)
		if err != nil {
			return 0, err
		}
		if n != 1 {
			return 0, errors.New("could not scan WATCHDOG_PID")
		}
		if pid != os.Getpid() {
			return 0, nil
		}
	}

	sttl := os.Getenv("WATCHDOG_USEC")
	if sttl == "" {
		return 0, errors.New("missing WATCHDOG_USEC")
	}
	ttl := uint64(0)
	n, err := fmt.Sscanf(sttl, "%d", &ttl)
	if err != nil {
		return 0, err
	}
	if n != 1 {
		return 0, errors.New("could not scan WATCHDOG_USEC")
	}
	return time.Duration(ttl) * time.Microsecond, nil
}

作者:lanio    项目:up   
func stringRangeWorker(rangeRepr string, ch chan int) {
	for _, part := range strings.Split(rangeRepr, ",") {
		var from, to int
		var err error

		data := []byte(part)
		if match := numberRe.FindSubmatch(data); match != nil {
			fmt.Sscanf(string(match[1]), "%d", &from)
			to = from
		} else if match := rangeRe.FindSubmatch(data); match != nil {
			fmt.Sscanf(string(match[1]), "%d", &from)
			fmt.Sscanf(string(match[2]), "%d", &to)
		} else {
			break
		}

		if err != nil {
			break
		}

		for i := from; i <= to; i++ {
			ch <- i
		}
	}
	close(ch)
}

作者:vil    项目:ai-contes   
func ParseGameState(lines []string) *PlanetWars {
	pw := &PlanetWars{make([]*Planet, len(lines)), make([]*Fleet, len(lines))}
	pNum, fNum := 0, 0

	for _, ln := range lines {

		switch ln[0] {
		case 'P':
			p := &Planet{ID: pNum}
			read, e := fmt.Sscanf(ln[2:], "%f %f %d %d %d", &p.X, &p.Y, &p.Owner, &p.NumShips, &p.GrowthRate)

			if read < 5 || e != nil {
				log.Stderrf("Bad line in input: %s\n", ln)
			}
			pw.Planets[pNum] = p
			pNum++
		case 'F':
			f := &Fleet{ID: fNum}
			read, e := fmt.Sscanf(ln[2:], "%d %d %d %d %d", &f.Owner, &f.NumShips, &f.Source, &f.Dest, &f.TripLength, &f.TurnsRemaining)

			if read < 5 || e != nil {
				log.Stderrf("Bad line in input: %s\n", ln)
			}
			pw.Fleets[fNum] = f
			fNum++
		default:
			log.Stderr("Error parsing gamestate: First char of line not 'P' or 'F'\n")
			return nil
		}
	}

	pw.Fleets = pw.Fleets[0:fNum]
	pw.Planets = pw.Planets[0:pNum]
	return pw
}

作者:shawshinin    项目:Codingam   
func main() {
	cgreader.RunStaticPrograms(
		cgreader.GetFileList("../../input/tan_network_%d.txt", 6),
		cgreader.GetFileList("../../output/tan_network_%d.txt", 6),
		true,
		func(input <-chan string, output chan string) {
			// this block could be ommited when solo-running
			minCost = math.MaxUint16
			routes, finalRoute = nil, nil

			start, stop := GetInput(input), GetInput(input)
			hashMap = make(map[uint32]string)
			identifierMap = make(map[string]uint32)
			stationsMC = make(map[uint32]uint16)

			var ns, nr uint32
			fmt.Sscanf(<-input, "%d", &ns)
			stations := make(map[uint32]Station)
			for i := uint32(0); i < ns; i++ {
				station := GetInput(input)
				info := strings.Split(station, ",")
				hashMap[i] = info[0]
				identifierMap[info[0]] = i
				stations[i] = Station{
					info[1][1 : len(info[1])-1],
					ToFloat(info[3]),
					ToFloat(info[4])}
			}

			startHash, finalHash = identifierMap[start], identifierMap[stop]

			if startHash == finalHash {
				output <- stations[startHash].name
				return
			}

			fmt.Sscanf(<-input, "%d", &nr)
			routes = make(map[uint32][]Destination)
			for i := uint32(0); i < nr; i++ {
				route := GetInput(input)
				ra, ro := string(route[:4]), string(route[14:])
				ha, ho := identifierMap[ra], identifierMap[ro]

				a, b := stations[ha], stations[ho]
				cost := GetCost(a.latitude, b.latitude, a.longitude, b.longitude)

				routes[ha] = append(routes[ha], Destination{ho, cost})
			}

			TravelRecursive(0, append(make([]uint32, 0), startHash))

			if finalRoute == nil {
				output <- "IMPOSSIBLE\n"
			} else {
				for _, hash := range finalRoute {
					output <- fmt.Sprintln(stations[hash].name)
				}
			}
		})
}

作者:wercke    项目:wercke   
// formatCompleteOutput will format the message m as an completed message.
func formatCompleteOutput(m *jsonmessage.JSONMessage) string {
	if strings.HasPrefix(m.Status, "The push refers to a repository") {
		return "Pushing to registry"
	}

	if strings.HasPrefix(m.Status, "Pushing repository") &&
		strings.HasSuffix(m.Status, "tags)") {
		tags := 0
		registry := ""
		fmt.Sscanf(m.Status, "Pushing repository %s (%d tags)", &registry, &tags)
		return fmt.Sprintf("Pushing %d tag(s)", tags)
	}

	if strings.HasPrefix(m.Status, "Pushing tag for rev [") &&
		strings.HasSuffix(m.Status, "};") {
		image := ""
		registry := ""
		fmt.Sscanf(m.Status, "Pushing tag for rev [%s] on {%s};", &image, &registry)
		image = strings.TrimSuffix(image, "]")
		return fmt.Sprintf("Pushing tag for image: %s", image)
	}

	if m.ID != "" {
		return fmt.Sprintf("%s: %s", m.Status, m.ID)
	}

	return m.Status
}

作者:oorj    项目:ce-challenge   
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() {
		s := strings.Split(scanner.Text(), ",")
		var l, m int
		fmt.Sscanf(strings.TrimSpace(s[0]), "%d", &m)
		for _, i := range s {
			var v int
			fmt.Sscanf(strings.TrimSpace(i), "%d", &v)
			if v > m {
				m = v
			}
			if v+l > m {
				m = v + l
			}
			if v+l > 0 {
				l += v
			} else {
				l = 0
			}
		}
		fmt.Println(m)
	}
}

作者:sara6    项目:centrifug   
// placepic puts a SVG file at a location
func placepic(x, y int, filename string) (int, int) {
	var (
		s             SVG
		width, height int
		wunit, hunit  string
	)
	f, err := os.Open(filename)
	if err != nil {
		fmt.Fprintf(os.Stderr, "%v\n", err)
		return 0, 0
	}
	defer f.Close()
	if err := xml.NewDecoder(f).Decode(&s); err != nil {
		fmt.Fprintf(os.Stderr, "Unable to parse (%v)\n", err)
		return 0, 0
	}

	// read the width and height, including any units
	// if there are errors use 10 as a default
	nw, _ := fmt.Sscanf(s.Width, "%d%s", &width, &wunit)
	if nw < 1 {
		width = 10
	}
	nh, _ := fmt.Sscanf(s.Height, "%d%s", &height, &hunit)
	if nh < 1 {
		height = 10
	}
	canvas.Group(`clip-path="url(#pic)"`, fmt.Sprintf(`transform="translate(%d,%d)"`, x, y))
	canvas.ClipPath(`id="pic"`)
	canvas.Rect(0, 0, width, height)
	canvas.ClipEnd()
	io.WriteString(canvas.Writer, s.Doc)
	canvas.Gend()
	return width, height
}


问题


面经


文章

微信
公众号

扫码关注公众号