1
0
mirror of https://github.com/robertkrimen/otto synced 2025-10-12 20:27:30 +08:00
otto/type_string.go
Robert Krimen c55510cb36 Inline context initialization & improve _object.value
* Context setup is now done via _newContext.
* _newContext is a function that resides in inline.go. _newContext is very flat,
resulting in almost no function calls (a 180 from the earlier status quo).
* inline.go is a Go source file that is built by Perl (via inline).
* Lots of crufty functions removed (along with all of their TODO & FIXME).
* In addition, before, the underlying value of _object.value was a pointer to
something. This made for extra work, since the type of _object.value is interface{},
which is already something of a pointer. Now, the underlying value of _object.value
in Function, Date, RegExp, ..., is a struct value.
* type_function.go was streamlined, removing superfluous struct fields and methods.
* There is now less "digging" to get to the actual value of a function, which is important
when makings lots of calls.

Before (without inline):

    PASS
    BenchmarkNew        2000           1067871 ns/op
    ok      github.com/robertkrimen/otto    3.336s
    PASS
    BenchmarkNew        2000           1077644 ns/op
    ok      github.com/robertkrimen/otto    3.367s

After (with inline):

    PASS
    BenchmarkNew       10000            364418 ns/op
    ok      github.com/robertkrimen/otto    4.616s
    PASS
    BenchmarkNew       10000            307241 ns/op
    ok      github.com/robertkrimen/otto    4.051s

This (partially) fixes #22
2013-06-09 18:28:18 -07:00

65 lines
1.4 KiB
Go

package otto
import (
"strconv"
"unicode/utf16"
)
type _stringObject struct {
value Value
value16 []uint16
}
func (runtime *_runtime) newStringObject(value Value) *_object {
value = toValue(toString(value))
value16 := utf16Of(value.value.(string))
self := runtime.newClassObject("String")
self.defineProperty("length", toValue(len(value16)), 0, false)
self.objectClass = _classString
self.value = _stringObject{
value: value,
value16: value16,
}
return self
}
func (self *_object) stringValue() (string, _stringObject) {
value, valid := self.value.(_stringObject)
if valid {
return value.value.value.(string), value
}
return "", _stringObject{}
}
func (self *_object) stringValue16() []uint16 {
_, value := self.stringValue()
return value.value16
}
func utf16Of(value string) []uint16 {
return utf16.Encode([]rune(value))
}
func stringEnumerate(self *_object, all bool, each func(string)) {
length := len(self.stringValue16())
for index := 0; index < length; index += 1 {
each(strconv.FormatInt(int64(index), 10))
}
objectEnumerate(self, all, each)
}
func stringGetOwnProperty(self *_object, name string) *_property {
if property := objectGetOwnProperty(self, name); property != nil {
return property
}
index := stringToArrayIndex(name)
if index >= 0 {
value16 := self.stringValue16()
if index < int64(len(value16)) {
return &_property{toValue(string(value16[index])), 0}
}
}
return nil
}