Example #1
0
/* parse a storage command parameters and read the related data
   returns a flag indicating sucesss */
func (self *StorageCommand) parse(line []string) bool {
	var flags, exptime, bytes, casuniq uint64
	var err os.Error
	if len(line) < 5 {
		return Error(self.session, ClientError, "Bad storage command: missing parameters")
	} else if flags, err = strconv.Atoui64(line[2]); err != nil {
		return Error(self.session, ClientError, "Bad storage command: bad flags")
	} else if exptime, err = strconv.Atoui64(line[3]); err != nil {
		return Error(self.session, ClientError, "Bad storage command: bad expiration time")
	} else if bytes, err = strconv.Atoui64(line[4]); err != nil {
		return Error(self.session, ClientError, "Bad storage command: bad byte-length")
	} else if line[0] == "cas" {
		if casuniq, err = strconv.Atoui64(line[5]); err != nil {
			return Error(self.session, ClientError, "Bad storage command: bad cas value")
		}
	}
	self.command = line[0]
	self.key = line[1]
	self.flags = uint32(flags)
	if exptime == 0 || exptime > secondsInMonth {
		self.exptime = uint32(exptime)
	} else {
		self.exptime = uint32(time.Seconds()) + uint32(exptime)
	}
	self.bytes = uint32(bytes)
	self.cas_unique = casuniq
	if line[len(line)-1] == "noreply" {
		self.noreply = true
	}
	return self.readData()
}
Example #2
0
func (self *MapCacheStorage) Incr(key string, value uint64, incr bool) (ErrorCode, *StorageEntry, *StorageEntry) {
	self.rwLock.Lock()
	defer self.rwLock.Unlock()
	entry, present := self.storageMap[key]
	if present && !entry.expired() {
		if addValue, err := strconv.Atoui64(string(entry.content)); err == nil {
			var incrValue uint64
			if incr {
				incrValue = uint64(addValue) + value
			} else if value > addValue {
				incrValue = 0
			} else {
				incrValue = uint64(addValue) - value
			}
			incrStrValue := strconv.Uitoa64(incrValue)
			old_value := entry.content
			entry.content = []byte(incrStrValue)
			entry.bytes = uint32(len(entry.content))
			entry.cas_unique += 1
			return Ok, &StorageEntry{entry.exptime, entry.flags, entry.bytes, entry.cas_unique, old_value}, entry
		} else {
			return IllegalParameter, nil, nil
		}
	}
	return KeyNotFound, nil, nil
}
Example #3
0
// Get node value as uint64
func (this *Node) U64(namespace, name string) uint64 {
	if node := rec_SelectNode(this, namespace, name); node != nil && node.Value != "" {
		n, _ := strconv.Atoui64(node.Value)
		return n
	}
	return 0
}
Example #4
0
// Get attribute value as uint64
func (this *Node) Au64(namespace, name string) uint64 {
	if s := this.As(namespace, name); s != "" {
		n, _ := strconv.Atoui64(s)
		return n
	}
	return 0
}
Example #5
0
func (r result) checkForInt(c *Conn, s string) (uint64, os.Error) {
	if r.err != nil {
		return 0, Error{c.Name, r.cmd, r.line, r.err}
	}

	if err, ok := replyErrors[r.name]; ok {
		return 0, Error{c.Name, r.cmd, r.line, err}
	}

	if r.name != s {
		return 0, Error{c.Name, r.cmd, r.line, BadReply}
	}

	if len(r.args) != 1 {
		return 0, Error{c.Name, r.cmd, r.line, BadReply}
	}

	n, err := strconv.Atoui64(r.args[0])

	if err != nil {
		return 0, Error{c.Name, r.cmd, r.line, BadReply}
	}

	return n, nil
}
Example #6
0
func AsUint64(v interface{}) (uint64, os.Error) {
	switch value := v.(type) {
	default:
		return 0, os.NewError(fmt.Sprintf("unexpected type: %T", value))
	case int:
		return uint64(value), nil
	case int8:
		return uint64(value), nil
	case int16:
		return uint64(value), nil
	case int32:
		return uint64(value), nil
	case int64:
		return uint64(value), nil
	case uint:
		return uint64(value), nil
	case uint8:
		return uint64(value), nil
	case uint16:
		return uint64(value), nil
	case uint32:
		return uint64(value), nil
	case uint64:
		return value, nil
	case float32:
		return uint64(value), nil
	case float64:
		return uint64(value), nil
	case string:
		return strconv.Atoui64(value)
	}
	panic(fmt.Sprintf("unsupported type: %s", reflect.ValueOf(v).Type().Name()))
}
Example #7
0
func (r result) checkForJob(c *Conn, s string) (*Job, os.Error) {
	if r.err != nil {
		return nil, Error{c.Name, r.cmd, r.line, r.err}
	}

	if err, ok := replyErrors[r.name]; ok {
		return nil, Error{c.Name, r.cmd, r.line, err}
	}

	if r.name != s {
		return nil, Error{c.Name, r.cmd, r.line, BadReply}
	}

	if len(r.args) != 2 {
		return nil, Error{c.Name, r.cmd, r.line, BadReply}
	}

	id, err := strconv.Atoui64(r.args[0])

	if err != nil {
		return nil, Error{c.Name, r.cmd, r.line, BadReply}
	}

	return &Job{id, r.body, c}, nil
}
Example #8
0
func decodeColumn(idx int, field *mysql.Field, val interface{}) (interface{}, os.Error) {
	var dec interface{}
	var err os.Error
	switch v := val.(type) {
	case int64:
		return v, nil
	case []byte:
		switch field.Type {
		case mysql.FIELD_TYPE_TINY, mysql.FIELD_TYPE_SHORT, mysql.FIELD_TYPE_YEAR, mysql.FIELD_TYPE_INT24, mysql.FIELD_TYPE_LONG, mysql.FIELD_TYPE_LONGLONG:
			if field.Flags&mysql.FLAG_UNSIGNED != 0 {
				dec, err = strconv.Atoui64(string(v))
			} else {
				dec, err = strconv.Atoi64(string(v))
			}
			if err != nil {
				return nil, fmt.Errorf("mysql: strconv.Atoi64 error on field %d: %v", idx, err)
			}
		case mysql.FIELD_TYPE_FLOAT, mysql.FIELD_TYPE_DOUBLE:
			dec, err = strconv.Atof64(string(v))
			if err != nil {
				return nil, fmt.Errorf("mysql: strconv.Atof64 error on field %d: %v", idx, err)
			}
		case mysql.FIELD_TYPE_DECIMAL, mysql.FIELD_TYPE_NEWDECIMAL, mysql.FIELD_TYPE_VARCHAR, mysql.FIELD_TYPE_VAR_STRING, mysql.FIELD_TYPE_STRING:
			dec = string(v)
		default:
			return nil, fmt.Errorf("row[%d] was a []byte but unexpected field type %d", idx, field.Type)
		}
		return dec, nil
	}
	return nil, fmt.Errorf("expected row[%d] contents to be a []byte, got %T for field type %d", idx, val, field.Type)
}
Example #9
0
func getIDFromIDFile() (uint64, os.Error) {
	G_idServerLock.Lock()
	defer G_idServerLock.Unlock()
	fd, err := os.Open(IDFILE, os.O_RDONLY, 0666)
	if err == nil {
		buf := bufio.NewReader(fd)
		lineofbytes, errb := buf.ReadBytes('\n')
		if errb == nil {
			lineofbytes = TrimCRLF(lineofbytes)
			fd.Close()
			return strconv.Atoui64(string(lineofbytes))
		} else {
			fmt.Println("Error creating bufio.NewReader(fd)")
		}
	} else {
		// Error reading file, does it exist?
		stat, _ := os.Stat(IDFILE)
		if stat == nil {
			// File doesn't exist
			fmt.Println("id.txt doesn't exist... Create one...")
			createNewIDFile()
		} else {
			fmt.Println("Can't open id.txt, but it does exist... FATAL.")
			os.Exit(-2)
		}
		return 0, nil
	}

	return 0, os.NewError("Impossible")
}
Example #10
0
func (this ParamList) U64(i int, defval uint64) uint64 {
	if -1 < i && i < len(this) {
		if v, err := strconv.Atoui64(this[i]); err == nil {
			return v
		}
	}
	return defval
}
Example #11
0
func (this *Section) U64(key string, defval uint64) uint64 {
	if v, ok := this.Pairs[key]; ok {
		if n, err := strconv.Atoui64(v); err == nil {
			return n
		}
	}
	return defval
}
Example #12
0
func Euler43() string {
	sum := uint64(0)
	pand := []byte("1023456789")
	for arithmetics.Permute(pand) {
		hasProperty := true
		for i, prime := range smallprimes {
			num, _ := strconv.Atoui64(string(pand[1+i : 4+i]))
			if num%prime != 0 {
				hasProperty = false
				break
			}
		}
		if hasProperty {
			num, _ := strconv.Atoui64(string(pand))
			sum += num
		}
	}
	return fmt.Sprint(sum)
}
func (self *Coder) prepare() {
	if self.Ctx == nil {
		self.Ctx = C.avcodec_alloc_context()
		cid, _ := strconv.Atoui64(self.Parameter["codecid"])
		self.Ctx.codec_id = uint32(cid)
	}
	/**
	 * @TODO: settng the fixed params like width, height, channels...
	 */
}
Example #14
0
func (cl *cleaner) update(ev store.Event) {
	parts := strings.Split(ev.Path, "/", -1)
	id := parts[3]
	seqn, err := strconv.Atoui64(ev.Body)
	if err != nil {
		cl.logger.Println(err)
		return
	}
	cl.table[id] = seqn
}
Example #15
0
func copyValue(dst reflect.Value, src []byte) (err os.Error) {
	// Helper functions for integer and unsigned integer conversions
	var itmp int64
	getInt64 := func() bool {
		itmp, err = strconv.Atoi64(string(src))
		// TODO: should check sizes
		return err == nil
	}
	var utmp uint64
	getUint64 := func() bool {
		utmp, err = strconv.Atoui64(string(src))
		// TODO: check for overflow?
		return err == nil
	}
	var ftmp float64
	getFloat64 := func() bool {
		ftmp, err = strconv.Atof64(string(src))
		// TODO: check for overflow?
		return err == nil
	}

	// Save accumulated data and comments
	switch t := dst; t.Kind() {
	case reflect.Invalid:
		// Probably a comment, handled below
	default:
		return os.NewError("cannot happen: unknown type " + t.Type().String())
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		if !getInt64() {
			return err
		}
		t.SetInt(itmp)
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
		if !getUint64() {
			return err
		}
		t.SetUint(utmp)
	case reflect.Float32, reflect.Float64:
		if !getFloat64() {
			return err
		}
		t.SetFloat(ftmp)
	case reflect.Bool:
		value, err := strconv.Atob(strings.TrimSpace(string(src)))
		if err != nil {
			return err
		}
		t.SetBool(value)
	case reflect.String:
		t.SetString(string(src))
	case reflect.Slice:
		t.Set(reflect.ValueOf(src))
	}
	return nil
}
Example #16
0
func (self *coder) prepare() {
	if self.Ctx.ctx == nil {
		println("Alloc Encoder Context")
		cid, _ := strconv.Atoui64(self.Parameter["codecid"])
		if cid == 0 {
			if self.codec_type == CODEC_TYPE_ENCODER {
				self.Codec = avcodec_find_encoder_by_name(self.Parameter["codecid"])
			}
			if self.codec_type == CODEC_TYPE_DECODER {
				self.Codec = avcodec_find_decoder_by_name(self.Parameter["codecid"])
			}
			if self.Codec.codec != nil {
				cid = uint64(self.Codec.codec.id) //,_:=strconv.Atoui64(self.Parameter["codecid"])
			}
		}
		log.Printf("searching for codec id %d", cid)
		self.Ctx = *avcodec_alloc_context()
		if len(self.ExtraData) > 0 {
			self.Ctx.ctx.extradata = (*_Ctypedef_uint8_t)(unsafe.Pointer(&self.ExtraData[0]))
		}

		self.pre_allocated = false
		self.Ctx.ctx.codec_id = uint32(cid)
		runtime.SetFinalizer(self, close_coder)
	} else {
		//c.pre_allocated=true
	}
	width, err := strconv.Atoi(self.Parameter["width"])
	if err == nil {
		self.Ctx.ctx.width = _Ctype_int(width)
		log.Printf("setting width to %d", self.Ctx.ctx.width)
	} else {
		//    println(err.String())
	}
	height, err := strconv.Atoi(self.Parameter["height"])
	if err == nil {
		self.Ctx.ctx.height = _Ctype_int(height)
		log.Printf("setting height to %d", self.Ctx.ctx.height)
	} else {
		//    println(err.String())
	}
	channels, err := strconv.Atoi(self.Parameter["ac"])
	if err == nil {
		self.Ctx.ctx.channels = _Ctype_int(channels)
		log.Printf("setting channels to %d", self.Ctx.ctx.channels)
	} else {
		//    println(err.String())
	}
	self.Ctx.ctx.debug = 0
	self.Ctx.ctx.debug_mv = 0
	/**
	 * @TODO: settng the fixed params like width, height, channels...
	 */
}
Example #17
0
// ArrayType = "[" int_lit "]" Type .
//
func (p *gcParser) parseArrayType() Type {
	// "[" already consumed and lookahead known not to be "]"
	lit := p.expect(scanner.Int)
	p.expect(']')
	elt := p.parseType()
	n, err := strconv.Atoui64(lit)
	if err != nil {
		p.error(err)
	}
	return &Array{Len: n, Elt: elt}
}
Example #18
0
func singleStatus(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	statusId, _ := strconv.Atoui64(strings.TrimLeft(r.URL.Path, "/status/"))
	c.Debugf("Trying to fetch status %s from cache", statusId)
	status, err := model.GetStatusById(c, statusId)
	if err == nil {
		renderStatus(w, status)
	} else {
		renderError(w, "Could not find status! <a href=\"/\">Reload me.<a>")
	}

}
Example #19
0
// There is no strconv.Atoui32, so make one here.
func atoui32(s string) (n uint32, err os.Error) {
	iu64, err := strconv.Atoui64(s)
	if err != nil {
		return 0, err
	}

	n = uint32(iu64)
	if uint64(n) != iu64 {
		return 0, &strconv.NumError{s, os.ERANGE}
	}

	return n, nil
}
Example #20
0
func (decoder *Decoder) readString(value reflect.Value) error {

	index, err := decoder.readU29()
	if err != nil {
		return err
	}

	ret := ""
	if (index & 0x01) == 0 {
		ret = decoder.stringCache[int(index>>1)]
	} else {
		index >>= 1
		bytes, err := decoder.readBytes(int(index))
		if err != nil {
			return err
		}

		ret = string(bytes)
	}

	if ret != "" {
		decoder.stringCache = append(decoder.stringCache, ret)
	}

	switch value.Kind() {
	case reflect.Int, reflect.Int32, reflect.Int64:
		num, err := strconv.Atoi64(ret)
		if err != nil {
			return err
		}

		value.SetInt(num)
	case reflect.Uint, reflect.Uint32, reflect.Uint64:
		num, err := strconv.Atoui64(ret)
		if err != nil {
			return err
		}

		value.SetUint(num)
	case reflect.String:
		value.SetString(ret)
	case reflect.Interface:
		value.Set(reflect.ValueOf(ret))
	default:
		return errors.New("invalid type:" + value.Type().String() + " for string")
	}

	return nil
}
Example #21
0
/**
 * Read row data packet
 */
func (pkt *packetRowData) read(reader *bufio.Reader) (err os.Error) {
	// Read (check if exists) null bit map
	c, err := reader.ReadByte()
	if err != nil {
		return
	}
	if c >= 0x40 && c <= 0x7f {
		pkt.nullBitMap = c
	} else {
		reader.UnreadByte()
	}
	// Allocate memory
	pkt.values = make([]interface{}, len(pkt.fields))
	// Read data for each field
	for i, field := range pkt.fields {
		str, _, err := pkt.readlengthCodedString(reader)
		if err != nil {
			return
		}
		switch field.Type {
		// Strings and everythign else, keep as string
		default:
			pkt.values[i] = str
		// Tiny, small + med int convert into (u)int
		case FIELD_TYPE_TINY, FIELD_TYPE_SHORT, FIELD_TYPE_LONG:
			if field.Flags.Unsigned {
				pkt.values[i], _ = strconv.Atoui(str)
			} else {
				pkt.values[i], _ = strconv.Atoi(str)
			}
		// Big int convert to (u)int64
		case FIELD_TYPE_LONGLONG:
			if field.Flags.Unsigned {
				pkt.values[i], _ = strconv.Atoui64(str)
			} else {
				pkt.values[i], _ = strconv.Atoi64(str)
			}
		// Floats
		case FIELD_TYPE_FLOAT:
			pkt.values[i], _ = strconv.Atof32(str)
		// Double
		case FIELD_TYPE_DOUBLE:
			pkt.values[i], _ = strconv.Atof64(str)
		}
	}
	return
}
Example #22
0
func (r *result) checkForJob(c *Conn) (*Job, os.Error) {
	if r.err != nil {
		return nil, Error{c.Name, r.line, r.err}
	}

	if len(r.args) != 2 {
		return nil, Error{c.Name, r.line, BadReply}
	}

	id, err := strconv.Atoui64(r.args[0])

	if err != nil {
		return nil, Error{c.Name, r.line, BadReply}
	}

	return &Job{id, r.body, c}, nil
}
Example #23
0
func (r *result) checkForInt(c *Conn) (uint64, os.Error) {
	if r.err != nil {
		return 0, Error{c.Name, r.line, r.err}
	}

	if len(r.args) != 1 {
		return 0, Error{c.Name, r.line, BadReply}
	}

	n, err := strconv.Atoui64(r.args[0])

	if err != nil {
		return 0, Error{c.Name, r.line, BadReply}
	}

	return n, nil
}
Example #24
0
func (self *IncrCommand) parse(line []string) bool {
	var err os.Error
	if len(line) < 3 {
		return Error(self.session, ClientError, "Bad incr/decr command: missing parameters")
	} else if self.value, err = strconv.Atoui64(line[2]); err != nil {
		return Error(self.session, ClientError, "Bad incr/decr command: bad value")
	}
	self.incr = (line[0] == "incr")
	self.key = line[1]

	if len(line) == 4 && line[3] == "noreply" {
		self.noreply = true
	} else {
		self.noreply = false
	}
	return true
}
Example #25
0
func (s *mapStorage) Inc(key, subKey string) (uint64, os.Error) {
	num := uint64(0)
	err := s.Update(key, func(obj map[string]string) os.Error {
		numStr, ok := obj[subKey]
		if ok {
			num2, err := strconv.Atoui64(numStr)
			if err != nil {
				return err
			}
			num = num2
		}
		obj[subKey] = strconv.Uitoa64(num + 1)
		return nil
	})
	if err != nil {
		return 0, err
	}
	return num + 1, nil
}
Example #26
0
func writeTo(s string, val reflect.Value) os.Error {
	switch v := val.(type) {
	// if we're writing to an interace value, just set the byte data
	// TODO: should we support writing to a pointer?
	case *reflect.InterfaceValue:
		v.Set(reflect.NewValue(s))
	case *reflect.BoolValue:
		if strings.ToLower(s) == "false" || s == "0" {
			v.Set(false)
		} else {
			v.Set(true)
		}
	case *reflect.IntValue:
		i, err := strconv.Atoi64(s)
		if err != nil {
			return err
		}
		v.Set(i)
	case *reflect.UintValue:
		ui, err := strconv.Atoui64(s)
		if err != nil {
			return err
		}
		v.Set(ui)
	case *reflect.FloatValue:
		f, err := strconv.Atof64(s)
		if err != nil {
			return err
		}
		v.Set(f)

	case *reflect.StringValue:
		v.Set(s)

	case *reflect.SliceValue:
		typ := v.Type().(*reflect.SliceType)
		if _, ok := typ.Elem().(*reflect.UintType); ok {
			v.Set(reflect.NewValue([]byte(s)).(*reflect.SliceValue))
		}
	}
	return nil
}
Example #27
0
func writeTo(data []byte, val reflect.Value) os.Error {
	s := string(data)
	switch v := val; v.Kind() {
	// if we're writing to an interace value, just set the byte data
	// TODO: should we support writing to a pointer?
	case reflect.Interface:
		v.Set(reflect.ValueOf(data))
	case reflect.Bool:
		b, err := strconv.Atob(s)
		if err != nil {
			return err
		}
		v.SetBool(b)
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		i, err := strconv.Atoi64(s)
		if err != nil {
			return err
		}
		v.SetInt(i)
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
		ui, err := strconv.Atoui64(s)
		if err != nil {
			return err
		}
		v.SetUint(ui)
	case reflect.Float32, reflect.Float64:
		f, err := strconv.Atof64(s)
		if err != nil {
			return err
		}
		v.SetFloat(f)

	case reflect.String:
		v.SetString(s)
	case reflect.Slice:
		typ := v.Type()
		if typ.Elem().Kind() == reflect.Uint || typ.Elem().Kind() == reflect.Uint8 || typ.Elem().Kind() == reflect.Uint16 || typ.Elem().Kind() == reflect.Uint32 || typ.Elem().Kind() == reflect.Uint64 || typ.Elem().Kind() == reflect.Uintptr {
			v.Set(reflect.ValueOf(data))
		}
	}
	return nil
}
Example #28
0
func writeTo(data []byte, val reflect.Value) os.Error {
	s := string(data)
	switch v := val.(type) {
	// if we're writing to an interace value, just set the byte data
	// TODO: should we support writing to a pointer?
	case *reflect.InterfaceValue:
		v.Set(reflect.NewValue(data))
	case *reflect.BoolValue:
		b, err := strconv.Atob(s)
		if err != nil {
			return err
		}
		v.Set(b)
	case *reflect.IntValue:
		i, err := strconv.Atoi64(s)
		if err != nil {
			return err
		}
		v.Set(i)
	case *reflect.UintValue:
		ui, err := strconv.Atoui64(s)
		if err != nil {
			return err
		}
		v.Set(ui)
	case *reflect.FloatValue:
		f, err := strconv.Atof64(s)
		if err != nil {
			return err
		}
		v.Set(f)

	case *reflect.StringValue:
		v.Set(s)
	case *reflect.SliceValue:
		typ := v.Type().(*reflect.SliceType)
		if _, ok := typ.Elem().(*reflect.UintType); ok {
			v.Set(reflect.NewValue(data).(*reflect.SliceValue))
		}
	}
	return nil
}
Example #29
0
func (self *TouchCommand) parse(line []string) bool {
	var exptime uint64
	var err os.Error
	if len(line) < 3 {
		return Error(self.session, ClientError, "Bad touch command: missing parameters")
	} else if exptime, err = strconv.Atoui64(line[2]); err != nil {
		return Error(self.session, ClientError, "Bad touch command: bad expiration time")
	}
	self.command = line[0]
	self.key = line[1]
	if exptime == 0 || exptime > secondsInMonth {
		self.exptime = uint32(exptime)
	} else {
		self.exptime = uint32(time.Seconds()) + uint32(exptime)
	}
	if line[len(line)-1] == "noreply" {
		self.noreply = true
	}
	return true
}
Example #30
0
func indexHandler(ws *websocket.Conn) {
	var ibuff [50]byte

	i, err := ws.Read(ibuff[0:50])
	if err != nil {
		fmt.Printf("WebSocket error: " + err.String())
		return
	}

	msg := string(ibuff[0:i])
	idx := strings.Index(msg, "!")
	if idx < 0 {
		fmt.Printf("Salt not found\n")
		return
	}

	idstr := msg[0:idx]
	salt := msg[idx+1:]

	uid, err := strconv.Atoui64(idstr)
	if err != nil {
		fmt.Printf("User ID invalid\n")
		return
	}

	defer UnlinkUser(uid, ws)

	usr := LinkUser(uid, salt, ws)
	if usr == nil {
		fmt.Printf("Cannot link with User ID\n")
		return
	}

	for usr.exit == false {
		time.Sleep(1e8)

		if IsClosed(ws) {
			break
		}
	}
}