Exemplo n.º 1
2
//export sourceFill
func sourceFill(dinfo *C.struct_jpeg_decompress_struct) C.boolean {
	mgr := getSourceManager(dinfo)
	buffer := [readBufferSize]byte{}
	bytes, err := mgr.src.Read(buffer[:])
	C.memcpy(mgr.buffer, unsafe.Pointer(&buffer[0]), C.size_t(bytes))
	mgr.pub.bytes_in_buffer = C.size_t(bytes)
	mgr.currentSize = bytes
	mgr.pub.next_input_byte = (*C.JOCTET)(mgr.buffer)
	if err == io.EOF {
		if bytes == 0 {
			if mgr.startOfFile {
				releaseSourceManager(mgr)
				panic("input is empty")
			}
			// EOF and need more data. Fill in a fake EOI to get a partial image.
			footer := []byte{0xff, C.JPEG_EOI}
			C.memcpy(mgr.buffer, unsafe.Pointer(&footer[0]), C.size_t(len(footer)))
			mgr.pub.bytes_in_buffer = 2
		}
	} else if err != nil {
		releaseSourceManager(mgr)
		panic(err)
	}
	mgr.startOfFile = false

	return C.TRUE
}
Exemplo n.º 2
0
// Changes the size of the canvas using specified filter and blur, returns true on success.
func (self *Canvas) ResizeWithFilter(width uint, height uint, filter uint, blur float32) error {
	if width == 0 && height == 0 {
		return errors.New("Please specify at least one of dimensions")
	}

	if width == 0 || height == 0 {
		origHeight := uint(C.MagickGetImageHeight(self.wand))
		origWidth := uint(C.MagickGetImageWidth(self.wand))

		if width == 0 {
			ratio := float32(origHeight) / float32(height)
			width = uint(float32(origWidth) / ratio)
		}
		if height == 0 {
			ratio := float32(origWidth) / float32(width)
			height = uint(float32(origHeight) / ratio)
		}
	}

	success := C.MagickResizeImage(self.wand, C.size_t(width), C.size_t(height), C.FilterTypes(filter), C.double(blur))

	if success == C.MagickFalse {
		return fmt.Errorf("Could not resize: %s", self.Error())
	}

	return nil
}
Exemplo n.º 3
0
// Use the codec to convert a string
func (cd *Iconv) Conv(input string) (result string, err error) {
	var buf bytes.Buffer

	if len(input) == 0 {
		return "", nil
	}

	inbuf := []byte(input)
	outbuf := make([]byte, bufSize)
	inbytes := C.size_t(len(inbuf))
	inptr := &inbuf[0]

	for inbytes > 0 {
		outbytes := C.size_t(len(outbuf))
		outptr := &outbuf[0]
		_, err = C.iconv(cd.pointer,
			(**C.char)(unsafe.Pointer(&inptr)), &inbytes,
			(**C.char)(unsafe.Pointer(&outptr)), &outbytes)
		buf.Write(outbuf[:len(outbuf)-int(outbytes)])
		if err != nil && err != syscall.E2BIG {
			return buf.String(), err
		}
	}

	return buf.String(), nil
}
Exemplo n.º 4
0
func Shuffle(rng *rng.GslRng, data interface{}, n int) {
	// data must be a slice
	dataType := reflect.TypeOf(data)
	if dataType.Kind() != reflect.Slice {
		gogsl.Error("rng.Shuffle() must have a slice as its second argument", gogsl.GSL_EINVAL)
		return
	}
	baseType := dataType.Elem()
	dataVal := reflect.ValueOf(data)
	sliceN := dataVal.Len()
	if sliceN < 0 {
		gogsl.Error("shuffle length may not be negative in rng.Shuffle()", gogsl.GSL_EINVAL)
		return
	}
	if sliceN < n {
		gogsl.Error("shuffle length too large for slice in rng.Shuffle()", gogsl.GSL_EINVAL)
		return
	}
	elementLen := baseType.Size()
	addr := dataVal.Index(0).UnsafeAddr()

	//hdr := (*reflect.SliceHeader)(unsafe.Pointer(addr))
	//void gsl_ran_shuffle (const gsl_rng * r, void * base, size_t n, size_t size)
	C.gsl_ran_shuffle((*C.gsl_rng)(unsafe.Pointer(rng.Ptr())),
		unsafe.Pointer(addr),
		C.size_t(n), C.size_t(elementLen))
}
Exemplo n.º 5
0
// Put writes data associated with a key to the database.
//
// If a nil []byte is passed in as value, it will be returned by Get as an
// zero-length slice.
//
// The key and value byte slices may be reused safely. Put takes a copy of
// them before returning.
func (db *DB) Put(wo *WriteOptions, key, value []byte) error {
	var errStr *C.char
	// leveldb_put, _get, and _delete call memcpy() (by way of Memtable::Add)
	// when called, so we do not need to worry about these []byte being
	// reclaimed by GC.
	var k, v *C.char
	if len(key) != 0 {
		k = (*C.char)(unsafe.Pointer(&key[0]))
	}
	if len(value) != 0 {
		v = (*C.char)(unsafe.Pointer(&value[0]))
	}

	lenk := len(key)
	lenv := len(value)
	C.leveldb_put(
		db.Ldb, wo.Opt, k, C.size_t(lenk), v, C.size_t(lenv), &errStr)

	if errStr != nil {
		gs := C.GoString(errStr)
		C.free(unsafe.Pointer(errStr))
		return DatabaseError(gs)
	}
	return nil
}
Exemplo n.º 6
0
func ReadAt(fd int, off int64, size int) ([]byte, error) {
	idx := <-idle_event
	retch := aio_result_map[idx]
	defer func() { idle_event <- idx }()

	var cb *C.struct_iocb = &cbs[idx]

	var read_buf unsafe.Pointer
	C.posix_memalign(&read_buf, pagesize, C.size_t(size))
	defer C.free(read_buf)

	C.io_prep_pread(cb, C.int(fd), read_buf, C.size_t(size), C.longlong(off))
	cbs[idx].data = unsafe.Pointer(&idx)

	aio_lock.Lock()
	rt := C.io_submit(ctx, 1, &cb)
	if int(rt) < 0 {
		aio_lock.Unlock()
		return nil, errors.New("io submit failed")
	}
	aiocount++
	aio_lock.Unlock()

	select {
	case have_aio_event <- 0:
	default:
	}

	ret := <-retch

	return ret.buf, ret.err
}
Exemplo n.º 7
0
func fset(target, old, new uintptr) {
	pageOffset := target % pageSize
	pageAddr := target - pageOffset

	var mem []byte
	memh := (*reflect.SliceHeader)(unsafe.Pointer(&mem))
	memh.Data = pageAddr
	memh.Len = pageSize * 2
	memh.Cap = pageSize * 2

	oldAddr := make([]byte, 8)
	newAddr := make([]byte, 8)

	binary.LittleEndian.PutUint64(oldAddr, uint64(old))
	binary.LittleEndian.PutUint64(newAddr, uint64(new))

	// BSD's syscall package misses Mprotect. Use cgo instead.
	C.mprotect(unsafe.Pointer(pageAddr), C.size_t(len(mem)), protEXEC|protREAD|protWRITE)
	defer C.mprotect(unsafe.Pointer(pageAddr), C.size_t(len(mem)), protEXEC|protREAD)

	delta := make([]byte, 4)
	for i, c := range mem[pageOffset:] {
		if c == 0xe8 && int(pageOffset)+i+5 < len(mem) {
			instrAddr := pageAddr + pageOffset + uintptr(i)
			binary.LittleEndian.PutUint32(delta, uint32(old-instrAddr-5))
			if bytes.Equal(mem[int(pageOffset)+i+1:int(pageOffset)+i+5], delta) {
				binary.LittleEndian.PutUint32(mem[int(pageOffset)+i+1:], uint32(new-instrAddr-5))
				return
			}
		}
	}
	panic("cannot setup qml package for testing")
}
Exemplo n.º 8
0
func NewTrailDBConstructor(path string, ofields ...string) (*TrailDBConstructor, error) {
	cons := C.tdb_cons_init()
	cpath := C.CString(path)
	defer C.free(unsafe.Pointer(cpath))

	var ofield_p *C.char
	ptrSize := unsafe.Sizeof(ofield_p)

	// Allocate the char** list.
	ptr := C.malloc(C.size_t(len(ofields)) * C.size_t(ptrSize))
	defer C.free(ptr)

	// Assign each byte slice to its appropriate offset.
	for i := 0; i < len(ofields); i++ {
		element := (**C.char)(unsafe.Pointer(uintptr(ptr) + uintptr(i)*ptrSize))
		cofield := C.CString(ofields[i])
		defer C.free(unsafe.Pointer(cofield))
		*element = cofield
	}

	if err := C.tdb_cons_open(cons, cpath, (**C.char)(ptr), C.uint64_t(len(ofields))); err != 0 {
		return nil, errors.New(errToString(err))
	}
	return &TrailDBConstructor{
		cons:         cons,
		path:         path,
		ofields:      ofields,
		valueLengths: make([]C.uint64_t, len(ofields)),
		valuePtr:     C.malloc(C.size_t(len(ofields)) * C.size_t(ptrSize)),
	}, nil
}
Exemplo n.º 9
0
func getGroupName(fi os.FileInfo) (string, error) {
	var rv C.int
	var grp C.struct_group
	var grpres *C.struct_group
	var bufSize C.long
	var result string

	bufSize = 1024
	buf := C.malloc(C.size_t(bufSize))
	defer C.free(buf)

	gid := fi.Sys().(*syscall.Stat_t).Gid

	rv = C.mygetgrgid_r(C.int(gid), &grp, (*C.char)(buf), C.size_t(bufSize), &grpres)
	if rv != 0 {
		return "", errors.New("Could not read groupname")
	}

	if grpres != nil {
		result = C.GoString(grp.gr_name)
	} else {
		return "", errors.New("Could not convert groupname")
	}
	return result, nil
}
Exemplo n.º 10
0
func getUserName(fi os.FileInfo) (string, error) {
	var rv C.int
	var pwd C.struct_passwd
	var pwdres *C.struct_passwd
	var bufSize C.long
	var result string

	bufSize = 1024
	buf := C.malloc(C.size_t(bufSize))
	defer C.free(buf)

	uid := fi.Sys().(*syscall.Stat_t).Uid

	rv = C.mygetpwuid_r(C.int(uid), &pwd, (*C.char)(buf), C.size_t(bufSize), &pwdres)
	if rv != 0 {
		return "", errors.New("Could not read username")
	}

	if pwdres != nil {
		result = C.GoString(pwd.pw_name)
	} else {
		return "", errors.New("Could not convert username")
	}

	return result, nil
}
Exemplo n.º 11
0
// Reads packets from a packet table starting at the current index.
// herr_t H5PTget_next( hid_t table_id, size_t nrecords, void *data)
func (t *Table) Next(data interface{}) error {
	rt := reflect.TypeOf(data)
	rv := reflect.ValueOf(data)
	c_nrecords := C.size_t(0)
	c_data := unsafe.Pointer(nil)
	switch rt.Kind() {
	case reflect.Array:
		//fmt.Printf("--> array\n")
		if rv.Cap() <= 0 {
			panic(fmt.Sprintf("not enough capacity in array (cap=%d)", rv.Cap()))
		}
		c_data = unsafe.Pointer(rv.Index(0).UnsafeAddr())
		c_nrecords = C.size_t(rv.Cap())

	case reflect.Slice:
		//fmt.Printf("--> slice\n")
		if rv.Cap() <= 0 {
			panic(fmt.Sprintf("not enough capacity in slice (cap=%d)", rv.Cap()))
		}
		slice := (*reflect.SliceHeader)(unsafe.Pointer(rv.UnsafeAddr()))
		c_data = unsafe.Pointer(slice.Data)
		c_nrecords = C.size_t(rv.Cap())

	default:
		panic(fmt.Sprintf("unhandled kind (%s) need slice or array", rt.Kind()))
	}
	//fmt.Printf("--data: %v...\n", data)
	err := C.H5PTget_next(t.id, c_nrecords, c_data)
	//fmt.Printf("--data: err [%v]\n", err)
	//fmt.Printf("--data: %v... [%v]\n", data, err)
	return togo_err(err)
}
Exemplo n.º 12
0
func (cq *CommandQueue) EnqueueReadImage(i *Image, blocking bool, origin, region [3]Size, rowPitch, slicePitch Size) ([]byte, error) {
	c_blocking := C.cl_bool(C.CL_FALSE)
	if blocking {
		c_blocking = C.CL_TRUE
	}

	size := Size(0)
	if i.Property(IMAGE_DEPTH) == 0 || i.Property(IMAGE_DEPTH) == 1 { // 2D image
		if rowPitch == 0 {
			rowPitch = i.Property(IMAGE_WIDTH) * i.Property(IMAGE_ELEMENT_SIZE)
		}
		size = rowPitch * i.Property(IMAGE_HEIGHT)
	} else {
		if slicePitch == 0 {
			if rowPitch == 0 {
				rowPitch = i.Property(IMAGE_WIDTH) * i.Property(IMAGE_ELEMENT_SIZE)
			}
			slicePitch = rowPitch * i.Property(IMAGE_DEPTH)
		}
		size = slicePitch * i.Property(IMAGE_DEPTH)
	}
	bytes := make([]byte, size)

	if ret := C.clEnqueueReadImage(
		cq.id, i.id, c_blocking,
		(*C.size_t)(unsafe.Pointer(&origin[0])), (*C.size_t)(unsafe.Pointer(&region[0])),
		C.size_t(rowPitch), C.size_t(slicePitch), unsafe.Pointer(&bytes[0]),
		0, nil, nil); ret != C.CL_SUCCESS {
		return nil, Cl_error(ret)
	}
	return bytes, nil
}
Exemplo n.º 13
0
func (cq *CommandQueue) EnqueueWriteBuffer(buf *Buffer, data []byte, offset uint32) error {

	if ret := C.clEnqueueWriteBuffer(cq.id, buf.id, C.CL_TRUE, C.size_t(offset), C.size_t(len(data)), unsafe.Pointer(&data[0]), 0, nil, nil); ret != C.CL_SUCCESS {
		return Cl_error(ret)
	}
	return nil
}
Exemplo n.º 14
0
func (cq *CommandQueue) EnqueueReadBuffer(buf *Buffer, offset uint32, size uint32) ([]byte, error) {
	bytes := make([]byte, size)
	if ret := C.clEnqueueReadBuffer(cq.id, buf.id, C.CL_TRUE, C.size_t(offset), C.size_t(size), unsafe.Pointer(&bytes[0]), 0, nil, nil); ret != C.CL_SUCCESS {
		return nil, Cl_error(ret)
	}
	return bytes, nil
}
Exemplo n.º 15
0
func (self *Canvas) SetSize(width, height uint) error {
	if C.MagickSetSize(self.wand, C.size_t(width), C.size_t(height)) == C.MagickFalse {
		return fmt.Errorf("Could not set size: %s", self.Error())
	}

	return nil
}
Exemplo n.º 16
0
// Transceive raw bit-frame to a target. n contains the received byte count on
// success, or is meaningless on error. The current implementation will return
// the libnfc error code in case of error, but this is subject to change. If
// txLength is longer than the supplied slice, an error will occur. txPar has to
// have the same length as tx, dito for rxPar and rx. An error will occur if any
// of these invariants do not hold.
//
// tx contains a byte slice of the frame that needs to be transmitted. txLength
// contains its length in bits.
//
// For example the REQA (0x26) command (the first anti-collision command of
// ISO14443-A) must be precise 7 bits long. This is not possible using
// Device.InitiatorTransceiveBytes(). With that function you can only
// communicate frames that consist of full bytes. When you send a full byte (8
// bits + 1 parity) with the value of REQA (0x26), a tag will simply not
// respond.
//
// txPar contains a byte slice of the corresponding parity bits needed to send
// per byte.
//
// For example if you send the SELECT_ALL (0x93, 0x20) = [ 10010011, 00100000 ]
// command, you have to supply the following parity bytes (0x01, 0x00) to define
// the correct odd parity bits. This is only an example to explain how it works,
// if you just are sending two bytes with ISO14443-A compliant parity bits you
// better can use the Device.InitiatorTransceiveBytes() method.
//
// rx will contain the response from the target. This function will return
// EOVFLOW if more bytes are received than the length of rx. rxPar contains a
// byte slice of the corresponding parity bits.
//
// The NFC device (configured as initiator) will transmit low-level messages
// where only the modulation is handled by the PN53x chip. Construction of the
// frame (data, CRC and parity) is completely done by libnfc.  This can be very
// useful for testing purposes. Some protocols (e.g. MIFARE Classic) require to
// violate the ISO14443-A standard by sending incorrect parity and CRC bytes.
// Using this feature you are able to simulate these frames.
func (d Device) InitiatorTransceiveBits(tx, txPar []byte, txLength uint, rx, rxPar []byte) (n int, err error) {
	if *d.d == nil {
		return ESOFT, errors.New("device closed")
	}

	if len(tx) != len(txPar) || len(rx) != len(rxPar) {
		return ESOFT, errors.New("Invariant doesn't hold")
	}

	if uint(len(tx))*8 < txLength {
		return ESOFT, errors.New("Slice shorter than specified bit count")
	}

	txptr := (*C.uint8_t)(&tx[0])
	txparptr := (*C.uint8_t)(&txPar[0])
	rxptr := (*C.uint8_t)(&rx[0])
	rxparptr := (*C.uint8_t)(&rxPar[0])

	n = int(C.nfc_initiator_transceive_bits(
		*d.d,
		txptr, C.size_t(txLength), txparptr,
		rxptr, C.size_t(len(rx)), rxparptr,
	))

	if n < 0 {
		err = Error(n)
	}

	return
}
Exemplo n.º 17
0
// Send data to target then retrieve data from target with timing control. n
// contains the received byte count on success, or is meaningless on error. c
// will contain the actual number of cycles waited. The current implementation
// will return the libnfc error code in case of error, but this is subject to
// change. This function will return EOVFLOW if more bytes are being received
// than the length of rx.
//
// This function is similar to Device.InitiatorTransceiveBytes() with the
// following differences:
//
//  - A precise cycles counter will indicate the number of cycles between emission & reception of frames.
//  - Only modes with EASY_FRAMING option disabled are supported.
//  - Overall communication with the host is heavier and slower.
//
// By default, the timer configuration tries to maximize the precision, which
// also limits the maximum cycle count before saturation / timeout. E.g. with
// PN53x it can count up to 65535 cycles, avout 4.8ms with a precision of about
// 73ns. If you're ok with the defaults, call this function with cycles = 0. If
// you need to count more cycles, set cycles to the maximum you exprect, but
// don't forget you'll loose in precision and it'll take more time before
// timeout, so don't abuse!
//
// Warning: The configuration option EASY_FRAMING must be set to false; the
// configuration option HANDLE_PARITY must be set to true (default value).
func (d Device) InitiatorTransceiveBytesTimed(tx, rx []byte, cycles uint32) (n int, c uint32, err error) {
	if *d.d == nil {
		return ESOFT, 0, errors.New("device closed")
	}

	var cptr *C.uint32_t
	*cptr = C.uint32_t(cycles)

	txptr := (*C.uint8_t)(&tx[0])
	rxptr := (*C.uint8_t)(&rx[0])

	n = int(C.nfc_initiator_transceive_bytes_timed(
		*d.d,
		txptr, C.size_t(len(tx)),
		rxptr, C.size_t(len(rx)),
		cptr,
	))

	if n < 0 {
		err = Error(n)
	}

	c = uint32(*cptr)

	return
}
Exemplo n.º 18
0
func sizeT3(i3 [3]int) [3]C.size_t {
	var val [3]C.size_t
	val[0] = C.size_t(i3[0])
	val[1] = C.size_t(i3[1])
	val[2] = C.size_t(i3[2])
	return val
}
Exemplo n.º 19
0
func CLCreateImage3D(context CL_context,
	flags CL_mem_flags,
	image_format *CL_image_format,
	image_width CL_size_t,
	image_height CL_size_t,
	image_depth CL_size_t,
	image_row_pitch CL_size_t,
	image_slice_pitch CL_size_t,
	host_ptr unsafe.Pointer,
	errcode_ret *CL_int) CL_mem {

	var c_image_format C.cl_image_format
	var c_errcode_ret C.cl_int
	var c_image C.cl_mem

	c_image_format.image_channel_order = C.cl_channel_order(image_format.Image_channel_order)
	c_image_format.image_channel_data_type = C.cl_channel_type(image_format.Image_channel_data_type)

	c_image = C.clCreateImage3D(context.cl_context,
		C.cl_mem_flags(flags),
		&c_image_format,
		C.size_t(image_width),
		C.size_t(image_height),
		C.size_t(image_depth),
		C.size_t(image_row_pitch),
		C.size_t(image_slice_pitch),
		host_ptr,
		&c_errcode_ret)

	if errcode_ret != nil {
		*errcode_ret = CL_int(c_errcode_ret)
	}

	return CL_mem{c_image}
}
Exemplo n.º 20
0
Arquivo: lookup.go Projeto: CSUA/pushy
// TODO: properly attribute http://golang.org/src/pkg/os/user/lookup_unix.go (BSD-style: http://golang.org/LICENSE)
func GetGidByName(name string) (gid int, err error) {
	var group C.struct_group
	var result *C.struct_group

	var bufSize C.long
	bufSize = C.sysconf(C._SC_GETGR_R_SIZE_MAX)
	if bufSize <= 0 || bufSize > 1<<20 {
		log.Fatalf("ERROR: unreasonable _SC_GETGR_R_SIZE_MAX of %d", bufSize)
	}
	buf := C.malloc(C.size_t(bufSize))
	defer C.free(buf)

	var returnValue C.int
	nameC := C.CString(config.Group)
	defer C.free(unsafe.Pointer(nameC))
	returnValue = C.getgrnam_r(nameC,
		&group,
		(*C.char)(buf),
		C.size_t(bufSize),
		&result)
	if returnValue != 0 {
		return -1, fmt.Errorf("ERROR: error looking up group", name, syscall.Errno(returnValue))
	}
	if result == nil {
		return -1, UnknownLookupError(name)
	}
	gid = int(result.gr_gid)
	return
}
Exemplo n.º 21
0
// Remove the specified `keys` from the omap `oid`
func (ioctx *IOContext) RmOmapKeys(oid string, keys []string) error {
	c_oid := C.CString(oid)
	defer C.free(unsafe.Pointer(c_oid))

	var c *C.char
	ptrSize := unsafe.Sizeof(c)

	c_keys := C.malloc(C.size_t(len(keys)) * C.size_t(ptrSize))
	defer C.free(unsafe.Pointer(c_keys))

	i := 0
	for _, key := range keys {
		c_key_ptr := (**C.char)(unsafe.Pointer(uintptr(c_keys) + uintptr(i)*ptrSize))
		*c_key_ptr = C.CString(key)
		defer C.free(unsafe.Pointer(*c_key_ptr))
		i++
	}

	op := C.rados_create_write_op()
	C.rados_write_op_omap_rm_keys(
		op,
		(**C.char)(c_keys),
		C.size_t(len(keys)))

	ret := C.rados_write_op_operate(op, ioctx.ioctx, c_oid, nil, 0)
	C.rados_release_write_op(op)

	return GetRadosError(ret)
}
Exemplo n.º 22
0
// Changes the size of the canvas, returns true on success.
func (cv Canvas) Resize(width uint, height uint) bool {
	status := C.MagickResizeImage(cv.wand, C.size_t(width), C.size_t(height), C.GaussianFilter, C.double(1.0))
	if status == C.MagickFalse {
		return false
	}
	return true
}
Exemplo n.º 23
0
// Because Go is like... naaaaa, no groups aren't a thing!
// Based on Go's src/os/user/lookup_unix.go
func currentUserAndGroup() (*userAndGroup, error) {
	u, err := user.Current()
	if err != nil {
		return nil, err
	}
	gid, err := strconv.Atoi(u.Gid)
	if err != nil {
		return nil, err
	}

	var grp C.struct_group
	var result *C.struct_group
	buflen := C.sysconf(C._SC_GETPW_R_SIZE_MAX)
	if buflen <= 0 || buflen > 1<<20 {
		return nil, fmt.Errorf("unreasonable _SC_GETGR_R_SIZE_MAX of %d", buflen)
	}
	buf := C.malloc(C.size_t(buflen))
	defer C.free(buf)

	r := C.mygetgrgid_r(C.gid_t(gid), &grp,
		(*C.char)(buf),
		C.size_t(buflen),
		&result)
	if r != 0 {
		return nil, fmt.Errorf("lookup gid %d: %s", gid, syscall.Errno(r))
	}
	if result == nil {
		return nil, fmt.Errorf("lookup gid %d failed", gid)
	}

	return &userAndGroup{
		User:      u,
		Groupname: C.GoString(grp.gr_name),
	}, nil
}
Exemplo n.º 24
0
// Adaptively changes the size of the canvas, returns true on success.
func (cv Canvas) AdaptiveResize(width uint, height uint) bool {
	status := C.MagickAdaptiveResizeImage(cv.wand, C.size_t(width), C.size_t(height))
	if status == C.MagickFalse {
		return false
	}
	return true
}
Exemplo n.º 25
0
// GetApproximateSizes returns the approximate number of bytes of file system
// space used by one or more key ranges.
//
// The keys counted will begin at Range.Start and end on the key before
// Range.Limit.
func (db *DB) GetApproximateSizes(ranges []Range) []uint64 {
	starts := make([]*C.char, len(ranges))
	limits := make([]*C.char, len(ranges))
	startLens := make([]C.size_t, len(ranges))
	limitLens := make([]C.size_t, len(ranges))
	for i, r := range ranges {
		starts[i] = C.CString(string(r.Start))
		startLens[i] = C.size_t(len(r.Start))
		limits[i] = C.CString(string(r.Limit))
		limitLens[i] = C.size_t(len(r.Limit))
	}
	sizes := make([]uint64, len(ranges))
	numranges := C.int(len(ranges))
	startsPtr := &starts[0]
	limitsPtr := &limits[0]
	startLensPtr := &startLens[0]
	limitLensPtr := &limitLens[0]
	sizesPtr := (*C.uint64_t)(&sizes[0])
	C.hyperleveldb_rocksdb_approximate_sizes(
		db.Ldb, numranges, startsPtr, startLensPtr,
		limitsPtr, limitLensPtr, sizesPtr)
	for i := range ranges {
		C.free(unsafe.Pointer(starts[i]))
		C.free(unsafe.Pointer(limits[i]))
	}
	return sizes
}
Exemplo n.º 26
0
// Creates an empty canvas of the given dimensions.
func (cv Canvas) Blank(width uint, height uint) bool {
	status := C.MagickNewImage(cv.wand, C.size_t(width), C.size_t(height), cv.bg)
	if status == C.MagickFalse {
		return false
	}
	return true
}
Exemplo n.º 27
0
// The C side of things will still need to allocate memory, due to the slices.
// Assumes Configuration is valid.
func (config *Configuration) _CGO() *C.CGO_Configuration {
	INFO.Println("Converting Config: ", config)
	size := C.size_t(unsafe.Sizeof(C.CGO_Configuration{}))
	c := (*C.CGO_Configuration)(C.malloc(size))

	// Need to convert each IceServer struct individually.
	total := len(config.IceServers)
	if total > 0 {
		sizeof := unsafe.Sizeof(C.CGO_IceServer{})
		cServers := unsafe.Pointer(C.malloc(C.size_t(sizeof * uintptr(total))))
		ptr := uintptr(cServers)
		for _, server := range config.IceServers {
			*(*C.CGO_IceServer)(unsafe.Pointer(ptr)) = server._CGO()
			ptr += sizeof
		}
		c.iceServers = (*C.CGO_IceServer)(cServers)
	}
	c.numIceServers = C.int(total)

	// c.iceServers = (*C.CGO_IceServer)(unsafe.Pointer(&config.IceServers))
	c.iceTransportPolicy = C.int(config.IceTransportPolicy)
	c.bundlePolicy = C.int(config.BundlePolicy)
	// [ED] c.RtcpMuxPolicy = C.int(config.RtcpMuxPolicy)
	c.peerIdentity = C.CString(config.PeerIdentity)
	// [ED] c.Certificates = config.Certificates
	// [ED] c.IceCandidatePoolSize = C.int(config.IceCandidatePoolSize)
	return c
}
Exemplo n.º 28
0
// Extracts a region from the canvas.
func (cv Canvas) Crop(x int, y int, width uint, height uint) bool {
	status := C.MagickCropImage(cv.wand, C.size_t(width), C.size_t(height), C.ssize_t(x), C.ssize_t(y))
	if status == C.MagickFalse {
		return false
	}
	return true
}
Exemplo n.º 29
0
func (ic *Iconv) convert(input []byte, out io.Writer, outBuf []byte) (bytesConverted int, err error) {
	inputLen := len(input)
	if inputLen == 0 {
		return
	}

	outputLen := len(outBuf)
	if outputLen == 0 {
		outputLen = inputLen
		outBuf = make([]byte, outputLen)
	}

	outputPtr := &outBuf[0]
	outputPtrPtr := (**C.char)(unsafe.Pointer(&outputPtr))
	outputBytesLeft := C.size_t(outputLen)

	inputPtr := &input[0]
	inputPtrPtr := (**C.char)(unsafe.Pointer(&inputPtr))
	inputBytesLeft := C.size_t(inputLen)

	_, err = C.iconv(ic.pIconv, inputPtrPtr, &inputBytesLeft, outputPtrPtr, &outputBytesLeft)
	bytesConverted = inputLen - int(inputBytesLeft)
	if int(outputBytesLeft) < outputLen {
		out.Write(outBuf[:outputLen-int(outputBytesLeft)])
	}
	return
}
Exemplo n.º 30
0
// IteratorInit creates an iterator to traverse a ForestDB snapshot by key range
func (k *KVStore) IteratorInit(startKey, endKey []byte, opt IteratorOpt) (*Iterator, error) {
	k.Lock()
	defer k.Unlock()

	var sk, ek unsafe.Pointer

	lensk := len(startKey)
	lenek := len(endKey)

	if lensk != 0 {
		sk = unsafe.Pointer(&startKey[0])
	}

	if lenek != 0 {
		ek = unsafe.Pointer(&endKey[0])
	}

	rv := Iterator{db: k}
	Log.Tracef("fdb_iterator_init call k:%p db:%v sk:%v ek:%v opt:%v", k, k.db, sk, ek, opt)
	errNo := C.fdb_iterator_init(k.db, &rv.iter, sk, C.size_t(lensk), ek, C.size_t(lenek), C.fdb_iterator_opt_t(opt))
	Log.Tracef("fdb_iterator_init retn k:%p rv:%v", k, rv.iter)
	if errNo != RESULT_SUCCESS {
		return nil, Error(errNo)
	}
	return &rv, nil
}