Пример #1
0
func main() {
	limit := uint64(100000000)
	square_sums := []uint64{}
	for i := uint64(0); i < limit; i++ {
		square_sums = append(square_sums, (uint64)(i*(i+1)*(2*i+1)/6))
		if i*i > limit {
			break
		}
	}
	palins := []uint64{}
	for i := 0; i < len(square_sums); i++ {
		for j := 0; j < i; j++ {
			sq_sum := square_sums[i] - square_sums[j]
			if i-j > 1 && sq_sum < limit && strconv.Uitoa64(sq_sum) == Reverse(strconv.Uitoa64(sq_sum)) {
				exists := false
				for k := 0; k < len(palins); k++ {
					if palins[k] == sq_sum {
						exists = true
					}
				}
				if !exists {
					palins = append(palins, sq_sum)
				}
			}
		}
	}
	sum := uint64(0)
	for _, palin := range palins {
		sum += palin
	}
	fmt.Println(sum)
}
Пример #2
0
func valueToString(v reflect.Value) (string, os.Error) {
	if v == nil {
		return "null", nil
	}

	switch v := v.(type) {
	case *reflect.PtrValue:
		return valueToString(reflect.Indirect(v))
	case *reflect.InterfaceValue:
		return valueToString(v.Elem())
	case *reflect.BoolValue:
		x := v.Get()
		if x {
			return "true", nil
		} else {
			return "false", nil
		}

	case *reflect.IntValue:
		return strconv.Itoa(v.Get()), nil
	case *reflect.Int8Value:
		return strconv.Itoa(int(v.Get())), nil
	case *reflect.Int16Value:
		return strconv.Itoa(int(v.Get())), nil
	case *reflect.Int32Value:
		return strconv.Itoa(int(v.Get())), nil
	case *reflect.Int64Value:
		return strconv.Itoa64(v.Get()), nil

	case *reflect.UintValue:
		return strconv.Uitoa(v.Get()), nil
	case *reflect.Uint8Value:
		return strconv.Uitoa(uint(v.Get())), nil
	case *reflect.Uint16Value:
		return strconv.Uitoa(uint(v.Get())), nil
	case *reflect.Uint32Value:
		return strconv.Uitoa(uint(v.Get())), nil
	case *reflect.Uint64Value:
		return strconv.Uitoa64(v.Get()), nil
	case *reflect.UintptrValue:
		return strconv.Uitoa64(uint64(v.Get())), nil

	case *reflect.FloatValue:
		return strconv.Ftoa(v.Get(), 'g', -1), nil
	case *reflect.Float32Value:
		return strconv.Ftoa32(v.Get(), 'g', -1), nil
	case *reflect.Float64Value:
		return strconv.Ftoa64(v.Get(), 'g', -1), nil

	case *reflect.StringValue:
		return v.Get(), nil
	case *reflect.SliceValue:
		typ := v.Type().(*reflect.SliceType)
		if _, ok := typ.Elem().(*reflect.Uint8Type); ok {
			return string(v.Interface().([]byte)), nil
		}
	}
	return "", os.NewError("Unsupported type")
}
Пример #3
0
func module(f string) (string, os.Error) {
	i, err := os.Stat(f)
	if err != nil {
		return "", err
	}

	m := "$" + f + "-" + strconv.Uitoa64(i.Dev) + "-" +
		strconv.Uitoa64(i.Ino) + "-" + strconv.Itoa64(i.Blocks) + "-" +
		strconv.Itoa64(i.Mtime_ns)

	return m, nil
}
Пример #4
0
func formatReflectValue(x reflect.Value) (string, os.Error) {
	/*
	   if !x.CanSet() {
	       return "", ErrorCantSet
	   }
	*/
	var (
		errc os.Error
		kind = x.Kind()
		//vintstr   string
	)
	switch kind {
	// Format pointers to standard types.
	case reflect.String:
		return x.Interface().(string), nil
	case reflect.Int:
		return strconv.Itoa(x.Interface().(int)), nil
	case reflect.Int8:
		return strconv.Itoa64(int64(x.Interface().(int8))), nil
	case reflect.Int16:
		return strconv.Itoa64(int64(x.Interface().(int16))), nil
	case reflect.Int32:
		return strconv.Itoa64(int64(x.Interface().(int32))), nil
	case reflect.Int64:
		return strconv.Itoa64(x.Interface().(int64)), nil
	case reflect.Uint:
		return strconv.Uitoa(x.Interface().(uint)), nil
	case reflect.Uint8:
		return strconv.Uitoa64(uint64(x.Interface().(uint8))), nil
	case reflect.Uint16:
		return strconv.Uitoa64(uint64(x.Interface().(uint16))), nil
	case reflect.Uint32:
		return strconv.Uitoa64(uint64(x.Interface().(uint32))), nil
	case reflect.Uint64:
		return strconv.Uitoa64(x.Interface().(uint64)), nil
	case reflect.Float32:
		return strconv.Ftoa32(x.Interface().(float32), FloatFmt, FloatPrec), nil
	case reflect.Float64:
		return strconv.Ftoa64(x.Interface().(float64), FloatFmt, FloatPrec), nil
	case reflect.Complex64:
		fallthrough
	case reflect.Complex128:
		errc = ErrorUnimplemented
	case reflect.Bool:
		return strconv.Btoa(x.Interface().(bool)), nil
	default:
		errc = ErrorFieldType
	}
	return "", errc
}
Пример #5
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
}
Пример #6
0
// any to string
func atos(i interface{}) (s string) {
	switch t := i.(type) {
	case int64:
		s = strconv.Itoa64(t)
	case uint64:
		s = strconv.Uitoa64(t)
	case float32:
		s = strconv.Ftoa32(t, 'f', -1)
	case float64:
		s = strconv.Ftoa64(t, 'f', -1)
	case []byte:
		s = string(t)
	case Date:
		return t.String()
	case Time:
		return t.String()
	case DateTime:
		return t.String()
	case string:
		return t
	default:
		panic("Not a string or compatible type")
	}
	return
}
Пример #7
0
func (f *Fortuna) reseed() {
	logTrace("--> F.reseed()")
	// on the n-th reseeding, pool k is used only if 2**k divides n
	f.timesSeeded++
	logDebug("F.reseed(): timesSeeded = " + strconv.Uitoa64(f.timesSeeded))
	f.lock.Lock()
	for k := 0; k < 32; k++ {
		if f.timesSeeded%(1<<uint64(k)) == 0 {
			poolBytes := f.pools[k].Sum()
			f.generator.md.Write(poolBytes)
		}
	}
	f.lock.Unlock()
	f.generator.reseed()
	f.pool0Count = 0
	f.timeLastSeeded = currentTimeMillis()
	if f.timesSeeded == 1 {
		logInfo("F.reseed(): Fortuna is ready and able...")
	}
	// IMPLEMENTATION NOTE (rsn) - we're supposed to save the random seed
	// just before a shutdown.  since we cannot do that in Go we opt for
	// saving it every 10 minutes and every 1000 reseedings.
	if f.timesSeeded%timesSeededPeriod == 0 {
		go updateSeedFile(f)
	}
	logTrace("<-- F.reseed()")
}
Пример #8
0
func enc(val reflect.Value, typ reflect.Type, buffer *bytes.Buffer, req bool) (encoded bool, err os.Error) {
	switch typ.(type) {
	case *reflect.PtrType:
		// log.Println("pointer")
		pt := typ.(*reflect.PtrType).Elem()
		pv := reflect.Indirect(val)
		// log.Println("Type is: ", pt.Name())
		if pv == nil {
			if !req {
				return false, nil
			} else {
				return false, os.NewError("Required field is nil")
			}
		}
		return enc(pv, pt, buffer, req)
	case *reflect.BoolType:
		if val.(*reflect.BoolValue).Get() {
			buffer.WriteString("true")
		} else {
			buffer.WriteString("false")
		}
	case *reflect.IntType:
		buffer.WriteString(strconv.Itoa64(val.(*reflect.IntValue).Get()))
	case *reflect.UintType:
		buffer.WriteString(strconv.Uitoa64(val.(*reflect.UintValue).Get()))
	case *reflect.StringType:
		buffer.WriteString("\"")
		// TODO: encode
		buffer.WriteString(val.(*reflect.StringValue).Get())
		buffer.WriteString("\"")
	case *reflect.FloatType:
		buffer.WriteString(strconv.Ftoa64(val.(*reflect.FloatValue).Get(), 'e', -1))
	case *reflect.StructType:
		enc_struct(val.(*reflect.StructValue), typ.(*reflect.StructType), buffer)
	case *reflect.SliceType:
		st := typ.(*reflect.SliceType).Elem()
		sv := val.(*reflect.SliceValue)
		if sv.IsNil() {
			if req {
				return false, os.NewError("Required field is nil")
			} else {
				return false, nil
			}
		}
		buffer.WriteString("[")
		for i := 0; i < sv.Len(); i++ {
			if i > 0 {
				buffer.WriteString(",")
			}
			_, err := enc(sv.Elem(i), st, buffer, true)
			if err != nil {
				return false, err
			}
		}
		buffer.WriteString("]")
	default:
		return false, os.NewError("Unsupported type")
	}
	return true, nil
}
Пример #9
0
func AsString(v interface{}) (string, os.Error) {
	switch value := v.(type) {
	default:
		return "", os.NewError(fmt.Sprintf("unexpected type: %T", value))
	case int:
		return strconv.Itoa(value), nil
	case int8:
		return strconv.Itoa(int(value)), nil
	case int16:
		return strconv.Itoa(int(value)), nil
	case int32:
		return strconv.Itoa(int(value)), nil
	case int64:
		return strconv.Itoa64(value), nil
	case uint:
		return strconv.Uitoa(value), nil
	case uint8:
		return strconv.Uitoa(uint(value)), nil
	case uint16:
		return strconv.Uitoa(uint(value)), nil
	case uint32:
		return strconv.Uitoa(uint(value)), nil
	case uint64:
		return strconv.Uitoa64(value), nil
	case float32:
		return strconv.Ftoa32(value, 'g', -1), nil
	case float64:
		return strconv.Ftoa64(value, 'g', -1), nil
	case string:
		return value, nil
	}
	panic(fmt.Sprintf("unsupported type: %s", reflect.ValueOf(v).Type().Name()))
}
Пример #10
0
func valueToString(v reflect.Value) (string, os.Error) {
	if v == nil {
		return "null", nil
	}

	switch v := v.(type) {
	case *reflect.PtrValue:
		return valueToString(reflect.Indirect(v))
	case *reflect.InterfaceValue:
		return valueToString(v.Elem())
	case *reflect.BoolValue:
		x := v.Get()
		if x {
			return "true", nil
		} else {
			return "false", nil
		}

	case *reflect.IntValue:
		return strconv.Itoa64(v.Get()), nil
	case *reflect.UintValue:
		return strconv.Uitoa64(v.Get()), nil
	case *reflect.UnsafePointerValue:
		return strconv.Uitoa64(uint64(v.Get())), nil

	case *reflect.FloatValue:
		return strconv.Ftoa64(v.Get(), 'g', -1), nil

	case *reflect.StringValue:
		return v.Get(), nil

	//This is kind of a rough hack to replace the old []byte
	//detection with reflect.Uint8Type, it doesn't catch
	//zero-length byte slices
	case *reflect.SliceValue:
		typ := v.Type().(*reflect.SliceType)
		if _, ok := typ.Elem().(*reflect.UintType); ok {
			if v.Len() > 0 {
				if v.Elem(1).(*reflect.UintValue).Overflow(257) {
					return string(v.Interface().([]byte)), nil
				}
			}
		}
	}
	return "", os.NewError("Unsupported type")
}
Пример #11
0
func valueToString(v reflect.Value) (string, os.Error) {
	if !v.IsValid() {
		return "null", nil
	}

	switch v.Kind() {
	case reflect.Ptr:
		return valueToString(reflect.Indirect(v))
	case reflect.Interface:
		return valueToString(v.Elem())
	case reflect.Bool:
		x := v.Bool()
		if x {
			return "true", nil
		} else {
			return "false", nil
		}

	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return strconv.Itoa64(v.Int()), nil
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
		return strconv.Uitoa64(v.Uint()), nil
	case reflect.UnsafePointer:
		return strconv.Uitoa64(uint64(v.Pointer())), nil

	case reflect.Float32, reflect.Float64:
		return strconv.Ftoa64(v.Float(), 'g', -1), nil

	case reflect.String:
		return v.String(), nil

	//This is kind of a rough hack to replace the old []byte
	//detection with reflect.Uint8Type, it doesn't catch
	//zero-length byte slices
	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 {
			if v.Len() > 0 {
				if v.Index(1).OverflowUint(257) {
					return string(v.Interface().([]byte)), nil
				}
			}
		}
	}
	return "", os.NewError("Unsupported type")
}
Пример #12
0
func (sh *serverHeap) printPresent() string {
	var out string = ""
	cnt := sh.vec.Len()
	for i := 0; i < cnt; i++ {
		s := sh.vec.At(i).(*server)
		out += "\ts.id: " + strconv.Uitoa64(s.id) + " addr: " + fmt.Sprintf("%s:%d", s.addr.IP.String(), s.addr.Port) + " nchunks: " + strconv.Itoa(s.chunks.Len()) + " chunks: "

		cnt2 := s.chunks.Len()
		for j := 0; j < cnt2; j++ {
			out += strconv.Uitoa64(s.chunks.At(j).(*chunk).chunkID) + ", "
		}

		out += "\n"
	}

	//log.Printf("master: server heap state follows:\n%s", out)
	return out
}
Пример #13
0
func main() {
	flag.Parse()
	fmt.Println("Consuming Messages :")
	fmt.Printf("From: %s, topic: %s, partition: %d\n", hostname, topic, partition)
	fmt.Println(" ---------------------- ")
	broker := kafka.NewBrokerConsumer(hostname, topic, partition, offset, uint32(maxSize))

	var payloadFile *os.File = nil
	if len(writePayloadsTo) > 0 {
		var err os.Error
		payloadFile, err = os.Create(writePayloadsTo)
		if err != nil {
			fmt.Println("Error opening file: ", err)
			payloadFile = nil
		}
	}

	consumerCallback := func(msg *kafka.Message) {
		if printmessage {
			msg.Print()
		}
		if payloadFile != nil {
			payloadFile.Write([]byte("Message at: " + strconv.Uitoa64(msg.Offset()) + "\n"))
			payloadFile.Write(msg.Payload())
			payloadFile.Write([]byte("\n-------------------------------\n"))
		}
	}

	if consumerForever {
		quit := make(chan bool, 1)
		go func() {
			for {
				sig := <-signal.Incoming
				if sig.(signal.UnixSignal) == syscall.SIGINT {
					quit <- true
				}
			}
		}()

		msgChan := make(chan *kafka.Message)
		go broker.ConsumeOnChannel(msgChan, 10, quit)
		for msg := range msgChan {
			if msg != nil {
				consumerCallback(msg)
			} else {
				break
			}
		}
	} else {
		broker.Consume(consumerCallback)
	}

	if payloadFile != nil {
		payloadFile.Close()
	}

}
Пример #14
0
// Update the prefix on a membership entry.
func (p *ModeParser) updatePrefix(m *core.Membership) {
	var prefix string
	for it := p.prefixes; it != nil; it = it.next {
		if m.Data(it.metadata) != "" {
			prefix += string(it.prefix)
		}
	}
	m.SetData("", nil, strconv.Uitoa64(p.id)+" prefixes", prefix)
}
Пример #15
0
func stringName(i uint32, names []intName, goSyntax bool) string {
	for _, n := range names {
		if n.i == i {
			if goSyntax {
				return "macho." + n.s
			}
			return n.s
		}
	}
	return strconv.Uitoa64(uint64(i))
}
Пример #16
0
func TestDecr(t *testing.T) {
	connect(t)
	err := memc.Add(KEY_1, []uint8("1243"), FLAGS, 0)
	assertNoError(t, err)
	i, err := memc.Decr(KEY_1, 9)
	assertNoError(t, err)
	if i != 1234 {
		t.Error("Value expected: 1234\nValue received: " + strconv.Uitoa64(i))
	}
	cleanUp()
}
Пример #17
0
func HandleNewClient(con *net.Conn, lst *list.List) {
	id := "USER" + strconv.Uitoa64(*idCounter)
	*idCounter++
	var newClient = new(UserInfo)
	newClient.Init(id, con, nil, lst, true)
	Log("HandleClient(): for " + id)
	PrintUsageToClient(newClient)
	go ClientSender(newClient)
	go ClientReceiver(newClient)
	lst.PushBack(newClient)
}
Пример #18
0
func NewInteger(arg Any) *Integer {
	var result big.Int
	switch arg.(type) {
	case int:
		result.SetInt64(int64(arg.(int)))
	case int64:
		result.SetInt64(arg.(int64))
	case uint64:
		result.SetString(strconv.Uitoa64(arg.(uint64)), 0)
	case string:
		result.SetString(arg.(string), 0)
	default:
		panic(fmt.Sprintf("Can not convert %T to Integer", arg))
	}
	return (*Integer)(&result)
}
Пример #19
0
func fetchStatusInMemcache(c appengine.Context, id uint64) (Status, os.Error) {
	key := "status" + strconv.Uitoa64(id)
	item, memErr := memcache.Get(c, key)
	if memErr != nil {
		c.Errorf("Error fetching item (%s)from memcache, %s", key, memErr)
		return Status{}, memErr
	}

	var data []byte = item.Value
	buffer := bytes.NewBuffer(data)
	dec := gob.NewDecoder(buffer)

	var status Status
	dec.Decode(&status)

	return status, nil
}
Пример #20
0
func (encoder *Encoder) encodeUint(value uint64) error {

	if value >= 0x20000000 {
		if value <= 0xffffffff {
			return encoder.encodeFloat(float64(value))
		}

		return encoder.encodeString(strconv.Uitoa64(value))
	}

	err := encoder.writeMarker(INTEGER_MARKER)
	if err != nil {
		return err
	}

	return encoder.writeU29(uint32(value))
}
func (r *resourceRequestProcessor) DoPost(req *http.Request) (int, map[string]string, []byte, os.Error) {
	path := req.URL.Path
	if !r.isPostablePath(path) {
		responseHeader := map[string]string{"Allow": r.getAllowHeader(req.URL.Path)}
		return http.StatusMethodNotAllowed, responseHeader, nil, nil
	}
	if !regexp.MustCompile("^application/json;?").MatchString(req.Header.Get("Content-Type")) {
		return http.StatusUnsupportedMediaType, nil, nil, nil
	}
	acceptHeader := req.Header.Get("Accept")
	if checkAcceptHeader("application/json", acceptHeader) == 0 {
		return http.StatusNotAcceptable, nil, nil, nil
	}
	requestBody, tooLarge, err := r.getRequestBody(req)
	if err != nil {
		return http.StatusInternalServerError, nil, nil, err
	}
	if tooLarge {
		return http.StatusRequestEntityTooLarge, nil, nil, nil
	}
	obj := map[string]string{}
	if err := json.Unmarshal(requestBody, &obj); err != nil {
		return http.StatusBadRequest, nil, nil, err
	}
	newID, err := r.ResourceStorage.Create(path)
	if err != nil {
		return http.StatusInternalServerError, nil, nil, err
	}
	if newID == 0 {
		return http.StatusNotFound, nil, nil, nil
	}
	newPath := path + "/" + strconv.Uitoa64(newID)
	if err := r.ResourceStorage.Set(newPath, obj); err != nil {
		return http.StatusInternalServerError, nil, nil, err
	}
	responseContent, err := json.Marshal(obj)
	if err != nil {
		return http.StatusInternalServerError, nil, nil, err
	}
	responseHeader := map[string]string{
		"Content-Type": "application/xhtml+xml; charset=utf-8",
		"Location":     r.getScheme() + "://" + req.Host + newPath}
	return http.StatusCreated, responseHeader, responseContent, nil
}
Пример #22
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
}
Пример #23
0
func Pulse(node string, seqns <-chan uint64, s Setter, sleep int64) {
	logger := util.NewLogger("pulse")

	var err os.Error
	cas := store.Missing

	for {
		seqn := strconv.Uitoa64(<-seqns)
		if closed(seqns) {
			break
		}

		cas, err = s.Set("/doozer/info/"+node+"/applied", seqn, cas)
		if err != nil {
			logger.Println(err)
		}

		time.Sleep(sleep)
	}
}
Пример #24
0
func primitiveToString(v reflect.Value) string {

	switch v.Kind() {

	case reflect.Bool:
		if v.Bool() {
			return "1"
		}
		return "0"
	case reflect.Int:
		fallthrough
	case reflect.Int8:
		fallthrough
	case reflect.Int16:
		fallthrough
	case reflect.Int32:
		fallthrough
	case reflect.Int64:
		return strconv.Itoa64(v.Int())

	case reflect.Uint:
		fallthrough
	case reflect.Uint8:
		fallthrough
	case reflect.Uint16:
		fallthrough
	case reflect.Uint32:
		fallthrough
	case reflect.Uint64:
		return strconv.Uitoa64(v.Uint())

	case reflect.Float32:
		fallthrough
	case reflect.Float64:
		return strconv.Ftoa64(v.Float(), 'g', 5)
	case reflect.String:
		return v.String()
	}

	return "(unknown type " + string(v.Kind()) + ")"
}
Пример #25
0
func (memc *Memcache) incdec(cmd string, key string, value uint64) (i uint64, err os.Error) {
	if memc == nil || memc.conn == nil {
		err = ConnectionError
		return
	}
	s := cmd + " " + key + " " + strconv.Uitoa64(value) + "\r\n"
	_, err = memc.conn.Write([]uint8(s))
	if err != nil {
		return
	}
	reader := bufio.NewReader(memc.conn)
	line, err := reader.ReadString('\n')
	if err != nil {
		return
	}
	if line == "NOT_FOUND\r\n" {
		err = NotFoundError
		return
	}
	i, err = strconv.Atoui64(strings.TrimSpace(line))
	return
}
Пример #26
0
func NewUser() string {
	usr := new(TalkUser)
	usr.c = make(chan string)
	usr.t = make(chan bool)
	usr.exit = false
	usr.salt = strconv.Itoa(rand.Int())

	go UserSocket(usr)
	go UserTimeout(usr)

	// INICIA CODIGO CRITICO
	currentUserIdx += 1

	myIdx := currentUserIdx
	// TERMINA CODIGO CRITICO

	talkUsers[myIdx] = usr

	// Join to the Global Channel
	JoinChannel(1, myIdx)

	return strconv.Uitoa64(myIdx) + "!" + usr.salt
}
Пример #27
0
func (c *ToSql) Convert(unknown interface{}) (s string) {
	switch val := unknown.(type) {
	case string:
		s = strconv.Quote(val)
	case bool:
		s = strconv.Btoa(val)
	case int:
		s = strconv.Itoa(val)
	case int64:
		s = strconv.Itoa64(val)
	case uint:
		s = strconv.Uitoa(val)
	case uint64:
		s = strconv.Uitoa64(val)
	case float32:
		s = strconv.Ftoa32(val, 'f', -1)
	case float64:
		s = strconv.Ftoa64(val, 'f', -1)
	default:
		s = c.ConvertUnknown(unknown)
	}
	return
}
Пример #28
0
func (e *encodeState) reflectValue(v reflect.Value) {
	if !v.IsValid() {
		e.WriteString("null")
		return
	}

	if j, ok := v.Interface().(Marshaler); ok {
		b, err := j.MarshalJSON()
		if err == nil {
			// copy JSON into buffer, checking validity.
			err = Compact(&e.Buffer, b)
		}
		if err != nil {
			e.error(&MarshalerError{v.Type(), err})
		}
		return
	}

	switch v.Kind() {
	case reflect.Bool:
		x := v.Bool()
		if x {
			e.WriteString("true")
		} else {
			e.WriteString("false")
		}

	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		e.WriteString(strconv.Itoa64(v.Int()))

	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
		e.WriteString(strconv.Uitoa64(v.Uint()))

	case reflect.Float32, reflect.Float64:
		e.WriteString(strconv.FtoaN(v.Float(), 'g', -1, v.Type().Bits()))

	case reflect.String:
		e.string(v.String())

	case reflect.Struct:
		e.WriteByte('{')
		t := v.Type()
		n := v.NumField()
		first := true
		for i := 0; i < n; i++ {
			f := t.Field(i)
			if f.PkgPath != "" {
				continue
			}
			if first {
				first = false
			} else {
				e.WriteByte(',')
			}
			if isValidTag(f.Tag) {
				e.string(f.Tag)
			} else {
				e.string(f.Name)
			}
			e.WriteByte(':')
			e.reflectValue(v.Field(i))
		}
		e.WriteByte('}')

	case reflect.Map:
		if v.Type().Key().Kind() != reflect.String {
			e.error(&UnsupportedTypeError{v.Type()})
		}
		if v.IsNil() {
			e.WriteString("null")
			break
		}
		e.WriteByte('{')
		var sv stringValues = v.MapKeys()
		sort.Sort(sv)
		for i, k := range sv {
			if i > 0 {
				e.WriteByte(',')
			}
			e.string(k.String())
			e.WriteByte(':')
			e.reflectValue(v.MapIndex(k))
		}
		e.WriteByte('}')

	case reflect.Array, reflect.Slice:
		if v.Type() == byteSliceType {
			e.WriteByte('"')
			s := v.Interface().([]byte)
			if len(s) < 1024 {
				// for small buffers, using Encode directly is much faster.
				dst := make([]byte, base64.StdEncoding.EncodedLen(len(s)))
				base64.StdEncoding.Encode(dst, s)
				e.Write(dst)
			} else {
				// for large buffers, avoid unnecessary extra temporary
				// buffer space.
				enc := base64.NewEncoder(base64.StdEncoding, e)
				enc.Write(s)
				enc.Close()
			}
			e.WriteByte('"')
			break
		}
		e.WriteByte('[')
		n := v.Len()
		for i := 0; i < n; i++ {
			if i > 0 {
				e.WriteByte(',')
			}
			e.reflectValue(v.Index(i))
		}
		e.WriteByte(']')

	case reflect.Interface, reflect.Ptr:
		if v.IsNil() {
			e.WriteString("null")
			return
		}
		e.reflectValue(v.Elem())

	default:
		e.error(&UnsupportedTypeError{v.Type()})
	}
	return
}
Пример #29
0
func (p *printer) marshalValue(val reflect.Value, name string) os.Error {
	if !val.IsValid() {
		return nil
	}

	kind := val.Kind()
	typ := val.Type()

	// Try Marshaler
	if typ.NumMethod() > 0 {
		if marshaler, ok := val.Interface().(Marshaler); ok {
			bytes, err := marshaler.MarshalXML()
			if err != nil {
				return err
			}
			p.Write(bytes)
			return nil
		}
	}

	// Drill into pointers/interfaces
	if kind == reflect.Ptr || kind == reflect.Interface {
		if val.IsNil() {
			return nil
		}
		return p.marshalValue(val.Elem(), name)
	}

	// Slices and arrays iterate over the elements. They do not have an enclosing tag.
	if (kind == reflect.Slice || kind == reflect.Array) && typ.Elem().Kind() != reflect.Uint8 {
		for i, n := 0, val.Len(); i < n; i++ {
			if err := p.marshalValue(val.Index(i), name); err != nil {
				return err
			}
		}
		return nil
	}

	// Find XML name
	xmlns := ""
	if kind == reflect.Struct {
		if f, ok := typ.FieldByName("XMLName"); ok {
			if tag := f.Tag.Get("xml"); tag != "" {
				if i := strings.Index(tag, " "); i >= 0 {
					xmlns, name = tag[:i], tag[i+1:]
				} else {
					name = tag
				}
			} else if v, ok := val.FieldByIndex(f.Index).Interface().(Name); ok && v.Local != "" {
				xmlns, name = v.Space, v.Local
			}
		}
	}

	p.WriteByte('<')
	p.WriteString(name)

	// Attributes
	if kind == reflect.Struct {
		if len(xmlns) > 0 {
			p.WriteString(` xmlns="`)
			Escape(p, []byte(xmlns))
			p.WriteByte('"')
		}

		for i, n := 0, typ.NumField(); i < n; i++ {
			if f := typ.Field(i); f.PkgPath == "" && f.Tag.Get("xml") == "attr" {
				if f.Type.Kind() == reflect.String {
					if str := val.Field(i).String(); str != "" {
						p.WriteByte(' ')
						p.WriteString(strings.ToLower(f.Name))
						p.WriteString(`="`)
						Escape(p, []byte(str))
						p.WriteByte('"')
					}
				}
			}
		}
	}
	p.WriteByte('>')

	switch k := val.Kind(); k {
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		p.WriteString(strconv.Itoa64(val.Int()))
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
		p.WriteString(strconv.Uitoa64(val.Uint()))
	case reflect.Float32, reflect.Float64:
		p.WriteString(strconv.Ftoa64(val.Float(), 'g', -1))
	case reflect.String:
		Escape(p, []byte(val.String()))
	case reflect.Bool:
		p.WriteString(strconv.Btoa(val.Bool()))
	case reflect.Array:
		// will be [...]byte
		bytes := make([]byte, val.Len())
		for i := range bytes {
			bytes[i] = val.Index(i).Interface().(byte)
		}
		Escape(p, bytes)
	case reflect.Slice:
		// will be []byte
		bytes := val.Interface().([]byte)
		Escape(p, bytes)
	case reflect.Struct:
		s := parentStack{printer: p}
		for i, n := 0, val.NumField(); i < n; i++ {
			if f := typ.Field(i); f.Name != "XMLName" && f.PkgPath == "" {
				name := f.Name
				vf := val.Field(i)
				switch tag := f.Tag.Get("xml"); tag {
				case "":
					s.trim(nil)
				case "chardata":
					if tk := f.Type.Kind(); tk == reflect.String {
						Escape(p, []byte(vf.String()))
					} else if tk == reflect.Slice {
						if elem, ok := vf.Interface().([]byte); ok {
							Escape(p, elem)
						}
					}
					continue
				case "innerxml":
					iface := vf.Interface()
					switch raw := iface.(type) {
					case []byte:
						p.Write(raw)
						continue
					case string:
						p.WriteString(raw)
						continue
					}
				case "attr":
					continue
				default:
					parents := strings.Split(tag, ">")
					if len(parents) == 1 {
						parents, name = nil, tag
					} else {
						parents, name = parents[:len(parents)-1], parents[len(parents)-1]
						if parents[0] == "" {
							parents[0] = f.Name
						}
					}

					s.trim(parents)
					if !(vf.Kind() == reflect.Ptr || vf.Kind() == reflect.Interface) || !vf.IsNil() {
						s.push(parents[len(s.stack):])
					}
				}

				if err := p.marshalValue(vf, name); err != nil {
					return err
				}
			}
		}
		s.trim(nil)
	default:
		return &UnsupportedTypeError{typ}
	}

	p.WriteByte('<')
	p.WriteByte('/')
	p.WriteString(name)
	p.WriteByte('>')

	return nil
}
Пример #30
0
func (e *encodeState) reflectValue(v reflect.Value) {
	if v == nil {
		e.WriteString("null")
		return
	}

	if j, ok := v.Interface().(Marshaler); ok {
		b, err := j.MarshalXML()
		if err == nil {
			// copy XML into buffer, checking validity.
			err = Compact(&e.Buffer, b)
		}
		if err != nil {
			e.error(&MarshalerError{v.Type(), err})
		}
		return
	}

	switch v := v.(type) {
	case *reflect.BoolValue:
		x := v.Get()
		if x {
			e.WriteString("true")
		} else {
			e.WriteString("false")
		}

	case *reflect.IntValue:
		e.WriteString(strconv.Itoa64(v.Get()))

	case *reflect.UintValue:
		e.WriteString(strconv.Uitoa64(v.Get()))

	case *reflect.FloatValue:
		e.WriteString(strconv.FtoaN(v.Get(), 'g', -1, v.Type().Bits()))

	case *reflect.StringValue:
		e.WriteString(v.Get())

	case *reflect.StructValue:
		t := v.Type().(*reflect.StructType)
		e.openTag(t.Name())
		n := v.NumField()
		for i := 0; i < n; i++ {
			f := t.Field(i)
			if f.Tag != "" {
				e.openTag(f.Tag)
				e.reflectValue(v.Field(i))
				e.closeTag(f.Tag)
			} else {
				e.openTag(f.Name)
				e.reflectValue(v.Field(i))
				e.closeTag(f.Name)
			}
		}
		e.closeTag(t.Name())

	case *reflect.MapValue:
		if _, ok := v.Type().(*reflect.MapType).Key().(*reflect.StringType); !ok {
			e.error(&UnsupportedTypeError{v.Type()})
		}
		if v.IsNil() {
			e.WriteString("null")
			break
		}
		e.WriteByte('{')
		var sv stringValues = v.Keys()
		sort.Sort(sv)
		for i, k := range sv {
			if i > 0 {
				e.WriteByte(',')
			}
			e.string(k.(*reflect.StringValue).Get())
			e.WriteByte(':')
			e.reflectValue(v.Elem(k))
		}
		e.WriteByte('}')

	case reflect.ArrayOrSliceValue:
		e.WriteByte('[')
		n := v.Len()
		for i := 0; i < n; i++ {
			if i > 0 {
				e.WriteByte(',')
			}
			e.reflectValue(v.Elem(i))
		}
		e.WriteByte(']')

	case interfaceOrPtrValue:
		if v.IsNil() {
			e.WriteString("null")
			return
		}
		e.reflectValue(v.Elem())

	default:
		e.error(&UnsupportedTypeError{v.Type()})
	}
	return
}