Esempio n. 1
0
func encodeDefault(object interface{}) (buffer []byte, err error) {
	switch object.(type) {
	case bool:
		buffer = strconv.AppendBool(buffer, object.(bool))
	case int:
		buffer = strconv.AppendInt(buffer, int64(object.(int)), _NUMERIC_BASE)
	case int8:
		buffer = strconv.AppendInt(buffer, int64(object.(int8)), _NUMERIC_BASE)
	case int16:
		buffer = strconv.AppendInt(buffer, int64(object.(int16)), _NUMERIC_BASE)
	case int32:
		buffer = strconv.AppendInt(buffer, int64(object.(int32)), _NUMERIC_BASE)
	case int64:
		buffer = strconv.AppendInt(buffer, object.(int64), _NUMERIC_BASE)
	case uint:
		buffer = strconv.AppendUint(buffer, uint64(object.(uint)), _NUMERIC_BASE)
	case uint8:
		buffer = strconv.AppendUint(buffer, uint64(object.(uint8)), _NUMERIC_BASE)
	case uint16:
		buffer = strconv.AppendUint(buffer, uint64(object.(uint16)), _NUMERIC_BASE)
	case uint32:
		buffer = strconv.AppendUint(buffer, uint64(object.(uint32)), _NUMERIC_BASE)
	case uint64:
		buffer = strconv.AppendUint(buffer, object.(uint64), _NUMERIC_BASE)
	case string:
		buffer = []byte(object.(string))
	case []byte:
		buffer = object.([]byte)
	default:
		err = errors.New("Invalid object for default encode")
	}
	return
}
Esempio n. 2
0
func encode(parameterStatus *parameterStatus, x interface{}, pgtypOid oid.Oid) []byte {
	switch v := x.(type) {
	case int64:
		return strconv.AppendInt(nil, v, 10)
	case float64:
		return strconv.AppendFloat(nil, v, 'f', -1, 64)
	case []byte:
		if pgtypOid == oid.T_bytea {
			return encodeBytea(parameterStatus.serverVersion, v)
		}

		return v
	case string:
		if pgtypOid == oid.T_bytea {
			return encodeBytea(parameterStatus.serverVersion, []byte(v))
		}

		return []byte(v)
	case bool:
		return strconv.AppendBool(nil, v)
	case time.Time:
		return formatTs(v)

	default:
		errorf("encode: unknown type for %T", v)
	}

	panic("not reached")
}
Esempio n. 3
0
func appendField(b []byte, k string, v interface{}) []byte {
	b = append(b, []byte(escape.String(k))...)
	b = append(b, '=')

	// check popular types first
	switch v := v.(type) {
	case float64:
		b = strconv.AppendFloat(b, v, 'f', -1, 64)
	case int64:
		b = strconv.AppendInt(b, v, 10)
		b = append(b, 'i')
	case string:
		b = append(b, '"')
		b = append(b, []byte(EscapeStringField(v))...)
		b = append(b, '"')
	case bool:
		b = strconv.AppendBool(b, v)
	case int32:
		b = strconv.AppendInt(b, int64(v), 10)
		b = append(b, 'i')
	case int16:
		b = strconv.AppendInt(b, int64(v), 10)
		b = append(b, 'i')
	case int8:
		b = strconv.AppendInt(b, int64(v), 10)
		b = append(b, 'i')
	case int:
		b = strconv.AppendInt(b, int64(v), 10)
		b = append(b, 'i')
	case uint32:
		b = strconv.AppendInt(b, int64(v), 10)
		b = append(b, 'i')
	case uint16:
		b = strconv.AppendInt(b, int64(v), 10)
		b = append(b, 'i')
	case uint8:
		b = strconv.AppendInt(b, int64(v), 10)
		b = append(b, 'i')
	// TODO: 'uint' should be considered just as "dangerous" as a uint64,
	// perhaps the value should be checked and capped at MaxInt64? We could
	// then include uint64 as an accepted value
	case uint:
		b = strconv.AppendInt(b, int64(v), 10)
		b = append(b, 'i')
	case float32:
		b = strconv.AppendFloat(b, float64(v), 'f', -1, 32)
	case []byte:
		b = append(b, v...)
	case nil:
		// skip
	default:
		// Can't determine the type, so convert to string
		b = append(b, '"')
		b = append(b, []byte(EscapeStringField(fmt.Sprintf("%v", v)))...)
		b = append(b, '"')

	}

	return b
}
Esempio n. 4
0
// appendEncodedText encodes item in text format as required by COPY
// and appends to buf
func appendEncodedText(parameterStatus *parameterStatus, buf []byte, x interface{}) []byte {
	switch v := x.(type) {
	case int64:
		return strconv.AppendInt(buf, v, 10)
	case float32:
		return strconv.AppendFloat(buf, float64(v), 'f', -1, 32)
	case float64:
		return strconv.AppendFloat(buf, v, 'f', -1, 64)
	case []byte:
		encodedBytea := encodeBytea(parameterStatus.serverVersion, v)
		return appendEscapedText(buf, string(encodedBytea))
	case string:
		return appendEscapedText(buf, v)
	case bool:
		return strconv.AppendBool(buf, v)
	case time.Time:
		return append(buf, v.Format(time.RFC3339Nano)...)
	case nil:
		return append(buf, "\\N"...)
	default:
		errorf("encode: unknown type for %T", v)
	}

	panic("not reached")
}
Esempio n. 5
0
func ExampleAppendBool() {
	b := []byte("bool:")
	b = strconv.AppendBool(b, true)
	fmt.Println(string(b))

	// Output:
	// bool:true
}
Esempio n. 6
0
func AppendTest() {
	//Append 系列函数将整数等转换为字符串后,添加到现有的字节数组中。
	str := make([]byte, 0, 100)
	str = strconv.AppendInt(str, 4567, 10)
	str = strconv.AppendBool(str, false)
	str = strconv.AppendQuote(str, "abcdefg")
	str = strconv.AppendQuoteRune(str, '单')
	fmt.Println(string(str))
}
Esempio n. 7
0
func (b boolParser) String() string {
	w := []byte{}
	for i, t := range b {
		if i > 0 {
			w = append(w, ' ')
		}
		w = strconv.AppendBool(w, t)
	}
	return string(w)
}
Esempio n. 8
0
func bytesFromIf(v interface{}) (b []byte, err error) {
	switch v := v.(type) {
	case []byte:
		b = v
	case *[]byte:
		b = *v
	case string:
		b = []byte(v)
	case *string:
		b = []byte(*v)
	case int64:
		b = strconv.AppendInt(b, v, 10)
	case *int64:
		b = strconv.AppendInt(b, *v, 10)
	case int32:
		b = strconv.AppendInt(b, int64(v), 10)
	case *int32:
		b = strconv.AppendInt(b, int64(*v), 10)
	case int:
		b = strconv.AppendInt(b, int64(v), 10)
	case *int:
		b = strconv.AppendInt(b, int64(*v), 10)
	case float64:
		b = strconv.AppendFloat(b, v, 'f', -1, 64)
	case *float64:
		b = strconv.AppendFloat(b, *v, 'f', -1, 64)
	case float32:
		b = strconv.AppendFloat(b, float64(v), 'f', -1, 64)
	case *float32:
		b = strconv.AppendFloat(b, float64(*v), 'f', -1, 64)
	case bool:
		b = strconv.AppendBool(b, v)
	case *bool:
		b = strconv.AppendBool(b, *v)
	case fmt.Stringer:
		b = []byte(v.String())
	case Interfacer:
		b, err = bytesFromIf(v.Interface())
	default:
		return b, errors.New("[]byte value expected")
	}
	return
}
Esempio n. 9
0
File: value.go Progetto: zgiber/tree
func (v *Value) MarshalJSON() ([]byte, error) {
	b := []byte{}
	switch v.t {
	case BoolType:
		return strconv.AppendBool(b, *v.b), nil
	case FloatType:
		return strconv.AppendFloat(b, *v.f, 'f', -1, 64), nil
	case MapType:
		return json.Marshal(v.m)
	default:
		return nil, fmt.Errorf("unsupported Value type")
	}
}
Esempio n. 10
0
func Teststrings() {

	//字符串s中是否包含substr,返回bool值
	fmt.Println(strings.Contains("seafood", "foo"))
	fmt.Println(strings.Contains("seafood", "bar"))
	fmt.Println(strings.Contains("seafood", ""))
	fmt.Println(strings.Contains("", ""))
	s := []string{"foo", "bar", "baz"}

	//字符串链接,把slice a通过sep链接起来
	fmt.Println(strings.Join(s, ", "))

	//在字符串s中查找sep所在的位置,返回位置值,找不到返回-1
	fmt.Println(strings.Index("chicken", "ken"))
	fmt.Println(strings.Index("chicken", "dmr"))

	//重复s字符串count次,最后返回重复的字符串
	fmt.Println("ba" + strings.Repeat("na", 2))

	//在s字符串中,把old字符串替换为new字符串,n表示替换的次数,小于0表示全部替换
	fmt.Println(strings.Replace("oink oink oink", "k", "ky", 2))
	fmt.Println(strings.Replace("oink oink oink", "oink", "moo", -1))

	//把s字符串按照sep分割,返回slice
	fmt.Printf("%q\n", strings.Split("a,b,c", ","))
	fmt.Printf("%q\n", strings.Split("a man a plan a canal panama", "a "))
	fmt.Printf("%q\n", strings.Split(" xyz ", ""))
	fmt.Printf("%q\n", strings.Split("", "Bernardo O'Higgins"))

	//在s字符串中去除cutset指定的字符串
	fmt.Printf("[%q]\n", strings.Trim(" !!! Achtung !!! ", "! "))

	//去除s字符串的空格符,并且按照空格分割返回slice
	fmt.Printf("Fields are: %q\n", strings.Fields("  foo bar  baz   "))

	//Append 系列函数将整数等转换为字符串后,添加到现有的字节数组中。
	str := make([]byte, 0, 100)
	str = strconv.AppendInt(str, 4567, 10)
	str = strconv.AppendBool(str, false)
	str = strconv.AppendQuote(str, "abcdefg")
	str = strconv.AppendQuoteRune(str, '单')
	fmt.Println(string(str))
	//Format 系列函数把其他类型的转换为字符串
	a := strconv.FormatBool(false)
	b := strconv.FormatFloat(123.23, 'g', 12, 64)
	c := strconv.FormatInt(1234, 10)
	d := strconv.FormatUint(12345, 10)
	e := strconv.Itoa(1023)
	fmt.Println(a, b, c, d, e)

}
Esempio n. 11
0
func main() {
	var s []byte = make([]byte, 0)

	s = strconv.AppendBool(s, true)
	fmt.Println(string(s)) // true: true를 문자열로 변환하여 "true"

	s = strconv.AppendFloat(s, 1.3, 'f', -1, 32) // dst, f, fmt, prec, bitSize
	fmt.Println(string(s))                       // true1.3: 1.3을 문자열로 변환하여 "1.3", 슬라이스 뒤에 붙여서 true1.3

	s = strconv.AppendInt(s, -10, 10)
	fmt.Println(string(s)) // true1.3-10: -10을 10진수로된 문자열로 변환하여 "-10",
	// 슬라이스 뒤에 붙여서 true1.3-10

	s = strconv.AppendUint(s, 32, 16)
	fmt.Println(string(s)) // true1.3-1020: 32를 16진수로된 문자열로 변환하여 "20",
	// 슬라이스 뒤에 붙여서 true1.3-1020
}
Esempio n. 12
0
func main() {
	str := make([]byte, 0, 100)
	str = strconv.AppendInt(str, 4567, 10)
	str = strconv.AppendBool(str, false)
	str = strconv.AppendQuote(str, "adcdef")
	str = strconv.AppendQuoteRune(str, '中')
	fmt.Println(string(str))

	fl := strconv.FormatFloat(123.23, 'g', 12, 64)
	fmt.Println(fl)

	ui, err := strconv.ParseUint("12345", 10, 64)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(ui + 10)
}
Esempio n. 13
0
func asBytes(buf []byte, rv reflect.Value) (b []byte, ok bool) {
	switch rv.Kind() {
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return strconv.AppendInt(buf, rv.Int(), 10), true
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		return strconv.AppendUint(buf, rv.Uint(), 10), true
	case reflect.Float32:
		return strconv.AppendFloat(buf, rv.Float(), 'g', -1, 32), true
	case reflect.Float64:
		return strconv.AppendFloat(buf, rv.Float(), 'g', -1, 64), true
	case reflect.Bool:
		return strconv.AppendBool(buf, rv.Bool()), true
	case reflect.String:
		s := rv.String()
		return append(buf, s...), true
	}
	return
}
Esempio n. 14
0
func processString() {
	str := make([]byte, 0, 100)
	// str := ""
	fmt.Println(str)
	str = strconv.AppendInt(str, 4567, 10)
	str = strconv.AppendBool(str, false)
	str = strconv.AppendQuote(str, "abcde")
	str = strconv.AppendQuoteRune(str, '周')

	fmt.Println(str)
	fmt.Println(string(str))

	str1 := strconv.FormatBool(false)
	fmt.Println(str1)

	str1 = strings.Repeat(str1, 2)
	fmt.Println(str1)
	fmt.Println(strings.Contains(str1, "al"))
	fmt.Println(strings.Index(str1, "al"))
	fmt.Println(strings.Trim("!a     james  May       !a", "!a"))
}
Esempio n. 15
0
func main() {

	// Append , 转换并添加到现有字符串
	str := make([]byte, 0, 1000)

	str = strconv.AppendInt(str, 4567, 10)
	str = strconv.AppendBool(str, false)
	str = strconv.AppendQuote(str, "abcdefg")
	str = strconv.AppendQuoteRune(str, '单')

	fmt.Println(string(str))

	// Format 把其他类型转成字符串
	a := strconv.FormatBool(false)
	b := strconv.FormatFloat(123.23, 'g', 12, 64)
	c := strconv.FormatInt(1234, 10)
	d := strconv.FormatUint(12345, 10)
	e := strconv.Itoa(1023)

	fmt.Println(a, b, c, d, e)

	// Parse 把字符串转为其他类型

	a1, err := strconv.ParseBool("false")
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println(a1)
	}

	b1, err := strconv.ParseFloat("123.23", 64)

	c1, err := strconv.ParseInt("1234", 10, 64)

	d1, err := strconv.ParseUint("12345", 10, 64)

	fmt.Println(a1, b1, c1, d1)

}
Esempio n. 16
0
//Initializes the app by setting up logging file, defaults to stdout in case of error opening the specified file.
//Opens the DB connection
//Initialized DB with tables if -initdb=true option is passed when starting the app
func InitApp(logFileName string, initializeDB *bool) {
	var err error
	file, err = os.OpenFile(logFileName, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0666)
	if err != nil {
		fmt.Println("Log file cannot be opened")
		file.Close()
		file = os.Stdout
	}

	InitLogger(file, file, file, file, file)
	TRACE.Println("Logger initialized to file " + logFileName)

	dbConnection = GetDBConnection()
	TRACE.Println("Global connection object initialized")

	TRACE.Println(string(strconv.AppendBool([]byte("Application started with Init DB flag value "), *initializeDB)))

	if *initializeDB == true {
		TRACE.Println("DB Init Start")
		InitDB()
		TRACE.Println("DB Init Complete")
	}

	LoadAppPropertiesFromDb()

	dbLoggerPropertyValue, err := GetAppProperties("DbDebugLogs")

	if err == nil {
		dbLoggerFlag, err := strconv.ParseBool(dbLoggerPropertyValue)
		if err == nil && dbLoggerFlag {
			dbConnection.LogMode(dbLoggerFlag)
			dbConnection.SetLogger(DATABASE)
			TRACE.Println("Database logger initialized")
		}
	}

	StartScheduledJobs()
}
Esempio n. 17
0
File: data.go Progetto: nowk/beard
func (d *Data) Bytes() []byte {
	var b []byte
	switch t := d.Value.(type) {
	case string:
		return []byte(t)
	case int:
		return strconv.AppendInt(b, int64(t), 10)
	case int64:
		return strconv.AppendInt(b, t, 10)
	case float64:
		return strconv.AppendFloat(b, float64(t), 'G', -1, 64)
	case bool:
		return strconv.AppendBool(b, t)
	case []byte:
		return t
	case reflect.Value:
		return []byte(t.String())

	default:
		return []byte(fmt.Sprintf("%s", t))
	}

	return nil
}
Esempio n. 18
0
// appendEncodedText encodes item in text format as required by COPY
// and appends to buf
func appendEncodedText(buf []byte, x interface{}) []byte {
	switch v := x.(type) {
	case int64:
		return strconv.AppendInt(buf, v, 10)
	case float32:
		return strconv.AppendFloat(buf, float64(v), 'f', -1, 32)
	case float64:
		return strconv.AppendFloat(buf, v, 'f', -1, 64)
	case []byte:
		return append(buf, fmt.Sprintf("\\\\x%x", v)...)
	case string:
		return appendEscapedText(buf, v)
	case bool:
		return strconv.AppendBool(buf, v)
	case time.Time:
		return append(buf, v.Format(time.RFC3339Nano)...)
	case nil:
		return append(buf, "\\N"...)
	default:
		errorf("encode: unknown type for %T", v)
	}

	panic("not reached")
}
Esempio n. 19
0
func main() {

	// Go offers several printing "verbs" designed to
	// format general Go values. For example, this prints
	// an instance of our `point` struct.
	p := point{1, 2}
	fmt.Printf("%v\n", p)

	// If the value is a struct, the `%+v` variant will
	// include the struct's field names.
	fmt.Printf("%+v\n", p)

	// The `%#v` variant prints a Go syntax representation
	// of the value, i.e. the source code snippet that
	// would produce that value.
	fmt.Printf("%#v\n", p)

	// To print the type of a value, use `%T`.
	fmt.Printf("%T\n", p)

	// Formatting booleans is straight-forward.
	fmt.Printf("%t\n", true)

	// There are many options for formatting integers.
	// Use `%d` for standard, base-10 formatting.
	fmt.Printf("%d\n", 123)

	// This prints a binary representation.
	fmt.Printf("%b\n", 14)

	// This prints the character corresponding to the
	// given integer.
	fmt.Printf("%c\n", 33)

	// `%x` provides hex encoding.
	fmt.Printf("%x\n", 456)

	// There are also several formatting options for
	// floats. For basic decimal formatting use `%f`.
	fmt.Printf("%f\n", 78.9)

	// `%e` and `%E` format the float in (slightly
	// different versions of) scientific notation.
	fmt.Printf("%e\n", 123400000.0)
	fmt.Printf("%E\n", 123400000.0)

	// For basic string printing use `%s`.
	fmt.Printf("%s\n", "\"string\"")

	// To double-quote strings as in Go source, use `%q`.
	fmt.Printf("%q\n", "\"string\"")

	// As with integers seen earlier, `%x` renders
	// the string in base-16, with two output characters
	// per byte of input.
	fmt.Printf("%x\n", "hex this")

	// To print a representation of a pointer, use `%p`.
	fmt.Printf("%p\n", &p)

	// When formatting numbers you will often want to
	// control the width and precision of the resulting
	// figure. To specify the width of an integer, use a
	// number after the `%` in the verb. By default the
	// result will be right-justified and padded with
	// spaces.
	fmt.Printf("|%6d|%6d|\n", 12, 345)

	// You can also specify the width of printed floats,
	// though usually you'll also want to restrict the
	// decimal precision at the same time with the
	// width.precision syntax.
	fmt.Printf("|%6.2f|%6.2f|\n", 1.2, 3.45)

	// To left-justify, use the `-` flag.
	fmt.Printf("|%-6.2f|%-6.2f|\n", 1.2, 3.45)

	// You may also want to control width when formatting
	// strings, especially to ensure that they align in
	// table-like output. For basic right-justified width.
	fmt.Printf("|%6s|%6s|\n", "foo", "b")

	// To left-justify use the `-` flag as with numbers.
	fmt.Printf("|%-6s|%-6s|\n", "foo", "b")

	// So far we've seen `Printf`, which prints the
	// formatted string to `os.Stdout`. `Sprintf` formats
	// and returns a string without printing it anywhere.
	s := fmt.Sprintf("a %s", "string")
	fmt.Println(s)

	// You can format+print to `io.Writers` other than
	// `os.Stdout` using `Fprintf`.
	fmt.Fprintf(os.Stderr, "an %s\n", "error")

	bs := []byte{}
	str := "this is a test!"
	c := len(str)
	bs = strconv.AppendInt(bs, int64(c), 10)
	bs = strconv.AppendQuote(bs, str)
	bs = strconv.AppendInt(bs, 123, 10)
	bs = strconv.AppendBool(bs, true)
	bs = strconv.AppendFloat(bs, 1.23, 'f', -1, 64)
	fmt.Println("string:", string(bs), " len:", len(bs))

	fmt.Println("bool: ", strconv.FormatBool(true))
	fmt.Println("2 int: ", strconv.FormatInt(123, 10))
	fmt.Println("36 int: ", strconv.FormatInt(123, 2))
	fmt.Println("2 uint: ", strconv.FormatUint(123, 10))
	fmt.Println("36 uint: ", strconv.FormatUint(123, 2))
	fmt.Println("float b: ", strconv.FormatFloat(1.230, 'b', -1, 64))
	fmt.Println("float E: ", strconv.FormatFloat(1.230, 'E', -1, 64))
	fmt.Println("float e: ", strconv.FormatFloat(1.230, 'e', -1, 64))
	fmt.Println("float f: ", strconv.FormatFloat(1.2301231, 'f', 6, 64))
	fmt.Println("float G: ", strconv.FormatFloat(1.23012321, 'G', 6, 64))
	fmt.Println("float g: ", strconv.FormatFloat(1.230123213, 'g', 6, 64))

	reader := strings.NewReader(str)
	b, _ := reader.ReadByte()
	fmt.Println(strconv.Atoi(string(b)))
}
Esempio n. 20
0
func main() {
	var i int
	fmt.Scanf("%d", &i)

	switch i {
	case 1:
		var num1 int
		var err error

		num1, err = strconv.Atoi("100")
		fmt.Println(num1, err)

		num1, err = strconv.Atoi("10t")
		fmt.Println(num1, err)

		var s string
		s = strconv.Itoa(100)
		fmt.Println(s)

		s = strconv.FormatBool(true)
		fmt.Println(s)

		s = strconv.FormatFloat(1.2, 'f', -1, 32)
		fmt.Println(s)

		s = strconv.FormatInt(-10, 10)
		fmt.Println(s)

		s = strconv.FormatUint(32, 16)
		fmt.Println(s)
	case 2:
		var s []byte = make([]byte, 0)
		s = strconv.AppendBool(s, true)
		fmt.Println(string(s))

		s = strconv.AppendFloat(s, 1.3, 'f', -1, 32)
		fmt.Println(string(s))

		s = strconv.AppendInt(s, -10, 10)
		fmt.Println(string(s))

		s = strconv.AppendUint(s, 32, 16)
		fmt.Println(string(s))
	case 3:
		var err1 error
		var b1 bool

		b1, err1 = strconv.ParseBool("true")
		fmt.Println(b1, err1)

		var num11 float64
		num11, err1 = strconv.ParseFloat("1.3", 64)
		fmt.Println(num11, err1)

		var num12 int64
		num12, err1 = strconv.ParseInt("-10", 10, 32)
		fmt.Println(num12, err1)

		var num13 uint64
		num13, err1 = strconv.ParseUint("20", 16, 32)
		fmt.Println(num13, err1)

	}

}
Esempio n. 21
0
func (p *printer) marshalStruct(tinfo *typeInfo, val reflect.Value) error {
	s := parentStack{p: p}
	for i := range tinfo.fields {
		finfo := &tinfo.fields[i]
		if finfo.flags&fAttr != 0 {
			continue
		}
		vf := finfo.value(val)

		// Dereference or skip nil pointer, interface values.
		switch vf.Kind() {
		case reflect.Ptr, reflect.Interface:
			if !vf.IsNil() {
				vf = vf.Elem()
			}
		}

		switch finfo.flags & fMode {
		case fCharData:
			if err := s.setParents(&noField, reflect.Value{}); err != nil {
				return err
			}
			if vf.CanInterface() && vf.Type().Implements(textMarshalerType) {
				data, err := vf.Interface().(encoding.TextMarshaler).MarshalText()
				if err != nil {
					return err
				}
				Escape(p, data)
				continue
			}
			if vf.CanAddr() {
				pv := vf.Addr()
				if pv.CanInterface() && pv.Type().Implements(textMarshalerType) {
					data, err := pv.Interface().(encoding.TextMarshaler).MarshalText()
					if err != nil {
						return err
					}
					Escape(p, data)
					continue
				}
			}
			var scratch [64]byte
			switch vf.Kind() {
			case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
				Escape(p, strconv.AppendInt(scratch[:0], vf.Int(), 10))
			case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
				Escape(p, strconv.AppendUint(scratch[:0], vf.Uint(), 10))
			case reflect.Float32, reflect.Float64:
				Escape(p, strconv.AppendFloat(scratch[:0], vf.Float(), 'g', -1, vf.Type().Bits()))
			case reflect.Bool:
				Escape(p, strconv.AppendBool(scratch[:0], vf.Bool()))
			case reflect.String:
				if err := EscapeText(p, []byte(vf.String())); err != nil {
					return err
				}
			case reflect.Slice:
				if elem, ok := vf.Interface().([]byte); ok {
					if err := EscapeText(p, elem); err != nil {
						return err
					}
				}
			}
			continue

		case fComment:
			if err := s.setParents(&noField, reflect.Value{}); err != nil {
				return err
			}
			k := vf.Kind()
			if !(k == reflect.String || k == reflect.Slice && vf.Type().Elem().Kind() == reflect.Uint8) {
				return fmt.Errorf("xml: bad type for comment field of %s", val.Type())
			}
			if vf.Len() == 0 {
				continue
			}
			p.writeIndent(0)
			p.WriteString("<!--")
			dashDash := false
			dashLast := false
			switch k {
			case reflect.String:
				s := vf.String()
				dashDash = strings.Index(s, "--") >= 0
				dashLast = s[len(s)-1] == '-'
				if !dashDash {
					p.WriteString(s)
				}
			case reflect.Slice:
				b := vf.Bytes()
				dashDash = bytes.Index(b, ddBytes) >= 0
				dashLast = b[len(b)-1] == '-'
				if !dashDash {
					p.Write(b)
				}
			default:
				panic("can't happen")
			}
			if dashDash {
				return fmt.Errorf(`xml: comments must not contain "--"`)
			}
			if dashLast {
				// "--->" is invalid grammar. Make it "- -->"
				p.WriteByte(' ')
			}
			p.WriteString("-->")
			continue

		case fInnerXml:
			iface := vf.Interface()
			switch raw := iface.(type) {
			case []byte:
				p.Write(raw)
				continue
			case string:
				p.WriteString(raw)
				continue
			}

		case fElement, fElement | fAny:
			if err := s.setParents(finfo, vf); err != nil {
				return err
			}
		}
		if err := p.marshalValue(vf, finfo, nil); err != nil {
			return err
		}
	}
	if err := s.setParents(&noField, reflect.Value{}); err != nil {
		return err
	}
	return p.cachedWriteError()
}
Esempio n. 22
0
func (bs Bytes) AppendBool(b bool) Bytes {
	r := strconv.AppendBool([]byte(bs), b)
	return Bytes(r)
}
Esempio n. 23
0
func prettyPrint(w *WorldDat, v reflect.Value, buf, indent []byte, outerTag reflect.StructTag) []byte {
	bufPreType := buf
	buf = append(buf, v.Kind().String()...)
	buf = append(buf, ' ')
	if v.Type().String() != v.Kind().String() {
		buf = append(buf, v.Type().String()...)
		buf = append(buf, ' ')
	}

	if p, ok := v.Interface().(prettyPrinter); ok {
		return p.prettyPrint(w, buf, indent, outerTag)
	}

	switch v.Kind() {
	case reflect.Ptr:
		if v.IsNil() {
			buf = append(buf, "(nil)"...)
		} else {
			buf = append(bufPreType, '&')
			buf = prettyPrint(w, v.Elem(), buf, indent, outerTag)
		}

	case reflect.Struct:
		buf = append(buf, '{')
		indent = append(indent, '\t')

		for i, l := 0, v.NumField(); i < l; i++ {
			fieldTag := v.Type().Field(i).Tag
			if tag := fieldTag.Get("df2014_version_min"); tag != "" {
				expected, err := strconv.ParseUint(tag, 0, 32)
				if err != nil {
					panic(err)
				}

				if w.Version < versions.Version(expected) {
					continue
				}
			}
			if tag := fieldTag.Get("df2014_version_max"); tag != "" {
				expected, err := strconv.ParseUint(tag, 0, 32)
				if err != nil {
					panic(err)
				}

				if w.Version > versions.Version(expected) {
					continue
				}
			}
			if tag := fieldTag.Get("df2014_type"); tag != "" {
				expected, err := strconv.ParseInt(tag, 0, 64)
				if err != nil {
					panic(err)
				}

				if v.FieldByName("Type").Int() != expected {
					continue
				}
			}
			buf = append(buf, indent...)
			buf = append(buf, v.Type().Field(i).Name...)
			buf = append(buf, ": "...)
			buf = prettyPrint(w, v.Field(i), buf, indent, fieldTag)
		}

		buf = append(buf, indent[:len(indent)-1]...)
		buf = append(buf, '}')

	case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		buf = strconv.AppendInt(buf, v.Int(), 10)
		buf = append(buf, " (0x"...)
		buf = strconv.AppendUint(buf, uint64(v.Int())&(1<<uint(v.Type().Bits())-1), 16)
		buf = append(buf, ')')

	case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		buf = strconv.AppendUint(buf, v.Uint(), 10)
		buf = append(buf, " (0x"...)
		buf = strconv.AppendUint(buf, v.Uint(), 16)
		buf = append(buf, ')')

	case reflect.String:
		buf = append(buf, "(len = "...)
		buf = strconv.AppendInt(buf, int64(len([]rune(v.String()))), 10)
		buf = append(buf, ") "...)
		buf = strconv.AppendQuote(buf, v.String())

	case reflect.Bool:
		buf = strconv.AppendBool(buf, v.Bool())

	case reflect.Slice, reflect.Array:
		if v.Kind() == reflect.Slice {
			buf = append(buf, "(len = "...)
			buf = strconv.AppendInt(buf, int64(v.Len()), 10)
			buf = append(buf, ") {"...)
		} else {
			buf = append(buf, '{')
		}
		indent = append(indent, '\t')

		var names []string
		if tag := outerTag.Get("df2014_key_is_string"); tag != "" {
			names = reflect.ValueOf(w.StringTables).FieldByName(tag).Interface().([]string)
		}
		for i, l := 0, v.Len(); i < l; i++ {
			buf = append(buf, indent...)
			buf = strconv.AppendInt(buf, int64(i), 10)
			if i >= 0 && int(i) < len(names) {
				buf = append(buf, " ("...)
				buf = append(buf, names[i]...)
				buf = append(buf, ')')
			}
			buf = append(buf, ": "...)
			buf = prettyPrint(w, v.Index(i), buf, indent, "")
		}

		buf = append(buf, indent[:len(indent)-1]...)
		buf = append(buf, '}')

	case reflect.Map:
		buf = append(buf, "(len = "...)
		buf = strconv.AppendInt(buf, int64(v.Len()), 10)
		buf = append(buf, ") {"...)
		indent = append(indent, '\t')

		var elements mapElements
		keys := v.MapKeys()
		for _, key := range keys {
			elements = append(elements, mapElement{key: key, value: v.MapIndex(key)})
		}

		sort.Sort(elements)

		for _, e := range elements {
			buf = append(buf, indent...)
			buf = prettyPrint(w, e.key, buf, indent, "")
			buf = append(buf, ": "...)
			buf = prettyPrint(w, e.value, buf, indent, "")
		}

		buf = append(buf, indent[:len(indent)-1]...)
		buf = append(buf, '}')

	default:
		panic("unhandled type: " + v.Kind().String() + " " + v.Type().String())
	}

	return buf
}
Esempio n. 24
0
func encodeBool(buf []byte, b bool) []byte {
	return strconv.AppendBool(buf, b)
}
Esempio n. 25
0
func (enc *textEncoder) AddBool(key string, val bool) {
	enc.addKey(key)
	enc.bytes = strconv.AppendBool(enc.bytes, val)
}
Esempio n. 26
0
func (c *Command) AddBool(b bool) *Command {
	*c = append(*c, strconv.AppendBool(nil, b))
	return c
}
Esempio n. 27
0
func (p *printer) marshalStruct(tinfo *typeInfo, val reflect.Value) error {
	s := parentStack{p: p}
	for i := range tinfo.fields {
		finfo := &tinfo.fields[i]
		if finfo.flags&fAttr != 0 {
			continue
		}
		vf := finfo.value(val)

		switch finfo.flags & fMode {
		case fCDATA, fCharData:
			emit := EscapeText
			if finfo.flags&fMode == fCDATA {
				emit = emitCDATA
			}
			if err := s.trim(finfo.parents); err != nil {
				return err
			}
			if vf.CanInterface() && vf.Type().Implements(textMarshalerType) {
				data, err := vf.Interface().(encoding.TextMarshaler).MarshalText()
				if err != nil {
					return err
				}
				if err := emit(p, data); err != nil {
					return err
				}
				continue
			}
			if vf.CanAddr() {
				pv := vf.Addr()
				if pv.CanInterface() && pv.Type().Implements(textMarshalerType) {
					data, err := pv.Interface().(encoding.TextMarshaler).MarshalText()
					if err != nil {
						return err
					}
					if err := emit(p, data); err != nil {
						return err
					}
					continue
				}
			}
			// Drill into interfaces and pointers.
			// This can turn into an infinite loop given a cyclic chain,
			// but it matches the Go 1 behavior.
			for vf.Kind() == reflect.Interface || vf.Kind() == reflect.Ptr {
				if vf.IsNil() {
					return nil
				}
				vf = vf.Elem()
			}

			var scratch [64]byte
			switch vf.Kind() {
			case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
				if err := emit(p, strconv.AppendInt(scratch[:0], vf.Int(), 10)); err != nil {
					return err
				}
			case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
				if err := emit(p, strconv.AppendUint(scratch[:0], vf.Uint(), 10)); err != nil {
					return err
				}
			case reflect.Float32, reflect.Float64:
				if err := emit(p, strconv.AppendFloat(scratch[:0], vf.Float(), 'g', -1, vf.Type().Bits())); err != nil {
					return err
				}
			case reflect.Bool:
				if err := emit(p, strconv.AppendBool(scratch[:0], vf.Bool())); err != nil {
					return err
				}
			case reflect.String:
				if err := emit(p, []byte(vf.String())); err != nil {
					return err
				}
			case reflect.Slice:
				if elem, ok := vf.Interface().([]byte); ok {
					if err := emit(p, elem); err != nil {
						return err
					}
				}
			}
			continue

		case fComment:
			if err := s.trim(finfo.parents); err != nil {
				return err
			}
			k := vf.Kind()
			if !(k == reflect.String || k == reflect.Slice && vf.Type().Elem().Kind() == reflect.Uint8) {
				return fmt.Errorf("xml: bad type for comment field of %s", val.Type())
			}
			if vf.Len() == 0 {
				continue
			}
			p.writeIndent(0)
			p.WriteString("<!--")
			dashDash := false
			dashLast := false
			switch k {
			case reflect.String:
				s := vf.String()
				dashDash = strings.Contains(s, "--")
				dashLast = s[len(s)-1] == '-'
				if !dashDash {
					p.WriteString(s)
				}
			case reflect.Slice:
				b := vf.Bytes()
				dashDash = bytes.Contains(b, ddBytes)
				dashLast = b[len(b)-1] == '-'
				if !dashDash {
					p.Write(b)
				}
			default:
				panic("can't happen")
			}
			if dashDash {
				return fmt.Errorf(`xml: comments must not contain "--"`)
			}
			if dashLast {
				// "--->" is invalid grammar. Make it "- -->"
				p.WriteByte(' ')
			}
			p.WriteString("-->")
			continue

		case fInnerXml:
			iface := vf.Interface()
			switch raw := iface.(type) {
			case []byte:
				p.Write(raw)
				continue
			case string:
				p.WriteString(raw)
				continue
			}

		case fElement, fElement | fAny:
			if err := s.trim(finfo.parents); err != nil {
				return err
			}
			if len(finfo.parents) > len(s.stack) {
				if vf.Kind() != reflect.Ptr && vf.Kind() != reflect.Interface || !vf.IsNil() {
					if err := s.push(finfo.parents[len(s.stack):]); err != nil {
						return err
					}
				}
			}
		}
		if err := p.marshalValue(vf, finfo, nil); err != nil {
			return err
		}
	}
	s.trim(nil)
	return p.cachedWriteError()
}
Esempio n. 28
0
func defaultFormatFunc(c *Console) Formatter {

	var b []byte
	var file string
	var lvl string
	var i int

	gopath := c.GOPATH()
	tsFormat := c.TimestampFormat()
	fnameDisplay := c.FilenameDisplay()

	if c.DisplayColor() {

		var color ansi.EscSeq

		return func(e *log.Entry) []byte {
			b = b[0:0]
			color = c.GetDisplayColor(e.Level)

			if e.Line == 0 {

				b = append(b, e.Timestamp.Format(tsFormat)...)
				b = append(b, space)
				b = append(b, color...)

				lvl = e.Level.String()

				for i = 0; i < 6-len(lvl); i++ {
					b = append(b, space)
				}
				b = append(b, lvl...)
				b = append(b, ansi.Reset...)
				b = append(b, space)
				b = append(b, e.Message...)

			} else {
				file = e.File

				if fnameDisplay == log.Lshortfile {

					for i = len(file) - 1; i > 0; i-- {
						if file[i] == '/' {
							file = file[i+1:]
							break
						}
					}
				} else {
					file = file[len(gopath):]
				}

				b = append(b, e.Timestamp.Format(tsFormat)...)
				b = append(b, space)
				b = append(b, color...)

				lvl = e.Level.String()

				for i = 0; i < 6-len(lvl); i++ {
					b = append(b, space)
				}

				b = append(b, lvl...)
				b = append(b, ansi.Reset...)
				b = append(b, space)
				b = append(b, file...)
				b = append(b, colon)
				b = strconv.AppendInt(b, int64(e.Line), base10)
				b = append(b, space)
				b = append(b, e.Message...)
			}

			for _, f := range e.Fields {
				b = append(b, space)
				b = append(b, color...)
				b = append(b, f.Key...)
				b = append(b, ansi.Reset...)
				b = append(b, equals)

				switch f.Value.(type) {
				case string:
					b = append(b, f.Value.(string)...)
				case int:
					b = strconv.AppendInt(b, int64(f.Value.(int)), base10)
				case int8:
					b = strconv.AppendInt(b, int64(f.Value.(int8)), base10)
				case int16:
					b = strconv.AppendInt(b, int64(f.Value.(int16)), base10)
				case int32:
					b = strconv.AppendInt(b, int64(f.Value.(int32)), base10)
				case int64:
					b = strconv.AppendInt(b, f.Value.(int64), base10)
				case uint:
					b = strconv.AppendUint(b, uint64(f.Value.(uint)), base10)
				case uint8:
					b = strconv.AppendUint(b, uint64(f.Value.(uint8)), base10)
				case uint16:
					b = strconv.AppendUint(b, uint64(f.Value.(uint16)), base10)
				case uint32:
					b = strconv.AppendUint(b, uint64(f.Value.(uint32)), base10)
				case uint64:
					b = strconv.AppendUint(b, f.Value.(uint64), base10)
				case bool:
					b = strconv.AppendBool(b, f.Value.(bool))
				default:
					b = append(b, fmt.Sprintf(v, f.Value)...)
				}
			}

			b = append(b, newLine)

			return b
		}
	}

	return func(e *log.Entry) []byte {
		b = b[0:0]

		if e.Line == 0 {

			b = append(b, e.Timestamp.Format(tsFormat)...)
			b = append(b, space)

			lvl = e.Level.String()

			for i = 0; i < 6-len(lvl); i++ {
				b = append(b, space)
			}

			b = append(b, lvl...)
			b = append(b, space)
			b = append(b, e.Message...)

		} else {
			file = e.File

			if fnameDisplay == log.Lshortfile {

				for i = len(file) - 1; i > 0; i-- {
					if file[i] == '/' {
						file = file[i+1:]
						break
					}
				}
			} else {

				// additional check, just in case user does
				// have a $GOPATH but code isn't under it.
				if strings.HasPrefix(file, gopath) {
					file = file[len(gopath):]
				}
			}

			b = append(b, e.Timestamp.Format(tsFormat)...)
			b = append(b, space)

			lvl = e.Level.String()

			for i = 0; i < 6-len(lvl); i++ {
				b = append(b, space)
			}

			b = append(b, lvl...)
			b = append(b, space)
			b = append(b, file...)
			b = append(b, colon)
			b = strconv.AppendInt(b, int64(e.Line), base10)
			b = append(b, space)
			b = append(b, e.Message...)
		}

		for _, f := range e.Fields {
			b = append(b, space)
			b = append(b, f.Key...)
			b = append(b, equals)

			switch f.Value.(type) {
			case string:
				b = append(b, f.Value.(string)...)
			case int:
				b = strconv.AppendInt(b, int64(f.Value.(int)), base10)
			case int8:
				b = strconv.AppendInt(b, int64(f.Value.(int8)), base10)
			case int16:
				b = strconv.AppendInt(b, int64(f.Value.(int16)), base10)
			case int32:
				b = strconv.AppendInt(b, int64(f.Value.(int32)), base10)
			case int64:
				b = strconv.AppendInt(b, f.Value.(int64), base10)
			case uint:
				b = strconv.AppendUint(b, uint64(f.Value.(uint)), base10)
			case uint8:
				b = strconv.AppendUint(b, uint64(f.Value.(uint8)), base10)
			case uint16:
				b = strconv.AppendUint(b, uint64(f.Value.(uint16)), base10)
			case uint32:
				b = strconv.AppendUint(b, uint64(f.Value.(uint32)), base10)
			case uint64:
				b = strconv.AppendUint(b, f.Value.(uint64), base10)
			case bool:
				b = strconv.AppendBool(b, f.Value.(bool))
			default:
				b = append(b, fmt.Sprintf(v, f.Value)...)
			}
		}

		b = append(b, newLine)

		return b
	}
}
Esempio n. 29
0
func (p *printer) marshalStruct(tinfo *typeInfo, val reflect.Value, nsctx *context) error {
	if val.Type() == timeType {
		_, err := p.WriteString(val.Interface().(time.Time).Format(time.RFC3339Nano))
		return err
	}
	s := parentStack{printer: p}
	for i := range tinfo.fields {
		finfo := &tinfo.fields[i]
		if finfo.flags&(fAttr) != 0 {
			continue
		}
		vf := finfo.value(val)
		switch finfo.flags & fMode {
		case fCharData:
			var scratch [64]byte
			switch vf.Kind() {
			case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
				Escape(p, strconv.AppendInt(scratch[:0], vf.Int(), 10))
			case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
				Escape(p, strconv.AppendUint(scratch[:0], vf.Uint(), 10))
			case reflect.Float32, reflect.Float64:
				Escape(p, strconv.AppendFloat(scratch[:0], vf.Float(), 'g', -1, vf.Type().Bits()))
			case reflect.Bool:
				Escape(p, strconv.AppendBool(scratch[:0], vf.Bool()))
			case reflect.String:
				Escape(p, []byte(vf.String()))
			case reflect.Slice:
				if elem, ok := vf.Interface().([]byte); ok {
					Escape(p, elem)
				}
			case reflect.Struct:
				if vf.Type() == timeType {
					Escape(p, []byte(vf.Interface().(time.Time).Format(time.RFC3339Nano)))
				}
			}
			continue

		case fComment:
			k := vf.Kind()
			if !(k == reflect.String || k == reflect.Slice && vf.Type().Elem().Kind() == reflect.Uint8) {
				return fmt.Errorf("xml: bad type for comment field of %s", val.Type())
			}
			if vf.Len() == 0 {
				continue
			}
			p.writeIndent(0)
			p.WriteString("<!--")
			dashDash := false
			dashLast := false
			switch k {
			case reflect.String:
				s := vf.String()
				dashDash = strings.Index(s, "--") >= 0
				dashLast = s[len(s)-1] == '-'
				if !dashDash {
					p.WriteString(s)
				}
			case reflect.Slice:
				b := vf.Bytes()
				dashDash = bytes.Index(b, ddBytes) >= 0
				dashLast = b[len(b)-1] == '-'
				if !dashDash {
					p.Write(b)
				}
			default:
				panic("can't happen")
			}
			if dashDash {
				return fmt.Errorf(`xml: comments must not contain "--"`)
			}
			if dashLast {
				// "--->" is invalid grammar. Make it "- -->"
				p.WriteByte(' ')
			}
			p.WriteString("-->")
			continue

		case fInnerXml:
			iface := vf.Interface()
			switch raw := iface.(type) {
			case []byte:
				p.Write(raw)
				continue
			case string:
				p.WriteString(raw)
				continue
			}

		case fElement, fElement | fAny:
			s.trim(finfo.parents)
			if len(finfo.parents) > len(s.stack) {
				if vf.Kind() != reflect.Ptr && vf.Kind() != reflect.Interface || !vf.IsNil() {
					s.push(finfo.parents[len(s.stack):])
				}
			}
		}
		if err := p.marshalValue(vf, finfo, nsctx.child()); err != nil {
			return err
		}
	}
	s.trim(nil)
	return p.cachedWriteError()
}
Esempio n. 30
0
/*
参数列表

dst 表示原列表
b 表示需要添加的bool值,true或者false

返回值:
[]byte 返回原列表追加bool后新生成的列表

功能说明:
将布尔值 b 转换为字符串 "true" 或 "false" 然后将结果追加到 dst 的尾部,返回追加后的 []byte
*/
func main() {
	b := []byte("bool:")
	b = strconv.AppendBool(b, true)
	fmt.Println(string(b))
}