Make *Context a writer and remove Output method

This commit is contained in:
Brandon Dyck 2022-11-27 15:45:18 -07:00
parent d7cc40e5dd
commit b285c354d5
2 changed files with 29 additions and 7 deletions

16
ph7.go
View File

@ -200,16 +200,18 @@ func (c *Context) ResultValue(value *Value) error {
// TODO (*Context).ResultResource // TODO (*Context).ResultResource
func (c *Context) Output(s string) error { func (c *Context) Write(p []byte) (int, error) {
// TODO Replace this with Write([]byte) (int, bool). cp := C.CBytes(p)
cs := C.CString(s) defer C.free(cp)
defer C.free(unsafe.Pointer(cs)) err := newError(C.ph7_context_output((*C.ph7_context)(c), (*C.char)(cp), C.int(len(p))))
if err != nil {
return newError(C.ph7_context_output((*C.ph7_context)(c), cs, C.int(len(s)))) return 0, err
}
return len(p), nil
} }
// TODO (*Context).OutputFormat maybe?
// TODO (*Context).ThrowError // TODO (*Context).ThrowError
// TODO (*Context).ThrowErrorFormat maybe?
func (c *Context) RandomNum() uint { func (c *Context) RandomNum() uint {
return uint(C.ph7_context_random_num((*C.ph7_context)(c))) return uint(C.ph7_context_random_num((*C.ph7_context)(c)))

View File

@ -158,6 +158,26 @@ func testResultCode(t *testing.T, expectedOutput string, f CtxFunc) {
expectOutput(t, vm, expectedOutput) expectOutput(t, vm, expectedOutput)
} }
func TestContextWrite(t *testing.T) {
const script = "echo doStuff();"
vm, close := setupVM(t, script)
defer close()
const s = "aoeu htns"
var written int
f := func(ctx *ph7.Context) error {
var err error
written, err = ctx.Write([]byte(s))
return err
}
mustSucceed(t, vm.CreateFunction("doStuff", CtxFunc(f)))
expectOutput(t, vm, s)
if written != len(s) {
t.Fatalf("wrote wrong number of bytes: expected %d, got %d", len(s), written)
}
}
func TestContextResultInt(t *testing.T) { func TestContextResultInt(t *testing.T) {
testResultCode(t, "42", func(ctx *ph7.Context) error { testResultCode(t, "42", func(ctx *ph7.Context) error {
return ctx.ResultInt(42) return ctx.ResultInt(42)