xgo/stdlib/fmt.go

102 lines
2.2 KiB
Go
Raw Normal View History

package stdlib
2019-01-09 10:17:42 +03:00
import (
"fmt"
2019-12-30 00:38:51 +03:00
"github.com/d5/tengo/v2"
2019-01-09 10:17:42 +03:00
)
2019-12-20 22:40:38 +03:00
var fmtModule = map[string]tengo.Object{
"print": &tengo.UserFunction{Name: "print", Value: fmtPrint},
"printf": &tengo.UserFunction{Name: "printf", Value: fmtPrintf},
"println": &tengo.UserFunction{Name: "println", Value: fmtPrintln},
"sprintf": &tengo.UserFunction{Name: "sprintf", Value: fmtSprintf},
}
2019-12-20 22:40:38 +03:00
func fmtPrint(args ...tengo.Object) (ret tengo.Object, err error) {
printArgs, err := getPrintArgs(args...)
if err != nil {
return nil, err
}
_, _ = fmt.Print(printArgs...)
return nil, nil
}
2019-12-20 22:40:38 +03:00
func fmtPrintf(args ...tengo.Object) (ret tengo.Object, err error) {
numArgs := len(args)
if numArgs == 0 {
2019-12-20 22:40:38 +03:00
return nil, tengo.ErrWrongNumArguments
}
2019-12-20 22:40:38 +03:00
format, ok := args[0].(*tengo.String)
if !ok {
2019-12-20 22:40:38 +03:00
return nil, tengo.ErrInvalidArgumentType{
Name: "format",
Expected: "string",
Found: args[0].TypeName(),
}
}
if numArgs == 1 {
fmt.Print(format)
return nil, nil
}
2019-12-20 22:40:38 +03:00
s, err := tengo.Format(format.Value, args[1:]...)
if err != nil {
return nil, err
}
fmt.Print(s)
return nil, nil
}
2019-12-20 22:40:38 +03:00
func fmtPrintln(args ...tengo.Object) (ret tengo.Object, err error) {
printArgs, err := getPrintArgs(args...)
if err != nil {
return nil, err
}
printArgs = append(printArgs, "\n")
_, _ = fmt.Print(printArgs...)
return nil, nil
}
2019-12-20 22:40:38 +03:00
func fmtSprintf(args ...tengo.Object) (ret tengo.Object, err error) {
numArgs := len(args)
if numArgs == 0 {
2019-12-20 22:40:38 +03:00
return nil, tengo.ErrWrongNumArguments
}
2019-12-20 22:40:38 +03:00
format, ok := args[0].(*tengo.String)
if !ok {
2019-12-20 22:40:38 +03:00
return nil, tengo.ErrInvalidArgumentType{
Name: "format",
Expected: "string",
Found: args[0].TypeName(),
}
}
if numArgs == 1 {
2019-12-20 22:40:38 +03:00
// okay to return 'format' directly as String is immutable
return format, nil
}
2019-12-20 22:40:38 +03:00
s, err := tengo.Format(format.Value, args[1:]...)
if err != nil {
return nil, err
}
2019-12-20 22:40:38 +03:00
return &tengo.String{Value: s}, nil
}
2019-12-20 22:40:38 +03:00
func getPrintArgs(args ...tengo.Object) ([]interface{}, error) {
var printArgs []interface{}
l := 0
for _, arg := range args {
2019-12-20 22:40:38 +03:00
s, _ := tengo.ToString(arg)
slen := len(s)
2019-12-20 22:40:38 +03:00
// make sure length does not exceed the limit
if l+slen > tengo.MaxStringLen {
return nil, tengo.ErrStringLimit
}
l += slen
printArgs = append(printArgs, s)
}
return printArgs, nil
}