func (w *window) newBuffer(width, height int, format uint32) *C.struct_wl_buffer { stride := width * 4 size := stride * height fd := C.os_create_anonymous_file(C.off_t(size)) if fd < 0 { panic("Could not create buffer file.") } data := C.mmap(nil, C.size_t(size), C.PROT_READ|C.PROT_WRITE, C.MAP_SHARED, C.int(fd), 0) if *(*int)(data) == -1 { panic("mmap failed") C.close(fd) return nil } pool := C.wl_shm_create_pool(w.display.shm, C.int32_t(fd), C.int32_t(size)) buffer := C.wl_shm_pool_create_buffer(pool, 0, C.int32_t(width), C.int32_t(height), C.int32_t(stride), C.uint32_t(format)) C.wl_shm_pool_destroy(pool) C.close(fd) w.shmData = data return buffer }
func (s *SystemPort) Open() error { if s.isOpen && s.stream == nil { return errors.New("Underlying portmidi port is already opened, " + "but stream is not connected to this SystemPort.") } if s.id == -1 || s.isOpen { // Fake port or opened already, ignore. return nil } var errNum C.PmError if s.IsInputPort { // The input / output naming LOOKS backwards, but we're opening a // portmidi "output stream" for input Ports and vice versa. errNum = C.Pm_OpenOutput(&(s.stream), C.PmDeviceID(s.id), nil, C.int32_t(512), nil, nil, 0) } else { errNum = C.Pm_OpenInput(&(s.stream), C.PmDeviceID(s.id), nil, C.int32_t(512), nil, nil) } if errNum == 0 { s.isOpen = true s.stop = make(chan bool, 1) s.noteOns = make(chan Note, BufferSize) s.noteOffs = make(chan Note, BufferSize) s.controlChanges = make(chan ControlChange, BufferSize) } return makePortMidiError(errNum) }
func (hll *Hll) AddInt32(value int32) { cValue := C.int32_t(value) cSeed := C.int32_t(0) cHashKey := C.hll_hash_int32(cValue, cSeed) C.multiset_add(hll.ms, cHashKey) }
func (g *Geometry) c() *C.struct_wlc_geometry { return C.init_geometry( C.int32_t(g.Origin.X), C.int32_t(g.Origin.Y), C.uint32_t(g.Size.W), C.uint32_t(g.Size.H), ) }
func New(log2m int, regwidth int, expthresh int64, sparseon int) (*Hll, error) { cLog2m := C.int32_t(log2m) cRegwidth := C.int32_t(regwidth) cExpthresh := C.int64_t(expthresh) cSparseon := C.int32_t(sparseon) hll := &Hll{ms: C.hll_empty4(cLog2m, cRegwidth, cExpthresh, cSparseon)} return hll, nil }
func redraw(data unsafe.Pointer, callback *C.struct_wl_callback, time C.uint32_t) { win := (*window)(data) win.paintPixels(uint32(time)) C.wl_surface_attach(win.surface, win.buffer, 0, 0) C.wl_surface_damage(win.surface, 0, 0, C.int32_t(win.width), C.int32_t(win.height)) }
// Initializes a new output stream. func NewOutputStream(deviceId DeviceId, bufferSize int64, latency int64) (stream *Stream, err error) { var str *C.PmStream errCode := C.Pm_OpenOutput( (*unsafe.Pointer)(unsafe.Pointer(&str)), C.PmDeviceID(deviceId), nil, C.int32_t(bufferSize), nil, nil, C.int32_t(latency)) if errCode != 0 { return nil, convertToError(errCode) } return &Stream{deviceId: deviceId, pmStream: str}, nil }
func doICU(tag, caser, input string) string { err := C.UErrorCode(0) loc := C.CString(tag) cm := C.ucasemap_open(loc, C.uint32_t(0), &err) buf := make([]byte, len(input)*4) dst := (*C.char)(unsafe.Pointer(&buf[0])) src := C.CString(input) cn := C.int32_t(0) switch caser { case "fold": cn = C.ucasemap_utf8FoldCase(cm, dst, C.int32_t(len(buf)), src, C.int32_t(len(input)), &err) case "lower": cn = C.ucasemap_utf8ToLower(cm, dst, C.int32_t(len(buf)), src, C.int32_t(len(input)), &err) case "upper": cn = C.ucasemap_utf8ToUpper(cm, dst, C.int32_t(len(buf)), src, C.int32_t(len(input)), &err) case "title": cn = C.ucasemap_utf8ToTitle(cm, dst, C.int32_t(len(buf)), src, C.int32_t(len(input)), &err) } return string(buf[:cn]) }
func (stmt *Stmt) bind(args []driver.Value) error { c := stmt.c parameterCount := int(stmt.parameterCount) if parameterCount == 0 || len(args) == 0 { return nil } parameters := make([]C.struct_nuodb_value, parameterCount) for i, v := range args { if i >= parameterCount { break // go1.0.3 allowed extra args; ignore } var vt C.enum_nuodb_value_type var i32 C.int32_t var i64 C.int64_t switch v := v.(type) { case int64: vt = C.NUODB_TYPE_INT64 i64 = C.int64_t(v) case float64: vt = C.NUODB_TYPE_FLOAT64 i64 = *(*C.int64_t)(unsafe.Pointer(&v)) case bool: vt = C.NUODB_TYPE_BOOL if v { i64 = 1 } else { i64 = 0 } case string: vt = C.NUODB_TYPE_STRING b := []byte(v) args[i] = b // ensure the b is not GC'ed before the _bind i32 = C.int32_t(len(v)) i64 = C.int64_t(uintptr(unsafe.Pointer(&b[0]))) case []byte: vt = C.NUODB_TYPE_BYTES i32 = C.int32_t(len(v)) i64 = C.int64_t(uintptr(unsafe.Pointer(&v[0]))) case time.Time: vt = C.NUODB_TYPE_TIME i32 = C.int32_t(v.Nanosecond()) i64 = C.int64_t(v.Unix()) // seconds default: vt = C.NUODB_TYPE_NULL } parameters[i].i64 = i64 parameters[i].i32 = i32 parameters[i].vt = vt } if C.nuodb_statement_bind(c.db, stmt.st, (*C.struct_nuodb_value)(unsafe.Pointer(¶meters[0]))) != 0 { return c.lastError() } return nil }
func populateCIndexEntry(source *IndexEntry, dest *C.git_index_entry) { dest.ctime.seconds = C.int32_t(source.Ctime.seconds) dest.ctime.nanoseconds = C.uint32_t(source.Ctime.nanoseconds) dest.mtime.seconds = C.int32_t(source.Mtime.seconds) dest.mtime.nanoseconds = C.uint32_t(source.Mtime.nanoseconds) dest.mode = C.uint32_t(source.Mode) dest.uid = C.uint32_t(source.Uid) dest.gid = C.uint32_t(source.Gid) dest.file_size = C.uint32_t(source.Size) dest.id = *source.Id.toC() dest.path = C.CString(source.Path) }
// Recv is called by Java in a loop and blocks until Go requests a callback // be executed by the JVM. Then a request object is returned, along with a // handle for the host to respond via RecvRes. //export Recv func Recv(in **C.uint8_t, inlen *C.size_t) (ref, code, handle C.int32_t) { recv.Lock() for len(recv.req) == 0 { recv.cond.Wait() } req := recv.req[0] recv.req = recv.req[1:] seqToBuf(in, inlen, req.in) recv.Unlock() return C.int32_t(req.ref.Num), C.int32_t(req.code), C.int32_t(req.handle) }
// NewOutputStream initializes a new output stream. func NewOutputStream(id DeviceID, bufferSize int64, latency int64) (stream *Stream, err error) { var str *C.PmStream errCode := C.Pm_OpenOutput( (*unsafe.Pointer)(unsafe.Pointer(&str)), C.PmDeviceID(id), nil, C.int32_t(bufferSize), nil, nil, C.int32_t(latency)) if errCode != 0 { return nil, convertToError(errCode) } if info := Info(id); !info.IsOutputAvailable { return nil, ErrOutputUnavailable } return &Stream{deviceID: id, pmStream: str}, nil }
func (d *DataWriterIMP) addInvertedDoc(inverter Inverter, docId int32) error { return clownfish.TrapErr(func() { self := (*C.lucy_DataWriter)(clownfish.Unwrap(d, "d")) inverterCF := (*C.lucy_Inverter)(clownfish.Unwrap(inverter, "inverter")) C.LUCY_DataWriter_Add_Inverted_Doc(self, inverterCF, C.int32_t(docId)) }) }
func CreateCloneParams(filename string, args []string, env *[]string, cwd *string, suid int, stdhandles StdHandles) (*CloneParams, error) { result := &CloneParams{} var err error result.CommReader, result.CommWriter, err = os.Pipe() if err != nil { return nil, err } result.tls = tools.AlignedBuffer(4096, 16) result.stack = tools.AlignedBuffer(4096, 16) result.repr.tls = (*C.char)(unsafe.Pointer(&result.tls[0])) result.repr.stack = (*C.char)(unsafe.Pointer(&result.stack[len(result.stack)-1])) result.repr.commfd = C.int32_t(result.CommWriter.Fd()) result.repr.filename = C.CString(filename) if cwd != nil { result.repr.cwd = C.CString(*cwd) } if args != nil { result.args = stringsToCchars(args) result.repr.argv = &result.args[0] } if env != nil { result.env = stringsToCchars(*env) result.repr.envp = &result.env[0] } result.repr.suid = C.uint32_t(suid) result.stdhandles = stdhandles result.repr.stdhandles[0] = getFd(result.stdhandles.StdIn) result.repr.stdhandles[1] = getFd(result.stdhandles.StdOut) result.repr.stdhandles[2] = getFd(result.stdhandles.StdErr) runtime.SetFinalizer(result, freeCloneParams) return result, nil }
// Serializes a message to OSC wire format. // If a unsupported type is encountered, serialization // will be stopped. func Serialize(m *Message) ([]byte, error) { msg := C.lo_message_new() for i, param := range m.Params { switch x := param.(type) { case int32: C.lo_message_add_int32(msg, C.int32_t(x)) case int64: C.lo_message_add_int64(msg, C.int64_t(x)) case float32: C.lo_message_add_float(msg, C.float(x)) case float64: C.lo_message_add_double(msg, C.double(x)) case string: cstr := C.CString(x) defer C.free(unsafe.Pointer(cstr)) C.lo_message_add_string(msg, cstr) default: return nil, fmt.Errorf("Parameter %d has invalid type", i) } } cpath := C.CString(m.Path) defer C.free(unsafe.Pointer(cpath)) var size int tmpbuffer := C.lo_message_serialise(msg, cpath, unsafe.Pointer(nil), (*C.size_t)(unsafe.Pointer((&size)))) defer C.free(unsafe.Pointer(tmpbuffer)) longbuffer := C.GoBytes(tmpbuffer, C.int(size)) shortbuffer := make([]byte, size) copy(shortbuffer, longbuffer) return shortbuffer, nil }
// init inits the manager and creates a goroutine to proxy the CGO calls. // All actions related to an ALooper needs to be performed from the same // OS thread. The goroutine proxy locks itself to an OS thread and handles the // CGO traffic on the same thread. func init() { go func() { runtime.LockOSThread() C.GoAndroid_createManager() for { v := <-inout switch s := v.in.(type) { case enableSignal: usecsDelay := s.delay.Nanoseconds() / 1000 code := int(C.GoAndroid_enableSensor(typeToInt(s.t), C.int32_t(usecsDelay))) if code != 0 { *s.err = fmt.Errorf("sensor: no default %v sensor on the device", s.t) } case disableSignal: C.GoAndroid_disableSensor(typeToInt(s.t)) case readSignal: n := readEvents(s.dst) *s.n = n case closeSignal: C.GoAndroid_destroyManager() close(v.out) return // we don't need this goroutine anymore } close(v.out) } }() }
// VImageRichardsonLucyDeConvolve_ARGB8888 sharpens an ARGB8888 image by undoing a previous convolution that blurred the image, such as diffraction effects in a camera lens. func VImageRichardsonLucyDeConvolve_ARGB8888(src, dst *VImageBuffer, tempBuffer []byte, roiX, roiY int, kernel, kernel2 []int16, kernelHeight, kernelWidth, kernelHeight2, kernelWidth2, divisor, divisor2 int, backgroundColor [4]uint8, iterationCount int, flags VImageFlag) error { var tmpBuf unsafe.Pointer if tempBuffer != nil { tmpBuf = unsafe.Pointer(&tempBuffer[0]) } var kernel2Ptr *C.int16_t if kernel2 != nil { kernel2Ptr = (*C.int16_t)(&kernel2[0]) } srcC := src.toC() dstC := dst.toC() return toError(C.vImageRichardsonLucyDeConvolve_ARGB8888(&srcC, &dstC, tmpBuf, C.vImagePixelCount(roiX), C.vImagePixelCount(roiY), (*C.int16_t)(&kernel[0]), kernel2Ptr, C.uint32_t(kernelHeight), C.uint32_t(kernelWidth), C.uint32_t(kernelHeight2), C.uint32_t(kernelWidth2), C.int32_t(divisor), C.int32_t(divisor2), (*C.uint8_t)(&backgroundColor[0]), C.uint32_t(iterationCount), C.vImage_Flags(flags))) }
// transact calls a method on an Objective-C object instance. // It blocks until the call is complete. // // Code (>0) is the method id assigned by gobind. // Code -1 is used to instruct Objective-C to decrement the ref count of // the Objective-Co object. func transact(ref *seq.Ref, descriptor string, code int, in *seq.Buffer) *seq.Buffer { var ( res *C.uint8_t = nil resLen C.size_t = 0 req *C.uint8_t = nil reqLen C.size_t = 0 ) if len(in.Data) > 0 { req = (*C.uint8_t)(unsafe.Pointer(&in.Data[0])) reqLen = C.size_t(len(in.Data)) } if debug { fmt.Printf("transact: ref.Num = %d code = %d\n", ref.Num, code) } desc := cstrings.get(descriptor) C.go_seq_recv(C.int32_t(ref.Num), desc, C.int(code), req, reqLen, &res, &resLen) if resLen > 0 { goSlice := (*[maxSliceLen]byte)(unsafe.Pointer(res))[:resLen] out := new(seq.Buffer) out.Data = make([]byte, int(resLen)) copy(out.Data, goSlice) C.free(unsafe.Pointer(res)) // TODO: own or copy []bytes whose addresses were passed in. return out } return nil }
func goToCKey(key MVCCKey) C.DBKey { return C.DBKey{ key: goToCSlice(key.Key), wall_time: C.int64_t(key.Timestamp.WallTime), logical: C.int32_t(key.Timestamp.Logical), } }
func Convert(input []byte, from string, to string) ([]byte, error) { cfrom := C.CString(from) defer C.free(unsafe.Pointer(cfrom)) cto := C.CString(to) defer C.free(unsafe.Pointer(cto)) src := (*C.char)(unsafe.Pointer(&input[0])) srcLen := C.int32_t(len(input)) uErr := C.UErrorCode(C.U_ZERO_ERROR) // get dstLen // ignore ENOENT dstLen, _ := C.ucnv_convert(cto, cfrom, nil, 0, src, srcLen, &uErr) if uErr != C.U_BUFFER_OVERFLOW_ERROR { return nil, uErrorToGoError(uErr) } uErr = C.UErrorCode(C.U_ZERO_ERROR) output := make([]byte, int(dstLen)) dst := (*C.char)(unsafe.Pointer(&output[0])) dstLen, err := C.ucnv_convert(cto, cfrom, dst, dstLen, src, srcLen, &uErr) if err != nil { return nil, err } if err = uErrorToGoError(uErr); err != nil { return nil, err } return output, nil }
// NewContext creates a new context of the requested kind. // // digits is used to set the precision to be used for an operation. The result of an // operation will be rounded to this length if necessary. digits should be in [MinDigits, MaxDigits]. // The maximum supported value for digits in many arithmetic operations is MaxMath. If digits is 0, // the context will be configured to use the default number of digits according to ContextKind. // // Note that the default exponent settings for InitBase will be too large for the few Number methods // that are considered mathematical functions. These defaults can be adjusted with SetEMax(), // SetEMin(), SetRounding() and SetClamp(). // // Although the native byte order should be properly detected at build time, NewContext() will // check the runtime byte order and panic if the byte order is not set correctly. If your code panics // on this check, please file a bug report. Check for any errors after context creation by calling // Context.ErrorStatus(). func NewContext(kind ContextKind, digits int32) (pContext *Context) { if C.decContextTestEndian(1) != 0 { panic("Wrong byte order for this architecture. Please file a bug report.") } pContext = new(Context) C.decContextDefault(&pContext.ctx, C.int32_t(kind)) if pContext.Status().Test(Errors) { // Happens if kind not in [0, 32, 64, 128] panic("Unsupported context kind.") } pContext.ctx.traps = 0 // disable traps if digits != 0 { pContext.ctx.digits = C.int32_t(digits) } return }
func OpenIndexer(args *OpenIndexerArgs) (obj Indexer, err error) { var schemaC *C.lucy_Schema = nil if args.Schema != nil { schemaC = (*C.lucy_Schema)(unsafe.Pointer(args.Schema.TOPTR())) } switch args.Index.(type) { case string: default: panic("TODO: support Folder") } ixLoc := clownfish.NewString(args.Index.(string)) var managerC *C.lucy_IndexManager = nil if args.Manager != nil { managerC = (*C.lucy_IndexManager)(unsafe.Pointer(args.Manager.TOPTR())) } var flags int32 if args.Create { flags = flags | int32(C.lucy_Indexer_CREATE) } if args.Truncate { flags = flags | int32(C.lucy_Indexer_TRUNCATE) } err = clownfish.TrapErr(func() { cfObj := C.lucy_Indexer_new(schemaC, (*C.cfish_Obj)(unsafe.Pointer(ixLoc.TOPTR())), managerC, C.int32_t(flags)) obj = WRAPIndexer(unsafe.Pointer(cfObj)) }) return obj, err }
func (s *SortCacheIMP) Ordinal(docId int32) (retval int32, err error) { err = clownfish.TrapErr(func() { self := (*C.lucy_SortCache)(clownfish.Unwrap(s, "s")) retvalCF := C.LUCY_SortCache_Ordinal(self, C.int32_t(docId)) retval = int32(retvalCF) }) return retval, err }
func (s *SearcherIMP) fetchDocVec(docID int32) (dv DocVector, err error) { err = clownfish.TrapErr(func() { self := (*C.lucy_Searcher)(clownfish.Unwrap(s, "s")) dvC := C.LUCY_Searcher_Fetch_Doc_Vec(self, C.int32_t(docID)) dv = WRAPDocVector(unsafe.Pointer(dvC)) }) return dv, err }
func (d *DocReaderIMP) FetchDoc(docID int32) (doc HitDoc, err error) { err = clownfish.TrapErr(func() { self := (*C.lucy_DocReader)(clownfish.Unwrap(d, "d")) docC := C.LUCY_DocReader_Fetch_Doc(self, C.int32_t(docID)) doc = WRAPHitDoc(unsafe.Pointer(docC)) }) return doc, err }
func (h *HighlightReaderIMP) FetchDocVec(docID int32) (retval DocVector, err error) { err = clownfish.TrapErr(func() { self := (*C.lucy_HighlightReader)(clownfish.Unwrap(h, "h")) retvalCF := C.LUCY_HLReader_Fetch_Doc_Vec(self, C.int32_t(docID)) retval = WRAPDocVector(unsafe.Pointer(retvalCF)) }) return retval, err }
// Truncate truncates 'a'. // It is like rounding with ROUND_DOWN. // // n must be in the range [-35...34]. Else, Invalid Operation flag is set, and NaN is returned. // // ### this method has not been fully tested yet, but it should work. I must write some test to be sure ### // func (context *Context) Truncate(a Quad, n int32) (r Quad) { var result C.Ret_decQuad_t assert_sane(context) result = C.mdq_roundM(a.val, C.int32_t(n), C.int(RoundDown), context.set) context.set = result.set return Quad{val: result.val} }
// FromNumber converts a Number to BCD Packed Decimal. // // The Number is converted to a BCD packed decimal byte array, right aligned in the bcd array. The // final 4-bit nibble in the array will be a sign nibble, C (1100) for + and D (1101) for -. Unused // bytes and nibbles to the left of the number are set to 0. // // The Packed scale is set to the scale of the number (this is the exponent, negated). To force the // number to a specified scale, first use Rescale, which will round and change // the exponent as necessary. // // If there is an error (that is, the Number has too many digits to fit the byte array, or it is a // NaN or Infinity), NULL is returned and the bcd and scale results are unchanged. Otherwise bcd is // returned. func (p *Packed) FromNumber(num *Number) error { p.Buf = make([]byte, (num.Digits()+2)/2) res := C.decPackedFromNumber((*C.uint8_t)(&p.Buf[0]), C.int32_t(len(p.Buf)), (*C.int32_t)(&p.Scale), num.DecNumber()) if res == nil { return &ContextError{InvalidOperation} } return nil }
// FromInt32 returns a Quad from a int32 value. // // No error should occur, and context status will not change. // func (context *Context) FromInt32(value int32) (r Quad) { var result C.Ret_decQuad_t assert_sane(context) result = C.mdq_from_int32(C.int32_t(value), context.set) context.set = result.set return Quad{val: result.val} }
func (s *SortCacheIMP) Value(ord int32) (retval interface{}, err error) { err = clownfish.TrapErr(func() { self := (*C.lucy_SortCache)(clownfish.Unwrap(s, "s")) retvalCF := C.LUCY_SortCache_Value(self, C.int32_t(ord)) defer C.cfish_decref(unsafe.Pointer(retvalCF)) retval = clownfish.ToGo(unsafe.Pointer(retvalCF)) }) return retval, err }