Globally renamed ios to swift as we migrated the package name

Change-Id: I0942931bdd403a3d34b4b49040f472110b054129
diff --git a/impl/google/rpc/swift.go b/impl/google/rpc/swift.go
new file mode 100644
index 0000000..6b5cd8f
--- /dev/null
+++ b/impl/google/rpc/swift.go
@@ -0,0 +1,183 @@
+// Copyright 2015 The Vanadium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// +build darwin,ios
+
+package rpc
+
+import (
+	"reflect"
+	"unsafe"
+
+	"v.io/v23"
+	"v.io/v23/context"
+	"v.io/v23/options"
+	"v.io/v23/rpc"
+	"v.io/v23/security"
+	"v.io/v23/vdl"
+	"v.io/v23/vom"
+
+	sutil "v.io/x/swift/util"
+	scontext "v.io/x/swift/v23/context"
+)
+
+/*
+#include <string.h> // memcpy
+#import "../../../types.h"
+// These sizes (including C struct memory alignment/padding) isn't available from Go, so we make that available via CGo.
+static const size_t sizeofSwiftByteArray = sizeof(SwiftByteArray);
+static const size_t sizeofSwiftByteArrayArray = sizeof(SwiftByteArrayArray);
+*/
+import "C"
+
+func doStartCall(context *context.T, name, method string, skipServerAuth bool, client rpc.Client, args []interface{}) (rpc.ClientCall, error) {
+	var opts []rpc.CallOpt
+	if skipServerAuth {
+		opts = append(opts,
+			options.NameResolutionAuthorizer{security.AllowEveryone()},
+			options.ServerAuthorizer{security.AllowEveryone()})
+	}
+	// Invoke StartCall
+	call, err := client.StartCall(context, name, method, args, opts...)
+	if err != nil {
+		return nil, err
+	}
+	return call, nil
+}
+
+// TODO From JNI, implement this for Swift
+//func decodeArgs(cVomArgs C.SwiftByteArrayArray) ([]interface{}, error) {
+//	if (cVomArgs == nil || cVomArgs.length == 0) {
+//		return make([]interface{}, 0), nil
+//	}
+//	// VOM-decode each arguments into a *vdl.Value.
+//	args := make([]interface{}, cVomArgs.length)
+//	for i := 0; i < cVomArgs.length; i++ {
+//		ret[i] = byte(*ptr)
+//		ptr = (*C.jbyte)(unsafe.Pointer(uintptr(unsafe.Pointer(ptr)) + unsafe.Sizeof(*ptr)))
+//
+//		cVomArgs
+//
+//		var err error
+//		if args[i], err = jutil.VomDecodeToValue(vomArgs[i]); err != nil {
+//			return nil, err
+//		}
+//	}
+//	return args, nil
+//}
+
+//export swift_io_v_impl_google_rpc_ClientImpl_nativeStartCallAsync
+func swift_io_v_impl_google_rpc_ClientImpl_nativeStartCallAsync(ctxHandle C.GoContextHandle, cName *C.char, cMethod *C.char, cVomArgs C.SwiftByteArrayArray, skipServerAuth bool, asyncId C.AsyncCallbackIdentifier, successCallback C.SwiftAsyncSuccessHandleCallback, failureCallback C.SwiftAsyncFailureCallback) {
+	name := C.GoString(cName)
+	method := C.GoString(cMethod)
+	ctx := scontext.GoContext(uint64(ctxHandle))
+	client := v23.GetClient(ctx)
+
+	// TODO Get args (we don't have VOM yet in Swift so nothing to get until then)
+	//	args, err := decodeArgs(env, jVomArgs)
+	//	if err != nil {
+	//		sutil.ThrowSwiftError(ctx, err, unsafe.Pointer(errOut))
+	//		return C.GoClientCallHandle(0)
+	//	}
+	args := make([]interface{}, 0)
+
+	go func() {
+		result, err := doStartCall(ctx, name, method, skipServerAuth == true, client, args)
+		if err != nil {
+			var swiftVError C.SwiftVError
+			sutil.ThrowSwiftError(ctx, err, unsafe.Pointer(&swiftVError))
+			sutil.DoFailureCallback(unsafe.Pointer(failureCallback), int32(asyncId), unsafe.Pointer(&swiftVError))
+		} else {
+			handle := C.GoClientCallHandle(SwiftClientCall(result))
+			sutil.DoSuccessHandlerCallback(unsafe.Pointer(successCallback), int32(asyncId), uint64(handle))
+		}
+	}()
+}
+
+//export swift_io_v_impl_google_rpc_ClientImpl_nativeClose
+func swift_io_v_impl_google_rpc_ClientImpl_nativeClose(ctxHandle C.GoContextHandle) {
+	ctx := scontext.GoContext(uint64(ctxHandle))
+	client := v23.GetClient(ctx)
+	<-client.Closed()
+}
+
+//export swift_io_v_impl_google_rpc_ClientCallImpl_nativeCloseSend
+func swift_io_v_impl_google_rpc_ClientCallImpl_nativeCloseSend(ctxHandle C.GoContextHandle, callHandle C.GoClientCallHandle, errOut *C.SwiftVError) {
+	ctx := scontext.GoContext(uint64(ctxHandle))
+	call := GoClientCall(uint64(callHandle))
+	if err := call.CloseSend(); err != nil {
+		sutil.ThrowSwiftError(ctx, err, unsafe.Pointer(errOut))
+		return
+	}
+}
+
+func doFinish(call rpc.ClientCall, numResults int) (C.SwiftByteArrayArray, error) {
+	// Have all the results be decoded into *vdl.Value.
+	resultPtrs := make([]interface{}, numResults)
+	for i := 0; i < numResults; i++ {
+		value := new(vdl.Value)
+		resultPtrs[i] = &value
+	}
+	if err := call.Finish(resultPtrs...); err != nil {
+		// Invocation error.
+		return EmptySwiftByteArrayArray(), err
+	}
+
+	// VOM-encode the results. Note in the future we'll want a pathway where we can get the original VOM results
+	// from finish so we don't end up wasting CPU & memory here.
+
+	// Prepare the byte array array that can be accessed from Swift via C.malloc
+	vomResultsMemory := C.malloc(C.size_t(numResults * int(C.sizeofSwiftByteArray)))
+	// Make that malloc'd memory available as a slice to Go.
+	vomResultsPtrsHdr := reflect.SliceHeader{
+		Data: uintptr(vomResultsMemory),
+		Len:  numResults,
+		Cap:  numResults,
+	}
+	vomResults := *(*[]C.SwiftByteArray)(unsafe.Pointer(&vomResultsPtrsHdr))
+	// Create the C Struct to return that encapsulates our byte array array
+	var cVomResults C.SwiftByteArrayArray
+	cVomResults.length = C._GoUint64(numResults)
+	cVomResults.data = (*C.SwiftByteArray)(vomResultsMemory)
+
+	// For each result, VOM encode into a byte array that we stick into the returned struct
+	for i, resultPtr := range resultPtrs {
+		// Remove the pointer from the result.  Simply *resultPtr doesn't work
+		// as resultPtr is of type interface{}.
+		result := interface{}(sutil.DerefOrDie(resultPtr))
+		var vomResult []byte
+		var err error
+		if vomResult, err = vom.Encode(result); err != nil {
+			return EmptySwiftByteArrayArray(), err
+		}
+		cVomResultCopy := C.malloc(C.size_t(len(vomResult)))
+		C.memcpy(cVomResultCopy, unsafe.Pointer(&vomResult[0]), C.size_t(len(vomResult)))
+		var cVomResult C.SwiftByteArray
+		cVomResult.length = C._GoUint64(len(vomResult))
+		cVomResult.data = (*C.char)(cVomResultCopy)
+		vomResults[i] = cVomResult
+	}
+	return cVomResults, nil
+}
+
+//export swift_io_v_impl_google_rpc_ClientCallImpl_nativeFinishAsync
+func swift_io_v_impl_google_rpc_ClientCallImpl_nativeFinishAsync(ctxHandle C.GoContextHandle, callHandle C.GoClientCallHandle, numResults int, asyncId C.AsyncCallbackIdentifier, successCallback C.SwiftAsyncSuccessByteArrayArrayCallback, failureCallback C.SwiftAsyncFailureCallback) {
+	ctx := scontext.GoContext(uint64(ctxHandle))
+	call := GoClientCall(uint64(callHandle))
+	go func() {
+		result, err := doFinish(call, numResults)
+		if err != nil {
+			var swiftVError C.SwiftVError
+			sutil.ThrowSwiftError(ctx, err, unsafe.Pointer(&swiftVError))
+			sutil.DoFailureCallback(unsafe.Pointer(failureCallback), int32(asyncId), unsafe.Pointer(&swiftVError))
+		} else {
+			sutil.DoSuccessByteArrayArrayCallback(unsafe.Pointer(successCallback), int32(asyncId), unsafe.Pointer(&result))
+		}
+	}()
+}
+
+//export swift_io_v_impl_google_rpc_ClientCallImpl_nativeFinalize
+func swift_io_v_impl_google_rpc_ClientCallImpl_nativeFinalize(callHandle C.GoClientCallHandle) {
+	sutil.GoUnref(uint64(callHandle))
+}
diff --git a/impl/google/rpc/util.go b/impl/google/rpc/util.go
new file mode 100644
index 0000000..4261074
--- /dev/null
+++ b/impl/google/rpc/util.go
@@ -0,0 +1,38 @@
+// Copyright 2015 The Vanadium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// +build darwin,ios
+
+package rpc
+
+import (
+	"fmt"
+
+	"v.io/v23/rpc"
+
+	sutil "v.io/x/swift/util"
+)
+
+// #include "../../../types.h"
+import "C"
+
+func SwiftClientCall(call rpc.ClientCall) C.GoClientCallHandle {
+	return C.GoClientCallHandle(sutil.GoNewRef(call))
+}
+
+func GoClientCall(callHandle uint64) rpc.ClientCall {
+	valptr := sutil.GoGetRef(callHandle)
+	if call, ok := valptr.(rpc.ClientCall); ok {
+		return call
+	} else {
+		panic(fmt.Sprintf("Couldn't get client call from handle with id %d", callHandle))
+	}
+}
+
+func EmptySwiftByteArrayArray() C.SwiftByteArrayArray {
+	var empty C.SwiftByteArrayArray
+	empty.length = 0
+	empty.data = nil
+	return empty
+}
diff --git a/impl/google/rt/swift.go b/impl/google/rt/swift.go
new file mode 100644
index 0000000..4dc57dc
--- /dev/null
+++ b/impl/google/rt/swift.go
@@ -0,0 +1,52 @@
+// Copyright 2015 The Vanadium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// +build darwin,ios
+
+package rt
+
+import (
+	"unsafe"
+
+	"v.io/v23"
+	"v.io/v23/context"
+
+	sutil "v.io/x/swift/util"
+	scontext "v.io/x/swift/v23/context"
+)
+
+// #import "../../../types.h"
+import "C"
+
+type shutdownKey struct{}
+
+//export swift_io_v_impl_google_rt_VRuntimeImpl_nativeInit
+func swift_io_v_impl_google_rt_VRuntimeImpl_nativeInit() C.GoContextHandle {
+	ctx, shutdownFunc := v23.Init()
+	ctx = context.WithValue(ctx, shutdownKey{}, shutdownFunc)
+	return C.GoContextHandle(scontext.SwiftContext(ctx))
+}
+
+//export swift_io_v_impl_google_rt_VRuntimeImpl_nativeShutdown
+func swift_io_v_impl_google_rt_VRuntimeImpl_nativeShutdown(ctxHandle C.GoContextHandle) {
+	ctx := scontext.GoContext(uint64(ctxHandle))
+	value := ctx.Value(shutdownKey{})
+
+	if shutdownFunc, ok := value.(v23.Shutdown); ok {
+		shutdownFunc()
+	}
+}
+
+//export swift_io_v_impl_google_rt_VRuntimeImpl_nativeWithNewClient
+func swift_io_v_impl_google_rt_VRuntimeImpl_nativeWithNewClient(ctxHandle C.GoContextHandle, errOut *C.SwiftVError) C.GoContextHandle {
+	ctx := scontext.GoContext(uint64(ctxHandle))
+	// No options supported yet.
+	newCtx, _, err := v23.WithNewClient(ctx)
+	if err != nil {
+		sutil.ThrowSwiftError(ctx, err, unsafe.Pointer(errOut))
+		return C.GoContextHandle(0)
+	}
+
+	return C.GoContextHandle(scontext.SwiftContext(newCtx))
+}
diff --git a/impl/google/swift.go b/impl/google/swift.go
new file mode 100644
index 0000000..d028886
--- /dev/null
+++ b/impl/google/swift.go
@@ -0,0 +1,17 @@
+// Copyright 2015 The Vanadium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// +build darwin,ios
+
+package google
+
+import (
+	_ "v.io/x/swift/impl/google/rpc"
+	_ "v.io/x/swift/impl/google/rt"
+)
+
+func Init() error {
+	// Currently nothing needed. Placeholder for the potential future.
+	return nil
+}
diff --git a/main/dummy.go b/main/dummy.go
new file mode 100644
index 0000000..be2f294
--- /dev/null
+++ b/main/dummy.go
@@ -0,0 +1,9 @@
+// Copyright 2015 The Vanadium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// +build !darwin
+
+package main
+
+func main() {}
diff --git a/main/main.go b/main/main.go
new file mode 100644
index 0000000..4cfb574
--- /dev/null
+++ b/main/main.go
@@ -0,0 +1,14 @@
+// Copyright 2015 The Vanadium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// +build darwin,ios
+
+package main
+
+import (
+	_ "v.io/x/swift"
+)
+
+func main() {
+}
diff --git a/swift.go b/swift.go
new file mode 100644
index 0000000..a2fc2e7
--- /dev/null
+++ b/swift.go
@@ -0,0 +1,58 @@
+// Copyright 2015 The Vanadium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// +build darwin,ios
+
+package swift
+
+import (
+	"unsafe"
+
+	"v.io/x/lib/vlog"
+
+	// TODO Make this pluggable somehow
+	_ "v.io/x/ref/runtime/factories/roaming"
+
+	sgoogle "v.io/x/swift/impl/google"
+	sutil "v.io/x/swift/util"
+	sv23 "v.io/x/swift/v23"
+)
+
+//#import "types.h"
+import "C"
+
+//export swift_io_v_v23_V_nativeInitGlobal
+func swift_io_v_v23_V_nativeInitGlobal(errOut *C.SwiftVError) {
+	// Send all vlog logs to stderr during the init so that we don't crash on android trying
+	// to create a log file.  These settings will be overwritten in nativeInitLogging below.
+	vlog.Log.Configure(vlog.OverridePriorConfiguration(true), vlog.LogToStderr(true))
+
+	if err := sv23.Init(); err != nil {
+		sutil.ThrowSwiftError(nil, err, unsafe.Pointer(errOut))
+		return
+	}
+	if err := sgoogle.Init(); err != nil {
+		sutil.ThrowSwiftError(nil, err, unsafe.Pointer(errOut))
+		return
+	}
+}
+
+//export swift_io_v_v23_V_nativeInitLogging
+func swift_io_v_v23_V_nativeInitLogging(logDir *C.char, logToStderr bool, logLevel int, moduleSpec *C.char, errOut *C.SwiftVError) {
+	dir, toStderr, level, vmodule, err := loggingOpts(C.GoString(logDir), logToStderr, logLevel, C.GoString(moduleSpec))
+	if err != nil {
+		sutil.ThrowSwiftError(nil, err, unsafe.Pointer(errOut))
+		return
+	}
+
+	vlog.Log.Configure(vlog.OverridePriorConfiguration(true), dir, toStderr, level, vmodule)
+}
+
+func loggingOpts(logDir string, logToStderr bool, logLevel int, moduleSpec string) (dir vlog.LogDir, toStderr vlog.LogToStderr, level vlog.Level, vmodule vlog.ModuleSpec, err error) {
+	dir = vlog.LogDir(logDir)
+	toStderr = vlog.LogToStderr(logToStderr)
+	level = vlog.Level(logLevel)
+	err = vmodule.Set(moduleSpec)
+	return
+}
diff --git a/types.h b/types.h
new file mode 100644
index 0000000..710c46a
--- /dev/null
+++ b/types.h
@@ -0,0 +1,50 @@
+// Copyright 2015 The Vanadium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+//
+// +build darwin,ios
+//
+// This file defines the types and structs that get passed between the Go runtime and Swift
+
+// Match the generated types from CGo without being able to include it's generated conversions
+typedef unsigned long long _GoUint64;
+typedef unsigned int _GoUint32;
+typedef long long _GoInt64;
+typedef int _GoInt32;
+
+// Define the handle types that allow us to reference objects in Go from Swift without passing unsafe pointers
+// This is particularly important given the upcoming moving GC dictates we can't rely on pointers staying stable.
+// See: https://github.com/golang/proposal/blob/master/design/12416-cgo-pointers.md
+typedef _GoUint64 _GoHandle;
+typedef _GoHandle GoContextHandle;
+typedef _GoHandle GoCancelableContextHandle;
+typedef _GoHandle GoClientCallHandle;
+
+// Express byte arrays with lengths
+typedef struct {
+    _GoUint64 length;
+    char* data;
+} SwiftByteArray;
+
+// Express arrays of byte arrays with lengths
+typedef struct {
+    _GoUint64 length;
+    SwiftByteArray* data;
+} SwiftByteArrayArray;
+
+// Encodes Go's VError in a format suitable for Swift conversion
+typedef struct {
+	char* identity;            // The identity of the error.
+	_GoUint32 actionCode;      // Default action to take on error.
+	char* msg;                 // Error message; empty if no language known.
+	char* stacktrace;          // Stacktraces rendered into a single string
+} SwiftVError;
+typedef SwiftVError* SwiftVErrorPtr;
+
+// Asynchronous callback function pointers, which use their own handle (AsyncCallbackIdentifier) to overcome
+// Swift limitations on context-free closures (function pointers)
+typedef int AsyncCallbackIdentifier;
+typedef void (*SwiftAsyncSuccessCallback)(AsyncCallbackIdentifier);
+typedef void (*SwiftAsyncSuccessHandleCallback)(AsyncCallbackIdentifier, _GoHandle);
+typedef void (*SwiftAsyncSuccessByteArrayArrayCallback)(AsyncCallbackIdentifier, SwiftByteArrayArray);
+typedef void (*SwiftAsyncFailureCallback)(AsyncCallbackIdentifier, SwiftVError);
diff --git a/util/ref.go b/util/ref.go
new file mode 100644
index 0000000..1d5ff08
--- /dev/null
+++ b/util/ref.go
@@ -0,0 +1,148 @@
+// Copyright 2015 The Vanadium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// +build darwin,ios
+
+package util
+
+import (
+	"fmt"
+	"reflect"
+	"sync"
+	"sync/atomic"
+)
+
+import "C"
+
+// GoRef creates a new reference to the value addressed by the provided pointer.
+// The value will remain referenced until it is explicitly unreferenced using
+// goUnref() using the returned sequence id.
+func GoNewRef(valptr interface{}) uint64 {
+	if !IsPointer(valptr) {
+		panic(fmt.Sprintf("must pass pointer value to goRef; instead got %v", valptr))
+	}
+	return goRefs.newRef(valptr)
+}
+
+// Increments the reference count to a previously existing id pointing to a value.
+func GoRef(id uint64) {
+	goRefs.ref(id)
+}
+
+// Removes a previously added reference to the value addressed by the
+// sequence id.  If the value hasn't been ref-ed (a bug?), this unref will
+// be a no-op.
+func GoUnref(id uint64) {
+	goRefs.unref(id)
+}
+
+func GoGetRef(id uint64) interface{} {
+	return goRefs.get(id)
+}
+
+// Returns true iff the provided value is a pointer.
+func IsPointer(val interface{}) bool {
+	v := reflect.ValueOf(val)
+	return v.Kind() == reflect.Ptr || v.Kind() == reflect.UnsafePointer
+}
+
+// Return the value of the pointer as a uintptr.
+func PtrValue(ptr interface{}) uintptr {
+	v := reflect.ValueOf(ptr)
+	if v.Kind() != reflect.Ptr && v.Kind() != reflect.UnsafePointer {
+		panic(fmt.Sprintf("must pass pointer value to PtrValue, was %v ", v.Type()))
+	}
+	return v.Pointer()
+}
+
+// Dereferences the provided (pointer) value, or panic-s if the value isn't of pointer type.
+func DerefOrDie(i interface{}) interface{} {
+	v := reflect.ValueOf(i)
+	if v.Kind() != reflect.Ptr {
+		panic(fmt.Sprintf("want reflect.Ptr value for %v, have %v", i, v.Type()))
+	}
+	return v.Elem().Interface()
+}
+
+// goRefs stores references to instances of various Go types, namely instances
+// that are referenced only by the Swift code.  The only purpose of this store
+// is to prevent Go runtime from garbage collecting those instances.
+var goRefs = newSafeRefCounter()
+var lastId uint64 = 0
+
+type refData struct {
+	instance interface{}
+	count    int
+}
+
+// Returns a new instance of a thread-safe reference counter.
+func newSafeRefCounter() *safeRefCounter {
+	return &safeRefCounter{
+		refs: make(map[uint64]*refData),
+	}
+}
+
+// safeRefCounter is a thread-safe reference counter.
+type safeRefCounter struct {
+	lock sync.Mutex
+	refs map[uint64]*refData
+}
+
+// Increment the reference count to the given valptr.
+func (c *safeRefCounter) ref(id uint64) {
+	c.lock.Lock()
+	defer c.lock.Unlock()
+	ref, ok := c.refs[id]
+	if !ok {
+		panic(fmt.Sprintf("Refing id %d that doesn't exist", id))
+	} else {
+		ref.count++
+	}
+}
+
+// Given a valptr, store that into our map and return the associated handle for Swift
+func (c *safeRefCounter) newRef(valptr interface{}) uint64 {
+	//	p := PtrValue(valptr)
+	c.lock.Lock()
+	defer c.lock.Unlock()
+	id := atomic.AddUint64(&lastId, 1)
+	c.refs[id] = &refData{
+		instance: valptr,
+		count:    1,
+	}
+	return id
+}
+
+// Decrement the reference count of the valptr asssociated with the handle, returning
+// the new reference count value and deleting the assocation if it hits 0.
+func (c *safeRefCounter) unref(id uint64) int {
+	c.lock.Lock()
+	defer c.lock.Unlock()
+	ref, ok := c.refs[id]
+	if !ok {
+		panic(fmt.Sprintf("Unrefing id %d that hasn't been refed before", id))
+	}
+	count := ref.count
+	if count == 0 {
+		panic(fmt.Sprintf("Ref count for id %d is zero", id))
+	}
+	if count > 1 {
+		ref.count--
+		return ref.count
+	}
+	delete(c.refs, id)
+	return 0
+}
+
+// Given a handle, return the associated go object
+func (c *safeRefCounter) get(id uint64) interface{} {
+	c.lock.Lock()
+	defer c.lock.Unlock()
+	ref, ok := c.refs[id]
+	if !ok {
+		panic(fmt.Sprintf("Trying to get id %d that doesn't exist", id))
+	} else {
+		return ref.instance
+	}
+}
diff --git a/util/type.go b/util/type.go
new file mode 100644
index 0000000..4f9e919
--- /dev/null
+++ b/util/type.go
@@ -0,0 +1,38 @@
+// Copyright 2015 The Vanadium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// +build darwin,ios
+
+package util
+
+import (
+	"math"
+	"time"
+)
+
+// #import "../types.h"
+import "C"
+
+// Useful when needing to return SOMETHING for a given function that otherwise is throwing an error via the errPtr
+func EmptySwiftByteArray() C.SwiftByteArray {
+	var empty C.SwiftByteArray
+	empty.length = 0
+	empty.data = nil
+	return empty
+}
+
+// Utils to convert between Go times and durations and NSTimeInterval in Swift
+func NSTimeInterval(t time.Time) C.double {
+	return C.double(t.UnixNano() / 1000000000.0)
+}
+
+func GoTime(t float64) time.Time {
+	seconds := math.Floor(t)
+	nsec := (t - seconds) * 1000000000.0
+	return time.Unix(int64(seconds), int64(nsec))
+}
+
+func GoDuration(d float64) time.Duration {
+	return time.Duration(int64(d * 1e9))
+}
diff --git a/util/util.go b/util/util.go
new file mode 100644
index 0000000..6fc4f81
--- /dev/null
+++ b/util/util.go
@@ -0,0 +1,88 @@
+// Copyright 2015 The Vanadium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// +build darwin,ios
+
+package util
+
+import (
+	"unsafe"
+
+	"v.io/v23/context"
+	"v.io/v23/verror"
+)
+
+/*
+#include "../types.h"
+
+// Because of weirdness with function pointers & cgo, we hack around limitations by defining methods that just call
+// C function pointers here. Go can call these functions directly.
+
+typedef void (*fxn_AsyncId)(AsyncCallbackIdentifier);
+typedef void (*fxn_AsyncId_GoHandle)(AsyncCallbackIdentifier, _GoHandle);
+typedef void (*fxn_AsyncId_SwiftByteArrayArray)(AsyncCallbackIdentifier, SwiftByteArrayArray);
+typedef void (*fxn_AsyncId_SwiftVError)(AsyncCallbackIdentifier, SwiftVError);
+
+static void callFxn_AsyncId(fxn_AsyncId fxnPtr, AsyncCallbackIdentifier a) {
+	fxnPtr(a);
+}
+
+static void callFxn_AsyncId_GoHandle(fxn_AsyncId_GoHandle fxnPtr, AsyncCallbackIdentifier a, _GoHandle b) {
+	fxnPtr(a, b);
+}
+
+static void callFxn_AsyncId_SwiftByteArrayArray(
+		fxn_AsyncId_SwiftByteArrayArray fxnPtr, AsyncCallbackIdentifier a, SwiftByteArrayArray b) {
+	fxnPtr(a, b);
+}
+
+static void callFxn_AsyncId_SwiftVError(fxn_AsyncId_SwiftVError fxnPtr, AsyncCallbackIdentifier a, SwiftVError b) {
+	fxnPtr(a, b);
+}
+*/
+import "C"
+
+func ThrowSwiftError(ctx *context.T, err error, swiftVErrorStructPtr unsafe.Pointer) {
+	id := verror.ErrorID(err)
+	actionCode := verror.Action(err)
+	vErr := verror.Convert(verror.IDAction{id, actionCode}, ctx, err)
+	pcs := verror.Stack(vErr)
+	stacktrace := pcs.String()
+	msg := vErr.Error()
+
+	var swiftErrorPtr *C.SwiftVError = (*C.SwiftVError)(swiftVErrorStructPtr)
+	(*swiftErrorPtr).identity = C.CString((string)(id))
+	(*swiftErrorPtr).actionCode = C._GoUint32(actionCode)
+	(*swiftErrorPtr).msg = C.CString(msg)
+	(*swiftErrorPtr).stacktrace = C.CString(stacktrace)
+}
+
+func DoSuccessCallback(successPtr unsafe.Pointer, asyncId int32) {
+	C.callFxn_AsyncId(
+		(C.fxn_AsyncId)(successPtr),
+		(C.AsyncCallbackIdentifier)(asyncId))
+}
+
+func DoSuccessHandlerCallback(successPtr unsafe.Pointer, asyncId int32, handler uint64) {
+	C.callFxn_AsyncId_GoHandle(
+		(C.fxn_AsyncId_GoHandle)(successPtr),
+		(C.AsyncCallbackIdentifier)(asyncId),
+		(C._GoHandle)(handler))
+}
+
+func DoSuccessByteArrayArrayCallback(successPtr unsafe.Pointer, asyncId int32, swiftByteArrayArrayPtr unsafe.Pointer) {
+	var byteArrayArray C.SwiftByteArrayArray = *(*C.SwiftByteArrayArray)(swiftByteArrayArrayPtr)
+	C.callFxn_AsyncId_SwiftByteArrayArray(
+		(C.fxn_AsyncId_SwiftByteArrayArray)(successPtr),
+		(C.AsyncCallbackIdentifier)(asyncId),
+		(C.SwiftByteArrayArray)(byteArrayArray))
+}
+
+func DoFailureCallback(failurePtr unsafe.Pointer, asyncId int32, swiftVErrorStructPtr unsafe.Pointer) {
+	var swiftError C.SwiftVError = *(*C.SwiftVError)(swiftVErrorStructPtr)
+	C.callFxn_AsyncId_SwiftVError(
+		(C.fxn_AsyncId_SwiftVError)(failurePtr),
+		(C.AsyncCallbackIdentifier)(asyncId),
+		swiftError)
+}
diff --git a/v23/context/swift.go b/v23/context/swift.go
new file mode 100644
index 0000000..a23b50d
--- /dev/null
+++ b/v23/context/swift.go
@@ -0,0 +1,81 @@
+// Copyright 2015 The Vanadium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// +build darwin,ios
+
+package context
+
+import (
+	"unsafe"
+
+	"v.io/v23/context"
+	sutil "v.io/x/swift/util"
+)
+
+//#import "../../types.h"
+import "C"
+
+// Not currently used
+//export swift_io_v_v23_context_VContext_nativeDeadline
+func swift_io_v_v23_context_VContext_nativeDeadline(ctxHandle C.GoContextHandle) C.double {
+	ctx := GoContext(uint64(ctxHandle))
+	d, ok := ctx.Deadline()
+	if !ok {
+		return 0
+	}
+	return C.double(sutil.NSTimeInterval(d))
+}
+
+//export swift_io_v_v23_context_VContext_nativeWithCancel
+func swift_io_v_v23_context_VContext_nativeWithCancel(ctxHandle C.GoContextHandle, errOut C.SwiftVErrorPtr) C.GoCancelableContextHandle {
+	ctx := GoContext(uint64(ctxHandle))
+	ctx, cancelFunc := context.WithCancel(ctx)
+	swiftCtx, err := SwiftCancelableContext(ctx, cancelFunc)
+	if err != nil {
+		sutil.ThrowSwiftError(ctx, err, unsafe.Pointer(errOut))
+		return C.GoCancelableContextHandle(0)
+	}
+	return C.GoCancelableContextHandle(swiftCtx)
+}
+
+//export swift_io_v_v23_context_VContext_nativeWithDeadline
+func swift_io_v_v23_context_VContext_nativeWithDeadline(ctxHandle C.GoContextHandle, deadlineEpoch C.double, errOut C.SwiftVErrorPtr) C.GoCancelableContextHandle {
+	ctx := GoContext(uint64(ctxHandle))
+	deadline := sutil.GoTime(float64(deadlineEpoch))
+	ctx, cancelFunc := context.WithDeadline(ctx, deadline)
+	swiftCtx, err := SwiftCancelableContext(ctx, cancelFunc)
+	if err != nil {
+		sutil.ThrowSwiftError(ctx, err, unsafe.Pointer(errOut))
+		return C.GoCancelableContextHandle(0)
+	}
+	return C.GoCancelableContextHandle(swiftCtx)
+}
+
+//export swift_io_v_v23_context_VContext_nativeWithTimeout
+func swift_io_v_v23_context_VContext_nativeWithTimeout(ctxHandle C.GoContextHandle, nsTimeout C.double, errOut *C.SwiftVError) C.GoCancelableContextHandle {
+	ctx := GoContext(uint64(ctxHandle))
+	timeout := sutil.GoDuration(float64(nsTimeout))
+	ctx, cancelFunc := context.WithTimeout(ctx, timeout)
+	swiftCtx, err := SwiftCancelableContext(ctx, cancelFunc)
+	if err != nil {
+		sutil.ThrowSwiftError(ctx, err, unsafe.Pointer(errOut))
+		return C.GoCancelableContextHandle(0)
+	}
+	return C.GoCancelableContextHandle(swiftCtx)
+}
+
+//export swift_io_v_v23_context_VContext_nativeFinalize
+func swift_io_v_v23_context_VContext_nativeFinalize(ctxHandle C.GoContextHandle) {
+	sutil.GoUnref(uint64(ctxHandle))
+}
+
+//export swift_io_v_v23_context_CancelableVContext_nativeCancelAsync
+func swift_io_v_v23_context_CancelableVContext_nativeCancelAsync(ctxHandle C.GoCancelableContextHandle, asyncId C.AsyncCallbackIdentifier, successCallback C.SwiftAsyncSuccessCallback) {
+	ctx, cancelFunc := GoCancelableContext(uint64(ctxHandle))
+	go func() {
+		cancelFunc()
+		<-ctx.Done()
+		sutil.DoSuccessCallback(unsafe.Pointer(successCallback), int32(asyncId))
+	}()
+}
diff --git a/v23/context/util.go b/v23/context/util.go
new file mode 100644
index 0000000..41793d0
--- /dev/null
+++ b/v23/context/util.go
@@ -0,0 +1,55 @@
+// Copyright 2015 The Vanadium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// +build darwin,ios
+
+package context
+
+import (
+	"fmt"
+
+	"v.io/v23/context"
+
+	sutil "v.io/x/swift/util"
+)
+
+// #include "../../types.h"
+import "C"
+
+// Converts a Go Context into a native pointer for Swift and increments the go reference count
+func SwiftContext(ctx *context.T) C.GoContextHandle {
+	id := sutil.GoNewRef(ctx)
+	return C.GoContextHandle(id)
+}
+
+// Converts a native pointer from Swift to a Go Context. Panics if it can't.
+func GoContext(ctxHandle uint64) *context.T {
+	valptr := sutil.GoGetRef(ctxHandle)
+	if ctx, ok := valptr.(*context.T); ok {
+		return ctx
+	} else {
+		panic(fmt.Sprintf("Couldn't get context from handle with id %d", ctxHandle))
+	}
+}
+
+type cancelFuncKey struct{}
+
+func SwiftCancelableContext(ctx *context.T, cancelFunc context.CancelFunc) (C.GoCancelableContextHandle, error) {
+	if cancelFunc == nil {
+		return C.GoCancelableContextHandle(0), fmt.Errorf("Cannot create SwiftCancelableContext with nil cancel function")
+	}
+	ctx = context.WithValue(ctx, cancelFuncKey{}, cancelFunc)
+	return C.GoCancelableContextHandle(SwiftContext(ctx)), nil
+}
+
+// Converts a native pointer from Swift to a Go Cancelable Context. Panics if it can't.
+func GoCancelableContext(ctxHandle uint64) (*context.T, context.CancelFunc) {
+	ctx := GoContext(ctxHandle)
+	value := ctx.Value(cancelFuncKey{})
+	if cancelFunc, ok := value.(context.CancelFunc); ok {
+		return ctx, cancelFunc
+	} else {
+		panic(fmt.Sprintf("Couldn't cast cancelFunc for contextId %d", ctxHandle))
+	}
+}
diff --git a/v23/swift.go b/v23/swift.go
new file mode 100644
index 0000000..6100440
--- /dev/null
+++ b/v23/swift.go
@@ -0,0 +1,18 @@
+// Copyright 2015 The Vanadium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// +build darwin,ios
+
+package v23
+
+import (
+	_ "v.io/x/swift/v23/context"
+)
+
+import "C"
+
+func Init() error {
+	// Currently nothing needed. Placeholder for the potential future.
+	return nil
+}