func extractISO8601Duration( iso_8601_duration string, ) ( minutes_duration, seconds_duration time.Duration, err error, ) { err = fmt.Errorf(`No duration can be extracted`) re := regexp.MustCompile(ISO_8601_DURATION_REGEX) if re.MatchString(iso_8601_duration) { matched_groups := re.FindAllStringSubmatch(iso_8601_duration, 1) if len(matched_groups) > 0 { groups := matched_groups[0] if d, d_err := strconv.ParseInt(groups[1], 10, 64); d_err == nil { minutes_duration = time.Minute * time.Duration(d) err = nil } else { err = d_err } if err == nil { if d, d_err := strconv.ParseInt(groups[2], 10, 64); d_err == nil { seconds_duration = time.Second * time.Duration(d) err = nil } else { err = d_err } } } } return }
func main() { //With ParseFloat, this 64 tells how many bits of precision to parse. f, _ := strconv.ParseFloat("1.234", 64) fmt.Println(f) //For ParseInt, the 0 means infer the base from the string. 64 requires that the result fit in 64 bits. i, _ := strconv.ParseInt("123", 0, 64) fmt.Println(i) //ParseInt will recognize hex-formatted numbers. d, _ := strconv.ParseInt("0x1c8", 0, 64) fmt.Println(d) //A ParseUint is also available. u, _ := strconv.ParseUint("789", 0, 64) fmt.Println(u) //Atoi is a convenience function for basic base-10 int parsing. k, _ := strconv.Atoi("135") fmt.Println(k) //Parse functions return an error on bad input. _, e := strconv.Atoi("wat") fmt.Println(e) }
// parsePAXTime takes a string of the form %d.%d as described in // the PAX specification. func parsePAXTime(t string) (time.Time, error) { buf := []byte(t) pos := bytes.IndexByte(buf, '.') var seconds, nanoseconds int64 var err error if pos == -1 { seconds, err = strconv.ParseInt(t, 10, 0) if err != nil { return time.Time{}, err } } else { seconds, err = strconv.ParseInt(string(buf[:pos]), 10, 0) if err != nil { return time.Time{}, err } nano_buf := string(buf[pos+1:]) // Pad as needed before converting to a decimal. // For example .030 -> .030000000 -> 30000000 nanoseconds if len(nano_buf) < maxNanoSecondIntSize { // Right pad nano_buf += strings.Repeat("0", maxNanoSecondIntSize-len(nano_buf)) } else if len(nano_buf) > maxNanoSecondIntSize { // Right truncate nano_buf = nano_buf[:maxNanoSecondIntSize] } nanoseconds, err = strconv.ParseInt(string(nano_buf), 10, 0) if err != nil { return time.Time{}, err } } ts := time.Unix(seconds, nanoseconds) return ts, nil }
// readGNUSparseMap0x1 reads the sparse map as stored in GNU's PAX sparse format // version 0.1. The sparse map is stored in the PAX headers. func readGNUSparseMap0x1(extHdrs map[string]string) ([]sparseEntry, error) { // Get number of entries. // Use integer overflow resistant math to check this. numEntriesStr := extHdrs[paxGNUSparseNumBlocks] numEntries, err := strconv.ParseInt(numEntriesStr, 10, 0) // Intentionally parse as native int if err != nil || numEntries < 0 || int(2*numEntries) < int(numEntries) { return nil, ErrHeader } // There should be two numbers in sparseMap for each entry. sparseMap := strings.Split(extHdrs[paxGNUSparseMap], ",") if int64(len(sparseMap)) != 2*numEntries { return nil, ErrHeader } // Loop through the entries in the sparse map. // numEntries is trusted now. sp := make([]sparseEntry, 0, numEntries) for i := int64(0); i < numEntries; i++ { offset, err := strconv.ParseInt(sparseMap[2*i], 10, 64) if err != nil { return nil, ErrHeader } numBytes, err := strconv.ParseInt(sparseMap[2*i+1], 10, 64) if err != nil { return nil, ErrHeader } sp = append(sp, sparseEntry{offset: offset, numBytes: numBytes}) } return sp, nil }
func evalStatusline(statusline string) (active, total, size int64, err error) { matches := statuslineRE.FindStringSubmatch(statusline) // +1 to make it more obvious that the whole string containing the info is also returned as matches[0]. if len(matches) < 3+1 { return 0, 0, 0, fmt.Errorf("too few matches found in statusline: %s", statusline) } else { if len(matches) > 3+1 { return 0, 0, 0, fmt.Errorf("too many matches found in statusline: %s", statusline) } } size, err = strconv.ParseInt(matches[1], 10, 64) if err != nil { return 0, 0, 0, fmt.Errorf("%s in statusline: %s", err, statusline) } total, err = strconv.ParseInt(matches[2], 10, 64) if err != nil { return 0, 0, 0, fmt.Errorf("%s in statusline: %s", err, statusline) } active, err = strconv.ParseInt(matches[3], 10, 64) if err != nil { return 0, 0, 0, fmt.Errorf("%s in statusline: %s", err, statusline) } return active, total, size, nil }
// Generates JSON for root list of trends func TrendsRootIndex(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) location := vars["location"] source := r.URL.Query().Get("source") limitParam := r.URL.Query().Get("limit") limit, _ := strconv.ParseInt(limitParam, 10, 0) if limit < 1 { limit = 10 } intervalParam := r.URL.Query().Get("interval") interval, _ := strconv.ParseInt(intervalParam, 10, 0) fromParam := r.URL.Query().Get("from") toParam := r.URL.Query().Get("to") t := time.Now() if fromParam == "" { from := t.Add(-24 * time.Hour) fromParam = from.Format("200601021504") } if toParam == "" { toParam = t.Format("200601021504") } if interval < 1 { interval = 2 } sortedCounts, _ := WordCountRootCollection(location, source, fromParam, toParam, int(interval), int(limit)) w.Header().Add("Access-Control-Allow-Origin", "*") w.Header().Add("Access-Control-Allow-Methods", "GET") w.Header().Add("Access-Control-Allow-Headers", "Content-Type, api_key, Authorization") json.NewEncoder(w).Encode(sortedCounts) }
func libSubstr(th *eval.Thread, in []eval.Value, out []eval.Value) { s := in[0].String() start, err := strconv.ParseInt(in[1].String(), 10, 32) var res string if err != nil { panic(err) } end, err := strconv.ParseInt(in[2].String(), 10, 32) if err != nil { panic(err) } if int(start) < 0 { newStart := len(s) + int(start) res := s[newStart:len(s)] out[0] = eval.ToValue(res) return } if len(s) < int(end) { res = s[start:] out[0] = eval.ToValue(res) return } res = s[start:end] out[0] = eval.ToValue(res) }
// Group selects a group. func (c *Client) Group(name string) (rv nntp.Group, err error) { var msg string _, msg, err = c.Command("GROUP "+name, 211) if err != nil { return } // count first last name parts := strings.Split(msg, " ") if len(parts) != 4 { err = errors.New("Don't know how to parse result: " + msg) } rv.Count, err = strconv.ParseInt(parts[0], 10, 64) if err != nil { return } rv.Low, err = strconv.ParseInt(parts[1], 10, 64) if err != nil { return } rv.High, err = strconv.ParseInt(parts[2], 10, 64) if err != nil { return } rv.Name = parts[3] return }
// List groups func (c *Client) List(sub string) (rv []nntp.Group, err error) { _, _, err = c.Command("LIST "+sub, 215) if err != nil { return } var groupLines []string groupLines, err = c.conn.ReadDotLines() if err != nil { return } rv = make([]nntp.Group, 0, len(groupLines)) for _, l := range groupLines { parts := strings.Split(l, " ") high, errh := strconv.ParseInt(parts[1], 10, 64) low, errl := strconv.ParseInt(parts[2], 10, 64) if errh == nil && errl == nil { rv = append(rv, nntp.Group{ Name: parts[0], High: high, Low: low, Posting: parsePosting(parts[3]), }) } } return }
func PermInt(str string) int { var res = 0 if str[0] == '0' { if len(str) == 1 { res = 0 } else if str[1] == 'x' { // this is hex number i64, err := strconv.ParseInt(str[2:], 16, 0) if err == nil { res = int(i64) } } else { // this is a octal number i64, err := strconv.ParseInt(str[2:], 8, 0) if err == nil { res = int(i64) } } } else { res, _ = strconv.Atoi(str) } if res > 511 { res = 511 } return res }
// buildSlaveInfoStruct builods the struct for a slave from the Redis slaves command func (r *Redis) buildSlaveInfoStruct(info map[string]string) (master SlaveInfo, err error) { s := reflect.ValueOf(&master).Elem() typeOfT := s.Type() for i := 0; i < s.NumField(); i++ { p := typeOfT.Field(i) f := s.Field(i) tag := p.Tag.Get("redis") if f.Type().Name() == "int" { val, err := strconv.ParseInt(info[tag], 10, 64) if err != nil { println("Unable to convert to data from sentinel server:", info[tag], err) } else { f.SetInt(val) } } if f.Type().Name() == "string" { f.SetString(info[tag]) } if f.Type().Name() == "bool" { // This handles primarily the xxx_xx style fields in the return data from redis if info[tag] != "" { val, err := strconv.ParseInt(info[tag], 10, 64) if err != nil { println("[bool] Unable to convert to data from sentinel server:", info[tag], err) fmt.Println("Error:", err) } else { if val > 0 { f.SetBool(true) } } } } } return }
func deleteBuildCommentHandler(w http.ResponseWriter, r *http.Request) { defer timer.New("deleteBuildCommentHandler").Stop() if !userHasEditRights(r) { util.ReportError(w, r, fmt.Errorf("User does not have edit rights."), "User does not have edit rights.") return } w.Header().Set("Content-Type", "application/json") cache, err := getCommitCache(w, r) if err != nil { return } buildId, err := strconv.ParseInt(mux.Vars(r)["buildId"], 10, 32) if err != nil { util.ReportError(w, r, err, fmt.Sprintf("Invalid build id: %v", err)) return } commentId, err := strconv.ParseInt(mux.Vars(r)["commentId"], 10, 32) if err != nil { util.ReportError(w, r, err, fmt.Sprintf("Invalid comment id: %v", err)) return } if err := cache.DeleteBuildComment(int(buildId), int(commentId)); err != nil { util.ReportError(w, r, err, fmt.Sprintf("Failed to delete comment: %v", err)) return } }
func waitForNotification(l *pq.Listener) { for { select { case notify := <-l.Notify: payload := strings.SplitN(notify.Extra, "|", 3) id, err := strconv.ParseInt(payload[0], 10, 64) if err != nil { panic(err) } var roomId int64 roomId, err = strconv.ParseInt(payload[1], 10, 64) if err != nil { panic(err) } msg := models.GetMessage(id) revel.INFO.Printf("received notification with payload: '%d' '%d' '%s' '%s'\n", msg.Id, msg.RoomId, msg.Text, msg.ImageUrl) Publish(EVENT_MSG, int64(roomId), *msg) case <-time.After(200 * time.Millisecond): go func() { if err := l.Ping(); err != nil { panic(err) } }() } } }
// parseJavaSamples parses the samples from a java profile and // populates the Samples in a profile. Returns the remainder of the // buffer after the samples. func parseJavaSamples(pType string, b []byte, p *Profile) ([]byte, map[uint64]*Location, error) { nextNewLine := bytes.IndexByte(b, byte('\n')) locs := make(map[uint64]*Location) for nextNewLine != -1 { line := string(bytes.TrimSpace(b[0:nextNewLine])) if line != "" { sample := javaSampleRx.FindStringSubmatch(line) if sample == nil { // Not a valid sample, exit. return b, locs, nil } // Java profiles have data/fields inverted compared to other // profile types. value1, value2, addrs := sample[2], sample[1], sample[3] var sloc []*Location for _, addr := range parseHexAddresses(addrs) { loc := locs[addr] if locs[addr] == nil { loc = &Location{ Address: addr, } p.Location = append(p.Location, loc) locs[addr] = loc } sloc = append(sloc, loc) } s := &Sample{ Value: make([]int64, 2), Location: sloc, } var err error if s.Value[0], err = strconv.ParseInt(value1, 0, 64); err != nil { return nil, nil, fmt.Errorf("parsing sample %s: %v", line, err) } if s.Value[1], err = strconv.ParseInt(value2, 0, 64); err != nil { return nil, nil, fmt.Errorf("parsing sample %s: %v", line, err) } switch pType { case "heap": const javaHeapzSamplingRate = 524288 // 512K s.NumLabel = map[string][]int64{"bytes": []int64{s.Value[1] / s.Value[0]}} s.Value[0], s.Value[1] = scaleHeapSample(s.Value[0], s.Value[1], javaHeapzSamplingRate) case "contention": if period := p.Period; period != 0 { s.Value[0] = s.Value[0] * p.Period s.Value[1] = s.Value[1] * p.Period } } p.Sample = append(p.Sample, s) } // Grab next line. b = b[nextNewLine+1:] nextNewLine = bytes.IndexByte(b, byte('\n')) } return b, locs, nil }
func (r bot) set(p *robots.Payload, cmd utils.Command) error { name := cmd.Arg(0) if name == "" { r.handler.Send(p, "Missing Slack user name. Use `!user set <user-name> [mvn:<mavenlink-id>] [pvt:<pivotal-id>]`") return nil } mvnId := cmd.Param("mvn") pvtId := cmd.Param("pvt") user := db.User{Name: name} if mvnId != "" { mvnInt, err := strconv.ParseInt(mvnId, 10, 64) if err != nil { return err } user.MavenlinkId = &mvnInt } if pvtId != "" { pvtInt, err := strconv.ParseInt(pvtId, 10, 64) if err != nil { return err } user.PivotalId = &pvtInt } if err := db.SaveUser(user); err != nil { return err } r.handler.Send(p, "User *"+name+"* saved") return nil }
func NewStart(ui terminal.UI, config configuration.Reader, appDisplayer ApplicationDisplayer, appRepo api.ApplicationRepository, appInstancesRepo api.AppInstancesRepository, logRepo api.LogsRepository) (cmd *Start) { cmd = new(Start) cmd.ui = ui cmd.config = config cmd.appDisplayer = appDisplayer cmd.appRepo = appRepo cmd.appInstancesRepo = appInstancesRepo cmd.logRepo = logRepo cmd.PingerThrottle = DefaultPingerThrottle if os.Getenv("CF_STAGING_TIMEOUT") != "" { duration, err := strconv.ParseInt(os.Getenv("CF_STAGING_TIMEOUT"), 10, 64) if err != nil { cmd.ui.Failed("invalid value for env var CF_STAGING_TIMEOUT\n%s", err) } cmd.StagingTimeout = time.Duration(duration) * time.Minute } else { cmd.StagingTimeout = DefaultStagingTimeout } if os.Getenv("CF_STARTUP_TIMEOUT") != "" { duration, err := strconv.ParseInt(os.Getenv("CF_STARTUP_TIMEOUT"), 10, 64) if err != nil { cmd.ui.Failed("invalid value for env var CF_STARTUP_TIMEOUT\n%s", err) } cmd.StartupTimeout = time.Duration(duration) * time.Minute } else { cmd.StartupTimeout = DefaultStartupTimeout } return }
func Call(nodeAddr, pubkey, addr, toAddr, amtS, nonceS, gasS, feeS, data string) (*types.CallTx, error) { pub, _, amt, nonce, err := checkCommon(nodeAddr, pubkey, addr, amtS, nonceS) if err != nil { return nil, err } toAddrBytes, err := hex.DecodeString(toAddr) if err != nil { return nil, fmt.Errorf("toAddr is bad hex: %v", err) } fee, err := strconv.ParseInt(feeS, 10, 64) if err != nil { return nil, fmt.Errorf("fee is misformatted: %v", err) } gas, err := strconv.ParseInt(gasS, 10, 64) if err != nil { return nil, fmt.Errorf("gas is misformatted: %v", err) } dataBytes, err := hex.DecodeString(data) if err != nil { return nil, fmt.Errorf("data is bad hex: %v", err) } tx := types.NewCallTxWithNonce(pub, toAddrBytes, dataBytes, amt, gas, fee, int(nonce)) return tx, nil }
func Hash(args martini.Params, su models.User, r render.Render, p *models.Page) { var th models.HashID user_id, err := strconv.ParseInt(args["user_id"], 10, 10) if err != nil { log.Println(err) } image_id, err := strconv.ParseInt(args["image_id"], 10, 10) if err != nil { log.Println(err) } time_now := time.Now().Unix() th.Init(utils.AppCfg.SecretKey(), 6) th.SetIds(int(user_id), int(image_id), int(time_now)) enc := th.Encrypt() log.Println(enc) dec := th.Decrypt() log.Println(dec) p.SetUser(su) p.SetTitle("") p.Data = th encoder.Render(p.Encoding, 200, "test/hash", p, r) }
func (oc OfflineComparer) Compare(a, b []byte) int { p1, p2, p3 := oc.Split(a) p4, p5, p6 := oc.Split(b) if p1 == nil || p4 == nil { log.Infof("can't find seperate, a:%s b:%s compare bytes...\n", string(a), string(b)) return bytes.Compare(a, b) } r1 := bytes.Compare(p1, p4) if r1 != 0 { return r1 } r2 := bytes.Compare(p2, p5) if r2 != 0 { return r2 } v1, err1 := strconv.ParseInt(string(p3), 10, 64) v2, err2 := strconv.ParseInt(string(p6), 10, 64) if err1 != nil || err2 != nil { log.Infof("parse int err, a:%s b:%s compare bytes...\n", string(a), string(b)) return bytes.Compare(p3, p6) } if v1 < v2 { return -1 } else if v1 == v2 { return 0 } else { return 1 } }
func decodeInt(l *lexer, val reflect.Value) error { token := l.nextToken() v := indirect(val) switch v.Kind() { default: return fmt.Errorf("Cannot store int64 into %s", v.Type()) case reflect.Interface: n, err := strconv.ParseInt(token.val, 10, 64) if err != nil { return err } v.Set(reflect.ValueOf(n)) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: n, err := strconv.ParseInt(token.val, 10, 64) if err != nil { return err } v.SetInt(n) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: n, err := strconv.ParseUint(token.val, 10, 64) if err != nil { return err } v.SetUint(n) } return nil }
func (s *HTTPServer) FileReadAtRequest(resp http.ResponseWriter, req *http.Request) (interface{}, error) { var allocID, path string var offset, limit int64 var err error q := req.URL.Query() if allocID = strings.TrimPrefix(req.URL.Path, "/v1/client/fs/readat/"); allocID == "" { return nil, allocIDNotPresentErr } if path = q.Get("path"); path == "" { return nil, fileNameNotPresentErr } if offset, err = strconv.ParseInt(q.Get("offset"), 10, 64); err != nil { return nil, fmt.Errorf("error parsing offset: %v", err) } if limit, err = strconv.ParseInt(q.Get("limit"), 10, 64); err != nil { return nil, fmt.Errorf("error parsing limit: %v", err) } fs, err := s.agent.client.GetAllocFS(allocID) if err != nil { return nil, err } r, err := fs.ReadAt(path, offset, limit) if err != nil { return nil, err } io.Copy(resp, r) return nil, nil }
func toColor(s string) color.Color { r, _ := strconv.ParseInt(s[0:2], 16, 0) g, _ := strconv.ParseInt(s[2:4], 16, 0) b, _ := strconv.ParseInt(s[4:], 16, 0) return color.RGBA{uint8(r), uint8(g), uint8(b), 0xff} }
/** * @api {get} /topics Get a list of topics * @apiName GetTopics * @apiGroup Topics * * @apiParam {Number} [limit=10] The maximum number of items to return * @apiParam {Number} [offset=0] The offset relative to the number of items (not page number) */ func (tc *TopicsController) Index(c *echo.Context) error { resp := response.New(c) defer resp.Render() // Defaults var limit int64 = 10 var offset int64 = 0 // Getting limit limitInt, err := strconv.ParseInt(c.Query("limit"), 10, 64) if err == nil { limit = limitInt } // Getting offset offsetInt, err := strconv.ParseInt(c.Query("offset"), 10, 64) if err == nil { offset = offsetInt } // Fetching models res, err := models.AllTopics(limit, offset) if err != nil { resp.SetResponse(http.StatusInternalServerError, nil) return nil } resp.SetResponse(http.StatusOK, res) return nil }
func (ds *Datastore) RefreshDatastore(*types.RefreshDatastore) soap.HasFault { r := &methods.RefreshDatastoreBody{} info := ds.Info.GetDatastoreInfo() buf, err := exec.Command("df", "-k", info.Url).Output() if err != nil { r.Fault_ = Fault(err.Error(), &types.HostConfigFault{}) return r } lines := strings.Split(string(buf), "\n") columns := strings.Fields(lines[1]) used, _ := strconv.ParseInt(columns[2], 10, 64) info.FreeSpace, _ = strconv.ParseInt(columns[3], 10, 64) info.FreeSpace *= 1024 used *= 1024 ds.Summary.FreeSpace = info.FreeSpace ds.Summary.Capacity = info.FreeSpace + used now := time.Now() info.Timestamp = &now return r }
func setField(field reflect.Value, defaultVal string) { var iface interface{} var err error switch field.Kind() { case reflect.Bool: iface, err = strconv.ParseBool(defaultVal) case reflect.Int: iface, err = strconv.ParseInt(defaultVal, 10, 64) iface = int(iface.(int64)) case reflect.Int8: iface, err = strconv.ParseInt(defaultVal, 10, 8) iface = int8(iface.(int64)) case reflect.Int16: iface, err = strconv.ParseInt(defaultVal, 10, 16) iface = int16(iface.(int64)) case reflect.Int32: iface, err = strconv.ParseInt(defaultVal, 10, 32) iface = int32(iface.(int64)) case reflect.Int64: t, err := time.ParseDuration(defaultVal) if err == nil { iface, err = t, nil } else { iface, err = strconv.ParseInt(defaultVal, 10, 64) } case reflect.Uint: iface, err = strconv.ParseUint(defaultVal, 10, 64) iface = uint(iface.(uint64)) case reflect.Uint8: iface, err = strconv.ParseUint(defaultVal, 10, 8) iface = uint8(iface.(uint64)) case reflect.Uint16: iface, err = strconv.ParseUint(defaultVal, 10, 16) iface = uint16(iface.(uint64)) case reflect.Uint32: iface, err = strconv.ParseUint(defaultVal, 10, 32) iface = uint32(iface.(uint64)) case reflect.Uint64: iface, err = strconv.ParseUint(defaultVal, 10, 64) case reflect.Uintptr: iface, err = strconv.ParseUint(defaultVal, 10, 64) iface = uintptr(iface.(uint64)) case reflect.Float32: iface, err = strconv.ParseFloat(defaultVal, 32) iface = float32(iface.(float64)) case reflect.Float64: iface, err = strconv.ParseFloat(defaultVal, 64) case reflect.String: iface = defaultVal default: err = errInvalidFieldType } if err == nil { if field.CanSet() { field.Set(reflect.ValueOf(iface)) } } }
func (pdu *V2CPDU) Init(params map[string]string) SnmpError { pdu.maxMsgSize = *maxPDUSize if v, ok := params["snmp.max_msg_size"]; ok { if num, e := strconv.ParseUint(v, 10, 0); nil == e { pdu.maxMsgSize = uint(num) } } if v, ok := params["snmp.max_repetitions"]; ok { if num, e := strconv.ParseInt(v, 10, 0); nil == e { pdu.max_repetitions = int(num) } } if v, ok := params["snmp.non_repeaters"]; ok { if num, e := strconv.ParseInt(v, 10, 0); nil == e { pdu.non_repeaters = int(num) } } community, ok := params["snmp.community"] if ok && "" != community { pdu.community = community return nil } return Error(SNMP_CODE_FAILED, "community is empty.") }
func parseline(line []byte, i int) (int, int, int, error) { comma := bytes.Index(line, []byte{'#'}) if comma >= 0 { line = line[0:comma] } if l := len(line); l < 4 { return -1, -1, -1, fmt.Errorf("line %d length invalid: %d %q\n", i, l, line) } rl := bytes.TrimSpace(line) rl = re_space.ReplaceAll(rl, []byte{' '}) chs := bytes.Split(rl, []byte{' '}) if len(chs) != 2 { return -1, -1, -1, fmt.Errorf("line %d has %d numbers: %s\n", i, len(chs), rl) } ret, err := strconv.ParseInt(string(bytes.ToLower(chs[0])), 0, 32) if err != nil { return -1, -1, -1, fmt.Errorf("convert %q to int failed at line %d: %s\n", chs[0], i, err) } gb2312 := int(ret) if gb2312 <= 0x7f { return gb2312, gb2312, gb2312, fmt.Errorf("No need convert for ascii 0x%x\n", gb2312) } ret, err = strconv.ParseInt(string(bytes.ToLower(chs[1])), 0, 32) if err != nil { return -1, -1, -1, fmt.Errorf("convert %q to int failed at line %d: %s\n", chs[1], i, err) } unicode := int(ret) utf8 := unicode2utf8(unicode) return gb2312, unicode, utf8, nil }
func ParseRect(val string, delimeter string) (*Rect, error) { if val == "" { return nil, fmt.Errorf("rect string null") } s := strings.Split(val, delimeter) if len(s) > 2 { return nil, fmt.Errorf("rect format error") } width, err := strconv.ParseInt(s[0], 10, 64) if err != nil { return nil, err } var rect Rect rect.Width = int(width) if len(s) == 2 { height, err := strconv.ParseInt(s[1], 10, 64) if err != nil { return nil, err } rect.Height = int(height) } return &rect, nil }
// readGNUSparseMap0x1 reads the sparse map as stored in GNU's PAX sparse format version 0.1. // The sparse map is stored in the PAX headers. func readGNUSparseMap0x1(headers map[string]string) ([]sparseEntry, error) { // Get number of entries numEntriesStr, ok := headers[paxGNUSparseNumBlocks] if !ok { return nil, ErrHeader } numEntries, err := strconv.ParseInt(numEntriesStr, 10, 0) if err != nil { return nil, ErrHeader } sparseMap := strings.Split(headers[paxGNUSparseMap], ",") // There should be two numbers in sparseMap for each entry if int64(len(sparseMap)) != 2*numEntries { return nil, ErrHeader } // Loop through the entries in the sparse map sp := make([]sparseEntry, 0, numEntries) for i := int64(0); i < numEntries; i++ { offset, err := strconv.ParseInt(sparseMap[2*i], 10, 0) if err != nil { return nil, ErrHeader } numBytes, err := strconv.ParseInt(sparseMap[2*i+1], 10, 0) if err != nil { return nil, ErrHeader } sp = append(sp, sparseEntry{offset: offset, numBytes: numBytes}) } return sp, nil }
func (c *Clang) GetDefinition(a *content.GetDefinitionArgs, ret *content.SourceLocation) error { fn, args, err := c.prepare(&a.CompleteAtArgs) if err != nil { return err } args = append([]string{"-fsyntax-only", "-Xclang", "-ast-dump", "-Xclang", "-ast-dump-filter", "-Xclang", a.Identifier}, args...) args = append(args, fn) out, oute, err := RunClang(a.Location.File.Contents, args...) if len(out) == 0 { if err != nil { return err } else { return fmt.Errorf("%s", oute) } } re, err := regexp.Compile(`\w+Decl[^<]+<(..[^:,]+):?(\d+)?:?(\d+)?.*?\s` + a.Identifier + `\s`) if err != nil { return err } res := re.FindAllStringSubmatch(string(out), -1) if len(res) == 0 { return fmt.Errorf("Not found") } ret.File.Name = res[0][1] i, _ := strconv.ParseInt(res[0][2], 10, 32) ret.Line = uint(i) i, _ = strconv.ParseInt(res[0][3], 10, 32) ret.Column = uint(i) return nil }