diff --git a/ph7.go b/ph7.go index 9f55559..e987e5e 100644 --- a/ph7.go +++ b/ph7.go @@ -200,16 +200,18 @@ func (c *Context) ResultValue(value *Value) error { // TODO (*Context).ResultResource -func (c *Context) Output(s string) error { - // TODO Replace this with Write([]byte) (int, bool). - cs := C.CString(s) - defer C.free(unsafe.Pointer(cs)) - - return newError(C.ph7_context_output((*C.ph7_context)(c), cs, C.int(len(s)))) +func (c *Context) Write(p []byte) (int, error) { + cp := C.CBytes(p) + defer C.free(cp) + err := newError(C.ph7_context_output((*C.ph7_context)(c), (*C.char)(cp), C.int(len(p)))) + if err != nil { + return 0, err + } + return len(p), nil } -// TODO (*Context).OutputFormat maybe? // TODO (*Context).ThrowError +// TODO (*Context).ThrowErrorFormat maybe? func (c *Context) RandomNum() uint { return uint(C.ph7_context_random_num((*C.ph7_context)(c))) diff --git a/ph7_test.go b/ph7_test.go index acdb7f3..028cc37 100644 --- a/ph7_test.go +++ b/ph7_test.go @@ -158,6 +158,26 @@ func testResultCode(t *testing.T, expectedOutput string, f CtxFunc) { 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) { testResultCode(t, "42", func(ctx *ph7.Context) error { return ctx.ResultInt(42)