Convert ctypes pointer to buffer type.
541219
def ctypes2buffer(cptr, length):
    """"""
    if not isinstance(cptr, ctypes.POINTER(ctypes.c_char)):
        raise RuntimeError('expected char pointer')
    res = bytearray(length)
    rptr = (ctypes.c_char * length).from_buffer(res)
    if not ctypes.memmove(rptr, cptr, length):
        raise RuntimeError('memmove failed')
    return res
661875
function bufferToArrayBuffer(buf) {
  const arr = new ArrayBuffer(buf.length);
  const view = new Uint8Array(arr);
  for (let i = 0; i < buf.length; ++i) {
    view[i] = buf[i];
  }
  return arr;
}
904932
def pytype_to_ctype(t):
    
    if isinstance(t, List):
        return 'pythonic::types::list<{0}>'.format(
            pytype_to_ctype(t.__args__[0])
        )
    elif isinstance(t, Set):
        return 'pythonic::types::set<{0}>'.format(
            pytype_to_ctype(t.__args__[0])
        )
    elif isinstance(t, Dict):
        tkey, tvalue = t.__args__
        return 'pythonic::types::dict<{0},{1}>'.format(pytype_to_ctype(tkey),
                                                       pytype_to_ctype(tvalue))
    elif isinstance(t, Tuple):
        return 'decltype(pythonic::types::make_tuple({0}))'.format(
            ", ".join('std::declval<{}>()'.format(pytype_to_ctype(p))
                      for p in t.__args__)
        )
    elif isinstance(t, NDArray):
        dtype = pytype_to_ctype(t.__args__[0])
        ndim = len(t.__args__) - 1
        shapes = ','.join(('long'
                           if s.stop == -1 or s.stop is None
                           else 'std::integral_constant<long, {}>'.format(
                               s.stop)
                           ) for s in t.__args__[1:])
        pshape = 'pythonic::types::pshape<{0}>'.format(shapes)
        arr = 'pythonic::types::ndarray<{0},{1}>'.format(
                    dtype, pshape)
        if t.__args__[1].start == -1:
            return 'pythonic::types::numpy_texpr<{0}>'.format(arr)
        elif any(s.step is not None and s.step < 0 for s in t.__args__[1:]):
            slices = ", ".join(['pythonic::types::normalized_slice'] * ndim)
            return 'pythonic::types::numpy_gexpr<{0},{1}>'.format(arr, slices)
        else:
            return arr
    elif isinstance(t, Pointer):
        return 'pythonic::types::pointer<{0}>'.format(
            pytype_to_ctype(t.__args__[0])
        )
    elif isinstance(t, Fun):
        return 'pythonic::types::cfun<{0}({1})>'.format(
            pytype_to_ctype(t.__args__[-1]),
            ", ".join(pytype_to_ctype(arg) for arg in t.__args__[:-1]),
        )
    elif t in PYTYPE_TO_CTYPE_TABLE:
        return PYTYPE_TO_CTYPE_TABLE[t]
    else:
        raise NotImplementedError("{0}:{1}".format(type(t), t))
961082
def to_bson(buffer = ByteBuffer.new, validating_keys = Config.validating_keys?)
      position = buffer.length
      buffer.put_int32(0)
      buffer.put_byte(SUBTYPES[type])
      buffer.put_int32(data.bytesize) if type == :old
      buffer.put_bytes(data.force_encoding(BINARY))
      buffer.replace_int32(position, buffer.length - position - 5)
    end
100788
def serialise(structure):
    
    return ctypes.cast(
        ctypes.pointer(structure),
        ctypes.POINTER(ctypes.c_char * ctypes.sizeof(structure)),
    ).contents
610508
function magicBuffer(buf, cb) {
  try {
    buf = bufferUtils.toBuffer(buf);
    magic(buf, cb);
  } catch(err) {
    cb(err);
  }
}
347404
def get_filetype_from_buffer(buf, max_lines=5):
    
    lines = buf.splitlines()
    for l in lines[-1:-max_lines-1:-1]:
        ret = get_filetype_from_line(l)
        if ret:
            return ret
    for i in range(max_lines, -1, -1):
        if i < len(lines):
            ret = get_filetype_from_line(lines[i])
            if ret:
                return ret

    return None
548332
def ctypes_parameter(self):
        
        if self._ctypes_parameter is None:
            #Essentially, we just need to check if we are an array that doesn't have explicitly
            #defined bounds. Assumed-shape arrays have to be 'pointer' or 'allocatable'. However,
            #the deffered/assumed shape arrays always use ':' as the array dimension.
            if self.dimension is not None and ":" in self.dimension:
                result = [self._get_ctypes_name()]
                result.extend([self._get_ctypes_name(i+1) for i in range(self.D)])
                if self.direction == "(inout)" and ("allocatable" in self.modifiers or
                                                    "pointer" in self.modifiers):
                    result.append("{}_o".format(self.name))
                self._ctypes_parameter = result
            elif self.dtype == "logical":
                self._ctypes_parameter = [self._get_ctypes_name()]
            elif hasattr(self, "parameters"):
                #This is the handler for the function return types that are simple
                self._ctypes_parameter = [self.name + "_f"]
            else:
                #Nothing special, just return the standard name.
                self._ctypes_parameter = [self.name]

        return self._ctypes_parameter
165540
def _legacy_bpf_pointer(tcpdump_lines):
    """"""
    X86_64 = os.uname()[4] in ['x86_64', 'aarch64']
    size = int(tcpdump_lines[0])
    bpf = b""
    for l in tcpdump_lines[1:]:
        if six.PY2:
            int_type = long  # noqa: F821
        else:
            int_type = int
        bpf += struct.pack("HBBI", *map(int_type, l.split()))

    # Thanks to http://www.netprojects.de/scapy-with-pypy-solved/ for the pypy trick  # noqa: E501
    if conf.use_pypy:
        str_buffer = ctypes.create_string_buffer(bpf)
        return struct.pack('HL', size, ctypes.addressof(str_buffer))
    else:
        # XXX. Argl! We need to give the kernel a pointer on the BPF,
        # Python object header seems to be 20 bytes. 36 bytes for x86 64bits arch.  # noqa: E501
        if X86_64:
            return struct.pack("HL", size, id(bpf) + 36)
        else:
            return struct.pack("HI", size, id(bpf) + 20)
1139145
def extern_type_to_str(self, context_handle, type_id):
    """"""
    c = self._ffi.from_handle(context_handle)
    return c.utf8_buf(text_type(c.from_id(type_id.tup_0).__name__))
467176
def extern_store_bytes(self, context_handle, bytes_ptr, bytes_len):
    """"""
    c = self._ffi.from_handle(context_handle)
    return c.to_value(binary_type(self._ffi.buffer(bytes_ptr, bytes_len)))
254276
def _ctypes_assign(parameter):
    
    #If the array is set to only have intent(out), we don't want to allocate or assign
    #a value to it; otherwise we do.
    if (parameter.direction != "(out)" and ("allocate" in parameter.modifiers
                                            or "pointer" in parameter.modifiers
                                            or "target" in parameter.modifiers)):
        if "in" in parameter.direction:
            splice = _ctypes_splice(parameter)
            result = []
            result.append("    allocate({}({}))".format(parameter.name, splice))
            result.append("    {0} = {0}_c".format(parameter.name))
            return ('\n'.join(result), True)
    elif parameter.dtype == "logical" and "in" in parameter.direction:
        return ("    {0} = {0}_c".format(parameter.name), False)
699791
def get_buffers_of_type(self, t):
        
        return [x for x in self.buffers if isinstance(x, t)]
1061049
function readType(buffer, type, size) {
  switch (type) {
    case types.BYTE:
      return buffer.readBytes(size);
    case types.CHAR:
      return trimNull(buffer.readChars(size));
    case types.SHORT:
      return readNumber(size, buffer.readInt16.bind(buffer));
    case types.INT:
      return readNumber(size, buffer.readInt32.bind(buffer));
    case types.FLOAT:
      return readNumber(size, buffer.readFloat32.bind(buffer));
    case types.DOUBLE:
      return readNumber(size, buffer.readFloat64.bind(buffer));
      /* istanbul ignore next */
    default:
      notNetcdf(true, `non valid type ${type}`);
      return undefined;
  }
}
1288104
def _ctypes_saved(parameter):
    
    if ("out" in parameter.direction and parameter.dimension is not None and
        ":" in parameter.dimension and ("allocatable" in parameter.modifiers or
                                        "pointer" in parameter.modifiers)):
        stype = _ctypes_dtype(parameter)
        name = "{}_t({})".format(parameter.name, parameter.dimension)
        return ("{}, allocatable, target, save :: {}".format(stype, name), True)
1108057
def pytype_to_deps_hpp(t):
    """"""
    if isinstance(t, List):
        return {'list.hpp'}.union(pytype_to_deps_hpp(t.__args__[0]))
    elif isinstance(t, Set):
        return {'set.hpp'}.union(pytype_to_deps_hpp(t.__args__[0]))
    elif isinstance(t, Dict):
        tkey, tvalue = t.__args__
        return {'dict.hpp'}.union(pytype_to_deps_hpp(tkey),
                                  pytype_to_deps_hpp(tvalue))
    elif isinstance(t, Tuple):
        return {'tuple.hpp'}.union(*[pytype_to_deps_hpp(elt)
                                     for elt in t.__args__])
    elif isinstance(t, NDArray):
        out = {'ndarray.hpp'}
        # it's a transpose!
        if t.__args__[1].start == -1:
            out.add('numpy_texpr.hpp')
        return out.union(pytype_to_deps_hpp(t.__args__[0]))
    elif isinstance(t, Pointer):
        return {'pointer.hpp'}.union(pytype_to_deps_hpp(t.__args__[0]))
    elif isinstance(t, Fun):
        return {'cfun.hpp'}.union(*[pytype_to_deps_hpp(a) for a in t.__args__])
    elif t in PYTYPE_TO_CTYPE_TABLE:
        return {'{}.hpp'.format(t.__name__)}
    else:
        raise NotImplementedError("{0}:{1}".format(type(t), t))
259653
def db_type(cls, dtype):
        """"""
        if isinstance(dtype, ExtensionDtype):
            return cls.type_map.get(dtype.kind)
        elif hasattr(dtype, 'char'):
            return cls.type_map.get(dtype.char)