Ejemplo n.º 1
1
// Symbol looks up the program counters listed in the request,
// responding with a table mapping program counters to function names.
// The package initialization registers it as /debug/pprof/symbol.
func Symbol(c *http.Conn, r *http.Request) {
	c.SetHeader("content-type", "text/plain; charset=utf-8")

	// We don't know how many symbols we have, but we
	// do have symbol information.  Pprof only cares whether
	// this number is 0 (no symbols available) or > 0.
	fmt.Fprintf(c, "num_symbols: 1\n")

	var b *bufio.Reader
	if r.Method == "POST" {
		b = bufio.NewReader(r.Body)
	} else {
		b = bufio.NewReader(strings.NewReader(r.URL.RawQuery))
	}

	for {
		w, err := b.ReadSlice('+')
		if err == nil {
			w = w[0 : len(w)-1] // trim +
		}
		pc, _ := strconv.Btoui64(string(w), 0)
		if pc != 0 {
			f := runtime.FuncForPC(uintptr(pc))
			if f != nil {
				fmt.Fprintf(c, "%#x %s\n", pc, f.Name())
			}
		}

		// Wait until here to check for err; the last
		// symbol will have an err because it doesn't end in +.
		if err != nil {
			break
		}
	}
}
Ejemplo n.º 2
0
func parseScript(line string, scripts map[string][]Script) {
	comment := strings.Index(line, "#")
	if comment >= 0 {
		line = line[0:comment]
	}
	line = strings.TrimSpace(line)
	if len(line) == 0 {
		return
	}
	field := strings.Split(line, ";")
	if len(field) != 2 {
		logger.Fatalf("%s: %d fields (expected 2)\n", line, len(field))
	}
	matches := scriptRe.FindStringSubmatch(line)
	if len(matches) != 4 {
		logger.Fatalf("%s: %d matches (expected 3)\n", line, len(matches))
	}
	lo, err := strconv.Btoui64(matches[1], 16)
	if err != nil {
		logger.Fatalf("%.5s...: %s", line, err)
	}
	hi := lo
	if len(matches[2]) > 2 { // ignore leading ..
		hi, err = strconv.Btoui64(matches[2][2:], 16)
		if err != nil {
			logger.Fatalf("%.5s...: %s", line, err)
		}
	}
	name := matches[3]
	scripts[name] = append(scripts[name], Script{uint32(lo), uint32(hi), name})
}
Ejemplo n.º 3
0
// Consume a single rune; assumes this is being invoked as the last possible
// option and will panic if an invalid escape sequence is found. Will return the
// found rune (as an integer) and with cursor past the entire representation.
func (p *parser) single_rune() int {
	if rune := p.src.curr(); rune != '\\' {
		// This is just a regular character; return it immediately.
		p.src.nextCh()
		return rune
	}

	if p.src.peek() == 'x' {
		// Match hex character code.
		var hex string
		p.src.nextCh()
		if p.src.nextCh() == '{' {
			hex = p.src.literal("{", "}")
		} else {
			hex = fmt.Sprintf("%c%c", p.src.curr(), p.src.nextCh())
			p.src.nextCh() // Step over the end of the hex code.
		}

		// Parse and return the corresponding rune.
		rune, err := strconv.Btoui64(hex, 16)
		if err != nil {
			panic(fmt.Sprintf("couldn't parse hex: %s", hex))
		}
		return int(rune)
	} else if rune := ESCAPES[p.src.peek()]; rune != 0 {
		// Literally match '\n', '\r', etc.
		p.src.nextCh()
		p.src.nextCh()
		return rune
	} else if unicode.Is(_punct, p.src.peek()) {
		// Allow punctuation to be blindly escaped.
		rune := p.src.nextCh()
		p.src.nextCh()
		return rune
	} else if unicode.IsDigit(p.src.peek()) {
		// Match octal character code (begins with digit, up to three digits).
		oct := ""
		p.src.nextCh()
		for i := 0; i < 3; i++ {
			oct += fmt.Sprintf("%c", p.src.curr())
			if !unicode.IsDigit(p.src.nextCh()) {
				break
			}
		}

		// Parse and return the corresponding rune.
		rune, err := strconv.Btoui64(oct, 8)
		if err != nil {
			panic(fmt.Sprintf("couldn't parse oct: %s", oct))
		}
		return int(rune)
	}

	// This is an escape sequence which does not identify a single rune.
	panic(fmt.Sprintf("not a valid escape sequence: \\%c", p.src.peek()))
}
Ejemplo n.º 4
0
func (cr *chunkedReader) beginChunk() {
	// chunk-size CRLF
	var line string
	line, cr.err = readLine(cr.r)
	if cr.err != nil {
		return
	}
	cr.n, cr.err = strconv.Btoui64(line, 16)
	if cr.err != nil {
		return
	}
	if cr.n == 0 {
		// trailer CRLF
		for {
			line, cr.err = readLine(cr.r)
			if cr.err != nil {
				return
			}
			if line == "" {
				break
			}
		}
		cr.err = os.EOF
	}
}
Ejemplo n.º 5
0
func serveSymbol(req *web.Request) {
	var p []byte
	if req.Method == "POST" {
		var err os.Error
		p, err = req.BodyBytes(-1)
		if err != nil {
			req.Error(web.StatusInternalServerError, err)
			return
		}
	} else {
		p = []byte(req.URL.RawQuery)
	}

	w := respondText(req)
	io.WriteString(w, "num_symbols: 1\n")
	for len(p) > 0 {
		var a []byte
		if i := bytes.IndexByte(p, '+'); i >= 0 {
			a = p[:i]
			p = p[i+1:]
		} else {
			a = p
			p = nil
		}
		if pc, _ := strconv.Btoui64(string(a), 0); pc != 0 {
			if f := runtime.FuncForPC(uintptr(pc)); f != nil {
				fmt.Fprintf(w, "%#x %s\n", pc, f.Name())
			}
		}
	}
}
Ejemplo n.º 6
0
// scanUint returns the value of the unsigned integer represented
// by the next token, checking for overflow.  Any error is stored in s.err.
func (s *ss) scanUint(verb int, bitSize int) uint64 {
	if verb == 'c' {
		return uint64(s.scanRune(bitSize))
	}
	s.skipSpace(false)
	base, digits := s.getBase(verb)
	haveDigits := false
	if verb == 'U' {
		if !s.consume("U", false) || !s.consume("+", false) {
			s.errorString("bad unicode format ")
		}
	} else if verb == 'v' {
		base, digits, haveDigits = s.scanBasePrefix()
	}
	tok := s.scanNumber(digits, haveDigits)
	i, err := strconv.Btoui64(tok, base)
	if err != nil {
		s.error(err)
	}
	n := uint(bitSize)
	x := (i << (64 - n)) >> (64 - n)
	if x != i {
		s.errorString("unsigned integer overflow on token " + tok)
	}
	return i
}
Ejemplo n.º 7
0
func TestRunServer(t *testing.T) {
	if !*serve {
		return
	}

	suites := strings.Split(*testCipherSuites, ",")
	testConfig.CipherSuites = make([]uint16, len(suites))
	for i := range suites {
		suite, err := strconv.Btoui64(suites[i], 0)
		if err != nil {
			panic(err)
		}
		testConfig.CipherSuites[i] = uint16(suite)
	}

	l, err := Listen("tcp", ":10443", testConfig)
	if err != nil {
		t.Fatal(err)
	}

	for {
		c, err := l.Accept()
		if err != nil {
			break
		}
		_, err = c.Write([]byte("hello, world\n"))
		if err != nil {
			t.Errorf("error from TLS: %s", err)
			break
		}
		c.Close()
	}
}
Ejemplo n.º 8
0
func Mknod(call []string) error {
	e := flagSet.Parse(call[1:])
	if e != nil {
		return e
	}

	if flagSet.NArg() != 1 || *helpFlag {
		println("`mknod` [options] <file>")
		flagSet.PrintDefaults()
		return nil
	}

	mode, ok := typemap[strings.ToLower(*typeFlag)]
	if !ok {
		return errors.New("Invalid node type \"" + *typeFlag + "\"")
	}

	if mode == syscall.S_IFBLK && (*majorFlag == -1 || *minorFlag == -1) {
		return errors.New("When creating a block device, both minor and major number have to be given")
	}

	fmode, e := strconv.Btoui64(*modeFlag, 8)
	if e != nil {
		return e
	}
	mode |= uint32(fmode)

	e = syscall.Mknod(flagSet.Arg(0), mode, *majorFlag<<8|*minorFlag)
	return e
}
Ejemplo n.º 9
0
Archivo: lexer.go Proyecto: nsf/shebang
func hexPairToByte(rune1 int, rune2 int) byte {
	// TODO: this one is slowpoke probably
	s := string([]byte{byte(rune1), byte(rune2)})
	ui, err := strconv.Btoui64(s, 16)
	if err != nil {
		panic(err)
	}
	return byte(ui)
}
Ejemplo n.º 10
0
func loadCasefold() {
	if *casefoldingURL == "" {
		flag.Set("casefolding", *url+"CaseFolding.txt")
	}
	resp, err := http.Get(*casefoldingURL)
	if err != nil {
		logger.Fatal(err)
	}
	if resp.StatusCode != 200 {
		logger.Fatal("bad GET status for CaseFolding.txt", resp.Status)
	}
	input := bufio.NewReader(resp.Body)
	for {
		line, err := input.ReadString('\n')
		if err != nil {
			if err == os.EOF {
				break
			}
			logger.Fatal(err)
		}
		if line[0] == '#' {
			continue
		}
		field := strings.Split(line, "; ")
		if len(field) != 4 {
			logger.Fatalf("CaseFolding.txt %.5s...: %d fields (expected %d)\n", line, len(field), 4)
		}
		kind := field[1]
		if kind != "C" && kind != "S" {
			// Only care about 'common' and 'simple' foldings.
			continue
		}
		p1, err := strconv.Btoui64(field[0], 16)
		if err != nil {
			logger.Fatalf("CaseFolding.txt %.5s...: %s", line, err)
		}
		p2, err := strconv.Btoui64(field[2], 16)
		if err != nil {
			logger.Fatalf("CaseFolding.txt %.5s...: %s", line, err)
		}
		chars[p1].foldCase = int(p2)
	}
	resp.Body.Close()
}
Ejemplo n.º 11
0
// getu4 decodes \uXXXX from the beginning of s, returning the hex value,
// or it returns -1.
func getu4(s []byte) int {
	if len(s) < 6 || s[0] != '\\' || s[1] != 'u' {
		return -1
	}
	rune, err := strconv.Btoui64(string(s[2:6]), 16)
	if err != nil {
		return -1
	}
	return int(rune)
}
Ejemplo n.º 12
0
// getu4 decodes \uXXXX from the beginning of s, returning the hex value,
// or it returns -1.
func getu4(s []byte) rune {
	if len(s) < 6 || s[0] != '\\' || s[1] != 'u' {
		return -1
	}
	r, err := strconv.Btoui64(string(s[2:6]), 16)
	if err != nil {
		return -1
	}
	return rune(r)
}
Ejemplo n.º 13
0
func (char *Char) letterValue(s string, cas string) int {
	if s == "" {
		return 0
	}
	v, err := strconv.Btoui64(s, 16)
	if err != nil {
		char.dump(cas)
		logger.Fatalf("%U: bad letter(%s): %s", char.codePoint, s, err)
	}
	return int(v)
}
Ejemplo n.º 14
0
func (char *Char) letterValue(s string, cas string) int {
	if s == "" {
		return 0
	}
	v, err := strconv.Btoui64(s, 16);
	if err != nil {
		char.dump(cas);
		die.Logf("U+%04x: bad letter(%s): %s", char.codePoint, s, err);
	}
	return int(v);
}
Ejemplo n.º 15
0
func parseScript(line string, scripts map[string][]Script) {
	comment := strings.Index(line, "#");
	if comment >= 0 {
		line = line[0:comment]
	}
	line = strings.TrimSpace(line);
	if len(line) == 0 {
		return
	}
	field := strings.Split(line, ";", -1);
	if len(field) != 2 {
		die.Logf("%s: %d fields (expected 2)\n", line, len(field))
	}
	matches := scriptRe.MatchStrings(line);
	if len(matches) != 4 {
		die.Logf("%s: %d matches (expected 3)\n", line, len(matches))
	}
	lo, err := strconv.Btoui64(matches[1], 16);
	if err != nil {
		die.Log("%.5s...:", err)
	}
	hi := lo;
	if len(matches[2]) > 2 {	// ignore leading ..
		hi, err = strconv.Btoui64(matches[2][2:len(matches[2])], 16);
		if err != nil {
			die.Log("%.5s...:", err)
		}
	}
	name := matches[3];
	s, ok := scripts[name];
	if !ok || len(s) == cap(s) {
		ns := make([]Script, len(s), len(s)+100);
		for i, sc := range s {
			ns[i] = sc
		}
		s = ns;
	}
	s = s[0 : len(s)+1];
	s[len(s)-1] = Script{uint32(lo), uint32(hi), name};
	scripts[name] = s;
}
Ejemplo n.º 16
0
func DiffFiles(paths []string) (d []FileDiff, e os.Error) {
	args := stringslice.Cat([]string{"--"}, paths)
	o,e := git.ReadS("diff-files", args)
	if e != nil { return }
	ls := strings.Split(o,"\n",-1)
	d = make([]FileDiff, 0, len(ls))
	i := 0
	for _,l := range ls {
		if len(l) < 84 { continue }
		d = d[0:i+1]
		if l[0] != ':' { continue }
		// It would be faster to just use byte offsets, but I'm sure I'd
		// get them wrong, so for now I'll just use the slow, sloppy, lazy
		// approach.
		xxxx := strings.Split(l[1:], "\t",-1)
		if len(xxxx) < 2 {
			e = os.NewError("bad line: "+l)
			return
		}
		chunks := strings.Split(xxxx[0]," ",-1)
		if len(chunks) < 4 { continue }
		mode, e := strconv.Btoui64(chunks[0],8)
		if e != nil { return }
		d[i].OldMode = int(mode)
		mode, e = strconv.Btoui64(chunks[1],8)
		if e != nil { return }
		d[i].NewMode = int(mode)
		d[i].OldHash = mkHash(chunks[2])
		d[i].NewHash = mkHash(chunks[3])
		d[i].Change = Verb(chunks[4][0])
		d[i].Name = xxxx[1]
		switch d[i].Change {
		case Renamed, Copied:
			d[i].OldName = xxxx[2]
		}
		i++
	}
	return
}
Ejemplo n.º 17
0
func parseDecomposition(s string, skipfirst bool) (a []int, e os.Error) {
	decomp := strings.Split(s, " ")
	if len(decomp) > 0 && skipfirst {
		decomp = decomp[1:]
	}
	for _, d := range decomp {
		point, err := strconv.Btoui64(d, 16)
		if err != nil {
			return a, err
		}
		a = append(a, int(point))
	}
	return a, nil
}
Ejemplo n.º 18
0
func extractAddrFromLine(line string) uint64 {
	if len(line) < 8 {
		return 0
	}
	i := strings.Index(line, ":")
	if i < 0 {
		return 0
	}
	addr, e := strconv.Btoui64(strings.TrimSpace(line[0:i]), 16)
	if e != nil {
		return 0
	}
	return addr
}
Ejemplo n.º 19
0
Archivo: uniq.go Proyecto: ypb/Q
// Tack starts a fresh "this second Epoch". It does not mean it lasts a
// second, it's mere resolution limitation. Given a "Tack" all following
// events receive monotonically increasing "Ticks". If Tack detects
// that last second is still up it does not reset the "Ticks" counter.
func (o *uniq) Tack() os.Error {
	var sec string
	var cnt uint16
	// stamp := time.Format("2006 Jan 02 | 05 04 15  MST (-0700)")
	var err tdb.Error
	meta := db[META+EXT] // GLOBAL ENV rox!
	store := true
	// ahh, those intermunged concerns...
	if meta == nil {
		return os.NewError("uniq.Tack(): nil META db")
	} else {
		o.utc = time.UTC()
		o.sec = strconv.Itob64(o.utc.Seconds(), BASE)
		var cnt_s string
		if sec, err = meta.Fetch(NOW); err == nil {
			// trin // f**k // order
			if o.sec == sec {
				if cnt_s, err = meta.Fetch(CNT); err == nil {
					cnt_ugh, _ := strconv.Btoui64(cnt_s, BASE)
					cnt = uint16(cnt_ugh)
					if cnt > o.cnt {
						o.cnt = cnt
						store = false
					}
				}
			} else {
				o.cnt = 0
			}
		}
		// TODO tdb.Exists()
		if store {
			if err = meta.Store(NOW, o.sec, tdb.MODIFY); err != nil {
				// presumably it yet exists not...
				if err = meta.Store(NOW, o.sec, tdb.INSERT); err != nil {
					return err
				}
			}
			// lazy logic.
			cnt_s = strconv.Itob64(int64(o.cnt), BASE)
			// mip map
			if err = meta.Store(CNT, cnt_s, tdb.MODIFY); err != nil {
				// presumably it yet exists not...
				if err = meta.Store(CNT, cnt_s, tdb.INSERT); err != nil {
					return err
				}
			}
		}
	}
	return nil
}
Ejemplo n.º 20
0
func (tr *Reader) octal(b []byte) int64 {
	// Removing leading spaces.
	for len(b) > 0 && b[0] == ' ' {
		b = b[1:]
	}
	// Removing trailing NULs and spaces.
	for len(b) > 0 && (b[len(b)-1] == ' ' || b[len(b)-1] == '\x00') {
		b = b[0 : len(b)-1]
	}
	x, err := strconv.Btoui64(cString(b), 8)
	if err != nil {
		tr.err = err
	}
	return int64(x)
}
Ejemplo n.º 21
0
func parseCategory(line string) (state State) {
	field := strings.Split(line, ";")
	if len(field) != NumField {
		logger.Fatalf("%5s: %d fields (expected %d)\n", line, len(field), NumField)
	}
	point, err := strconv.Btoui64(field[FCodePoint], 16)
	if err != nil {
		logger.Fatalf("%.5s...: %s", line, err)
	}
	lastChar = uint32(point)
	if point == 0 {
		return // not interesting and we use 0 as unset
	}
	if point > MaxChar {
		return
	}
	char := &chars[point]
	char.field = field
	if char.codePoint != 0 {
		logger.Fatalf("point %U reused", point)
	}
	char.codePoint = lastChar
	char.category = field[FGeneralCategory]
	category[char.category] = true
	switch char.category {
	case "Nd":
		// Decimal digit
		_, err := strconv.Atoi(field[FNumericValue])
		if err != nil {
			logger.Fatalf("%U: bad numeric field: %s", point, err)
		}
	case "Lu":
		char.letter(field[FCodePoint], field[FSimpleLowercaseMapping], field[FSimpleTitlecaseMapping])
	case "Ll":
		char.letter(field[FSimpleUppercaseMapping], field[FCodePoint], field[FSimpleTitlecaseMapping])
	case "Lt":
		char.letter(field[FSimpleUppercaseMapping], field[FSimpleLowercaseMapping], field[FCodePoint])
	default:
		char.letter(field[FSimpleUppercaseMapping], field[FSimpleLowercaseMapping], field[FSimpleTitlecaseMapping])
	}
	switch {
	case strings.Index(field[FName], ", First>") > 0:
		state = SFirst
	case strings.Index(field[FName], ", Last>") > 0:
		state = SLast
	}
	return
}
Ejemplo n.º 22
0
func parseCategory(line string) (state State) {
	field := strings.Split(line, ";", -1);
	if len(field) != NumField {
		die.Logf("%5s: %d fields (expected %d)\n", line, len(field), NumField)
	}
	point, err := strconv.Btoui64(field[FCodePoint], 16);
	if err != nil {
		die.Log("%.5s...:", err)
	}
	lastChar = uint32(point);
	if point == 0 {
		return	// not interesting and we use 0 as unset
	}
	if point > MaxChar {
		return
	}
	char := &chars[point];
	char.field = field;
	if char.codePoint != 0 {
		die.Logf("point U+%04x reused\n")
	}
	char.codePoint = lastChar;
	char.category = field[FGeneralCategory];
	category[char.category] = true;
	switch char.category {
	case "Nd":
		// Decimal digit
		_, err := strconv.Atoi(field[FNumericValue]);
		if err != nil {
			die.Log("U+%04x: bad numeric field: %s", point, err)
		}
	case "Lu":
		char.letter(field[FCodePoint], field[FSimpleLowercaseMapping], field[FSimpleTitlecaseMapping])
	case "Ll":
		char.letter(field[FSimpleUppercaseMapping], field[FCodePoint], field[FSimpleTitlecaseMapping])
	case "Lt":
		char.letter(field[FSimpleUppercaseMapping], field[FSimpleLowercaseMapping], field[FCodePoint])
	case "Lm", "Lo":
		char.letter(field[FSimpleUppercaseMapping], field[FSimpleLowercaseMapping], field[FSimpleTitlecaseMapping])
	}
	switch {
	case strings.Index(field[FName], ", First>") > 0:
		state = SFirst
	case strings.Index(field[FName], ", Last>") > 0:
		state = SLast
	}
	return;
}
Ejemplo n.º 23
0
func (ss *Superset) UnixMode() (mode uint32) {
	m64, err := strconv.Btoui64(ss.UnixPermission, 8)
	if err == nil {
		mode = mode | uint32(m64)
	}

	// TODO: add other types
	switch ss.Type {
	case "directory":
		mode = mode | syscall.S_IFDIR
	case "file":
		mode = mode | syscall.S_IFREG
	case "symlink":
		mode = mode | syscall.S_IFLNK
	}
	return
}
Ejemplo n.º 24
0
// CompositionExclusions.txt has form:
// 0958    # ...
// See http://unicode.org/reports/tr44/ for full explanation
func parseExclusion(line string) int {
	comment := strings.Index(line, "#")
	if comment >= 0 {
		line = line[0:comment]
	}
	if len(line) == 0 {
		return 0
	}
	matches := singlePointRe.FindStringSubmatch(line)
	if len(matches) != 2 {
		logger.Fatalf("%s: %d matches (expected 1)\n", line, len(matches))
	}
	point, err := strconv.Btoui64(matches[1], 16)
	if err != nil {
		logger.Fatalf("%.5s...: %s", line, err)
	}
	return int(point)
}
Ejemplo n.º 25
0
// scanUint returns the value of the unsigned integer represented
// by the next token, checking for overflow.  Any error is stored in s.err.
func (s *ss) scanUint(verb int, bitSize int) uint64 {
	if verb == 'c' {
		return uint64(s.scanRune(bitSize))
	}
	base, digits := s.getBase(verb)
	s.skipSpace(false)
	tok := s.scanNumber(digits)
	i, err := strconv.Btoui64(tok, base)
	if err != nil {
		s.error(err)
	}
	n := uint(bitSize)
	x := (i << (64 - n)) >> (64 - n)
	if x != i {
		s.errorString("unsigned integer overflow on token " + tok)
	}
	return i
}
Ejemplo n.º 26
0
// Symbol looks up the program counters listed in the request,
// responding with a table mapping program counters to function names.
// The package initialization registers it as /debug/pprof/symbol.
func Symbol(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/plain; charset=utf-8")

	// We have to read the whole POST body before
	// writing any output.  Buffer the output here.
	var buf bytes.Buffer

	// We don't know how many symbols we have, but we
	// do have symbol information.  Pprof only cares whether
	// this number is 0 (no symbols available) or > 0.
	fmt.Fprintf(&buf, "num_symbols: 1\n")

	var b *bufio.Reader
	if r.Method == "POST" {
		b = bufio.NewReader(r.Body)
	} else {
		b = bufio.NewReader(strings.NewReader(r.URL.RawQuery))
	}

	for {
		word, err := b.ReadSlice('+')
		if err == nil {
			word = word[0 : len(word)-1] // trim +
		}
		pc, _ := strconv.Btoui64(string(word), 0)
		if pc != 0 {
			f := runtime.FuncForPC(uintptr(pc))
			if f != nil {
				fmt.Fprintf(&buf, "%#x %s\n", pc, f.Name())
			}
		}

		// Wait until here to check for err; the last
		// symbol will have an err because it doesn't end in +.
		if err != nil {
			if err != io.EOF {
				fmt.Fprintf(&buf, "reading request: %v\n", err)
			}
			break
		}
	}

	w.Write(buf.Bytes())
}
Ejemplo n.º 27
0
// Next returns the next line from the stream. The returned slice is
// overwritten by the next call to Next.
func (ts *TwitterStream) Next() []byte {
	var p []byte
	for {
		for ts.r == nil {
			d := ts.waitUntil - time.Nanoseconds()
			if d > 0 {
				time.Sleep(d)
			}
			ts.waitUntil = time.Nanoseconds() + 30e9
			ts.connect()
		}
		var err os.Error
		p, err = ts.r.ReadSlice('\n')
		if err != nil {
			ts.error("error reading chunk-size", err)
			continue
		} else if len(p) <= 2 {
			// ignore keepalive line
		}
		size, err := strconv.Btoui64("0x"+strings.Trim(string(p), "\r\n"), 0)
		if err != nil {
			ts.error("error invalid chunk-size", err)
			continue
		}
		if size == 0 {
			ts.Close()
			continue
		}
		p = make([]byte, size)
		if _, err = io.ReadFull(ts.r, p); err != nil {
			ts.error("error reading chunk-data", err)
			continue
		}
		_, err = ts.r.ReadSlice('\n')
		if err != nil {
			ts.error("error reading chunk-data", err)
			continue
		} else {
			break
		}
	}
	return p
}
Ejemplo n.º 28
0
func readChunkFraming(br *bufio.Reader, first bool) (int, os.Error) {
	if !first {
		// trailer from previous chunk
		p := make([]byte, 2)
		if _, err := io.ReadFull(br, p); err != nil {
			return 0, err
		}
		if p[0] != '\r' && p[1] != '\n' {
			return 0, os.NewError("twister: bad chunked format")
		}
	}

	line, isPrefix, err := br.ReadLine()
	if err != nil {
		return 0, err
	}
	if isPrefix {
		return 0, os.NewError("twister: bad chunked format")
	}
	n, err := strconv.Btoui64(string(line), 16)
	if err != nil {
		return 0, err
	}
	if n == 0 {
		for {
			line, isPrefix, err = br.ReadLine()
			if err != nil {
				return 0, err
			}
			if isPrefix {
				return 0, os.NewError("twister: bad chunked format")
			}
			if len(line) == 0 {
				return 0, os.EOF
			}
		}
	}
	return int(n), nil
}
Ejemplo n.º 29
0
func readPacket(r io.Reader) (b []byte, err os.Error) {
	n := make([]byte, 4)
	_, err = r.Read(n)
	if err != nil {
		return
	}
	n2, err := strconv.Btoui64(string(n), 16)
	if err != nil {
		return
	}
	// flush
	if n2 == 0 {
		return
	}
	b = make([]byte, n2-4)
	_, err = r.Read(b)
	if err != nil {
		b = nil
		return
	}
	return
}
Ejemplo n.º 30
0
// Return a geohased representation of a latitude & longitude bearing point using bits precision.
// If bits is 0 or larger than 30, it is set to a maximum of 30 bits
func LatLongToGeoHashBits(pc *PolarCoord, bits byte) string {

	if bits == 0 || bits > 30 {
		bits = 30
	}

	var accu, bitstring string
	latbits, longbits := bits, bits

	for addlong := byte(1); (longbits+latbits)%5 != 0; addlong = (addlong + 1) % 2 {
		longbits += addlong % 2
		latbits += (addlong + 1) % 2
	}

	latbitstring := geohashbitset(pc.Latitude, -90.0, 90.0, latbits)
	longbitstring := geohashbitset(pc.Longitude, -180.0, 180.0, longbits)

	for startlong := true; len(latbitstring)+len(longbitstring) > 0; startlong = !startlong {
		switch startlong {
		case true:
			bitstring += longbitstring[:1]
			longbitstring = longbitstring[1:]
		case false:
			bitstring += latbitstring[:1]
			latbitstring = latbitstring[1:]
		}
	}
	var base32fragment string
	var base32index uint64

	for ; len(bitstring) > 0; bitstring = bitstring[5:] {
		base32fragment = bitstring[:5]

		// An error is entirely the algorithms fault, so we ignore it here
		base32index, _ = strconv.Btoui64(base32fragment, 2)
		accu += string(Base32GeohashCode[uint8(base32index)])
	}
	return accu
}