Beispiel #1
0
 def test_keypresses(self):
     if not self.is_interactive:
         py.test.skip("interactive test only")
     RSDL.EnableUNICODE(1)
     print
     print "Keys pressed in the Pygame window should be printed below."
     print "    Use Escape to quit."
     event = lltype.malloc(RSDL.Event, flavor='raw')
     try:
         while True:
                 ok = RSDL.WaitEvent(event)
                 assert rffi.cast(lltype.Signed, ok) == 1
                 c_type = rffi.getintfield(event, 'c_type')
                 if c_type == RSDL.KEYDOWN:
                     p = rffi.cast(RSDL.KeyboardEventPtr, event)
                     if rffi.getintfield(p.c_keysym, 'c_sym') == RSDL.K_ESCAPE:
                         print 'Escape key'
                         break
                     char = rffi.getintfield(p.c_keysym, 'c_unicode')
                     if char != 0:
                         print 'Key:', unichr(char).encode('utf-8')
                     else:
                         print 'Some special key'
                 else:
                     print '(event of type %d)' % c_type
     finally:
         lltype.free(event, flavor='raw')
def set_pixel(image, x, y, pixel):
    """Return the pixel value at (x, y)
    NOTE: The surface must be locked before calling this!
    """
    bpp = rffi.getintfield(image.c_format, 'c_BytesPerPixel')
    pitch = rffi.getintfield(image, 'c_pitch')
    # Here p is the address to the pixel we want to retrieve
    p = rffi.ptradd(image.c_pixels, y * pitch + x * bpp)
    if bpp == 1:
        p[0] = rffi.cast(rffi.UCHAR,pixel)
    elif bpp == 2:
        p = rffi.cast(RSDL.Uint16P, p)
        p[0] = rffi.cast(RSDL.Uint16,pixel) 
    elif bpp == 3:
        if RSDL.BYTEORDER == RSDL.BIG_ENDIAN:
            p[0] = rffi.cast(rffi.UCHAR,(pixel >> 16) & 0xFF)
            p[1] = rffi.cast(rffi.UCHAR,(pixel >> 8 ) & 0xFF)
            p[2] = rffi.cast(rffi.UCHAR,pixel & 0xFF)
        else:
            p[0] = rffi.cast(rffi.UCHAR,pixel & 0xFF)
            p[1] = rffi.cast(rffi.UCHAR,(pixel >> 8 ) & 0xFF)
            p[2] = rffi.cast(rffi.UCHAR,(pixel >> 16) & 0xFF)
    elif bpp == 4:
        p = rffi.cast(RSDL.Uint32P, p)
        p[0] = rffi.cast(RSDL.Uint32, pixel)
    else:
        raise ValueError("bad BytesPerPixel")
Beispiel #3
0
    def _sem_timedwait_save(sem, deadline):
        delay = 0
        void = lltype.nullptr(rffi.VOIDP.TO)
        with lltype.scoped_alloc(TIMEVALP.TO, 1) as tvdeadline:
            while True:
                # poll
                if _sem_trywait(sem) == 0:
                    return 0
                elif rposix.get_errno() != errno.EAGAIN:
                    return -1

                now = gettimeofday()
                c_tv_sec = rffi.getintfield(deadline[0], 'c_tv_sec')
                c_tv_nsec = rffi.getintfield(deadline[0], 'c_tv_nsec')
                if (c_tv_sec < now[0]
                        or (c_tv_sec == now[0] and c_tv_nsec <= now[1])):
                    rposix.set_errno(errno.ETIMEDOUT)
                    return -1

                # calculate how much time is left
                difference = ((c_tv_sec - now[0]) * 1000000 +
                              (c_tv_nsec - now[1]))

                # check delay not too long -- maximum is 20 msecs
                if delay > 20000:
                    delay = 20000
                if delay > difference:
                    delay = difference
                delay += 1000

                # sleep
                rffi.setintfield(tvdeadline[0], 'c_tv_sec', delay / 1000000)
                rffi.setintfield(tvdeadline[0], 'c_tv_usec', delay % 1000000)
                if _select(0, void, void, void, tvdeadline) < 0:
                    return -1
Beispiel #4
0
def set_pixel(image, x, y, pixel):
    """Return the pixel value at (x, y)
    NOTE: The surface must be locked before calling this!
    """
    bpp = rffi.getintfield(image.c_format, 'c_BytesPerPixel')
    pitch = rffi.getintfield(image, 'c_pitch')
    # Here p is the address to the pixel we want to retrieve
    p = rffi.ptradd(image.c_pixels, y * pitch + x * bpp)
    if bpp == 1:
        p[0] = rffi.cast(rffi.UCHAR, pixel)
    elif bpp == 2:
        p = rffi.cast(RSDL.Uint16P, p)
        p[0] = rffi.cast(RSDL.Uint16, pixel)
    elif bpp == 3:
        if RSDL.BYTEORDER == RSDL.BIG_ENDIAN:
            p[0] = rffi.cast(rffi.UCHAR, (pixel >> 16) & 0xFF)
            p[1] = rffi.cast(rffi.UCHAR, (pixel >> 8) & 0xFF)
            p[2] = rffi.cast(rffi.UCHAR, pixel & 0xFF)
        else:
            p[0] = rffi.cast(rffi.UCHAR, pixel & 0xFF)
            p[1] = rffi.cast(rffi.UCHAR, (pixel >> 8) & 0xFF)
            p[2] = rffi.cast(rffi.UCHAR, (pixel >> 16) & 0xFF)
    elif bpp == 4:
        p = rffi.cast(RSDL.Uint32P, p)
        p[0] = rffi.cast(RSDL.Uint32, pixel)
    else:
        raise ValueError("bad BytesPerPixel")
Beispiel #5
0
 def test_mousemove(self):
     if not self.is_interactive:
         py.test.skip("interactive test only")
     print
     print "Move the Mouse up and down:"
     print "    Use Escape to quit."
     event = lltype.malloc(RSDL.Event, flavor="raw")
     directions = [False]*4
     try:
         while True:
             ok = RSDL.WaitEvent(event)
             assert rffi.cast(lltype.Signed, ok) == 1
             c_type = rffi.getintfield(event, "c_type")
             if c_type == RSDL.MOUSEMOTION:
                 m = rffi.cast(RSDL.MouseMotionEventPtr, event)
                 assert rffi.getintfield(m, "c_x") >= 0
                 assert rffi.getintfield(m, "c_y") >= 0
                 print rffi.getintfield(m, "c_xrel")
                 directions[0] |= rffi.getintfield(m, "c_xrel")>0
                 directions[1] |= rffi.getintfield(m, "c_xrel")<0
                 directions[2] |= rffi.getintfield(m, "c_yrel")>0
                 directions[3] |= rffi.getintfield(m, "c_yrel")<0
                 if False not in directions:
                     break
             elif c_type == RSDL.KEYUP:
                 p = rffi.cast(RSDL.KeyboardEventPtr, event)
                 if rffi.getintfield(p.c_keysym, 'c_sym') == RSDL.K_ESCAPE:
                     print "    test manually aborted"
                     py.test.fail(" mousemovement test aborted")
                     break  
     finally:
         lltype.free(event, flavor='raw')
Beispiel #6
0
 def test_poll(self):
     if not self.is_interactive:
         py.test.skip("interactive test only")
     import time, sys
     RSDL.EnableUNICODE(1)
     print
     print "Keys pressed in the Pygame window give a dot."
     print "    Wait 3 seconds to quit."
     timeout = time.time() + 3
     event = lltype.malloc(RSDL.Event, flavor='raw')
     try:
         while True:
             # busy polling
             ok = RSDL.PollEvent(event)
             ok = rffi.cast(lltype.Signed, ok)
             assert ok >= 0
             if ok > 0:
                 c_type = rffi.getintfield(event, 'c_type')
                 if c_type == RSDL.KEYDOWN:
                     sys.stderr.write('.')
                     p = rffi.cast(RSDL.KeyboardEventPtr, event)
                     if rffi.getintfield(p.c_keysym, 'c_sym') == RSDL.K_ESCAPE:
                         print 'Escape key'
                         break
                     timeout = time.time() + 3
             else:
                 if time.time() > timeout:
                     break
             time.sleep(0.05)
     finally:
         lltype.free(event, flavor='raw')
Beispiel #7
0
def get_pixel(image, x, y):
    """Return the pixel value at (x, y)
    NOTE: The surface must be locked before calling this!
    """
    bpp = rffi.getintfield(image.c_format, 'c_BytesPerPixel')
    pitch = rffi.getintfield(image, 'c_pitch')
    # Here p is the address to the pixel we want to retrieve
    p = rffi.ptradd(image.c_pixels, y * pitch + x * bpp)
    if bpp == 1:
        return rffi.cast(RSDL.Uint32, p[0])
    elif bpp == 2:
        p = rffi.cast(RSDL.Uint16P, p)
        return rffi.cast(RSDL.Uint32, p[0])
    elif bpp == 3:
        p0 = rffi.cast(lltype.Signed, p[0])
        p1 = rffi.cast(lltype.Signed, p[1])
        p2 = rffi.cast(lltype.Signed, p[2])
        if RSDL.BYTEORDER == RSDL.BIG_ENDIAN:
            result = p0 << 16 | p1 << 8 | p2
        else:
            result = p0 | p1 << 8 | p2 << 16
        return rffi.cast(RSDL.Uint32, result)
    elif bpp == 4:
        p = rffi.cast(RSDL.Uint32P, p)
        return p[0]
    else:
        raise ValueError("bad BytesPerPixel")
Beispiel #8
0
 def check_for_escape(self):
     c_type = rffi.getintfield(self.event, 'c_type')
     if c_type == RSDL.KEYDOWN:
         p = rffi.cast(RSDL.KeyboardEventPtr, self.event)
         if rffi.getintfield(p.c_keysym, 'c_sym') == RSDL.K_ESCAPE:
             return True
     return False
Beispiel #9
0
def test_load_image():
    for filename in ["demo.jpg", "demo.png"]:
        image = RIMG.Load(os.path.join(autopath.this_dir, filename))
        assert image
        assert rffi.getintfield(image, 'c_w') == 17
        assert rffi.getintfield(image, 'c_h') == 23
        RSDL.FreeSurface(image)
Beispiel #10
0
def get_pixel(image, x, y):
    """Return the pixel value at (x, y)
    NOTE: The surface must be locked before calling this!
    """
    bpp = rffi.getintfield(image.c_format, 'c_BytesPerPixel')
    pitch = rffi.getintfield(image, 'c_pitch')
    # Here p is the address to the pixel we want to retrieve
    p = rffi.ptradd(image.c_pixels, y * pitch + x * bpp)
    if bpp == 1:
        return rffi.cast(RSDL.Uint32, p[0])
    elif bpp == 2:
        p = rffi.cast(RSDL.Uint16P, p)
        return rffi.cast(RSDL.Uint32, p[0])
    elif bpp == 3:
        p0 = rffi.cast(lltype.Signed, p[0])
        p1 = rffi.cast(lltype.Signed, p[1])
        p2 = rffi.cast(lltype.Signed, p[2])
        if RSDL.BYTEORDER == RSDL.BIG_ENDIAN:
            result = p0 << 16 | p1 << 8 | p2
        else:
            result = p0 | p1 << 8 | p2 << 16
        return rffi.cast(RSDL.Uint32, result)
    elif bpp == 4:
        p = rffi.cast(RSDL.Uint32P, p)
        return p[0]
    else:
        raise ValueError("bad BytesPerPixel")
def test_load_image():
    for filename in ["demo.jpg", "demo.png"]:
        image = RIMG.Load(os.path.join(autopath.this_dir, filename))
        assert image
        assert rffi.getintfield(image, 'c_w') == 17
        assert rffi.getintfield(image, 'c_h') == 23
        RSDL.FreeSurface(image)
Beispiel #12
0
 def gettimeofday():
     now = lltype.malloc(TIMEVALP.TO, 1, flavor='raw')
     try:
         res = _gettimeofday(now, None)
         if res < 0:
             raise OSError(rposix.get_errno(), "gettimeofday failed")
         return rffi.getintfield(now[0], 'c_tv_sec'), rffi.getintfield(now[0], 'c_tv_usec')
     finally:
         lltype.free(now, flavor='raw')
Beispiel #13
0
 def check_for_escape(self):
     if not constants.USE_RSDL: return False
     c_type = rffi.getintfield(self.event, 'c_type')
     if c_type == RSDL.KEYDOWN:
         p = rffi.cast(RSDL.KeyboardEventPtr, self.event)
         if rffi.getintfield(p.c_keysym, 'c_sym') == RSDL.K_ESCAPE:
             return True
     elif c_type == RSDL.QUIT:
         return True
     return False
Beispiel #14
0
 def gettimeofday():
     now = lltype.malloc(TIMEVALP.TO, 1, flavor='raw')
     try:
         res = _gettimeofday(now, None)
         if res < 0:
             raise OSError(rposix.get_errno(), "gettimeofday failed")
         return rffi.getintfield(now[0], 'c_tv_sec'), rffi.getintfield(
             now[0], 'c_tv_usec')
     finally:
         lltype.free(now, flavor='raw')
Beispiel #15
0
def test_surface_basic():
    assert RSDL.Init(RSDL.INIT_VIDEO) >= 0
    surface = RSDL.CreateRGBSurface(0, 150, 50, 32, r_uint(0x000000FF),
                                    r_uint(0x0000FF00), r_uint(0x00FF0000),
                                    r_uint(0xFF000000))
    assert surface
    assert rffi.getintfield(surface, 'c_w') == 150
    assert rffi.getintfield(surface, 'c_h') == 50
    RSDL.FreeSurface(surface)
    RSDL.Quit()
Beispiel #16
0
    def flush(self):
        if not self.running:
            raise OperationError(
                self.space.w_ValueError,
                self.space.wrap("this object was already flushed"))
        self.running = False

        out_bufsize = SMALLCHUNK
        out_buf = lltype.malloc(rffi.CCHARP.TO,
                                out_bufsize,
                                flavor='raw',
                                zero=True)

        try:

            self.bzs.c_next_out = out_buf
            rffi.setintfield(self.bzs, 'c_avail_out', out_bufsize)

            total_out = _bzs_total_out(self.bzs)

            temp = []
            while True:
                bzerror = BZ2_bzCompress(self.bzs, BZ_FINISH)
                if bzerror == BZ_STREAM_END:
                    break
                elif bzerror != BZ_FINISH_OK:
                    _catch_bz2_error(self.space, bzerror)

                if rffi.getintfield(self.bzs, 'c_avail_out') == 0:
                    data = "".join(
                        [out_buf[i] for i in range(_bzs_total_out(self.bzs))])
                    temp.append(data)

                    out_bufsize = _new_buffer_size(out_bufsize)
                    out_buf = lltype.malloc(rffi.CCHARP.TO,
                                            out_bufsize,
                                            flavor='raw',
                                            zero=True)
                    self.bzs.c_next_out = out_buf
                    rffi.setintfield(self.bzs, 'c_avail_out', out_bufsize)

            if temp:
                return self.space.wrap("".join(temp))

            if rffi.getintfield(self.bzs, 'c_avail_out'):
                size = _bzs_total_out(self.bzs) - total_out
                res = "".join([out_buf[i] for i in range(size)])
                return self.space.wrap(res)

            total_out = _bzs_total_out(self.bzs)
            res = "".join([out_buf[i] for i in range(total_out)])
            return self.space.wrap(res)
        finally:
            lltype.free(out_buf, flavor='raw')
Beispiel #17
0
def test_surface_basic():
    assert RSDL.Init(RSDL.INIT_VIDEO) >= 0
    surface = RSDL.CreateRGBSurface(0, 150, 50, 32,
                                    r_uint(0x000000FF),
                                    r_uint(0x0000FF00),
                                    r_uint(0x00FF0000),
                                    r_uint(0xFF000000))
    assert surface
    assert rffi.getintfield(surface, 'c_w') == 150
    assert rffi.getintfield(surface, 'c_h') == 50
    RSDL.FreeSurface(surface)
    RSDL.Quit()
Beispiel #18
0
    def flush(self):
        if not self.running:
            raise OperationError(self.space.w_ValueError,
                self.space.wrap("this object was already flushed"))
        self.running = False
        
        out_bufsize = SMALLCHUNK
        out_buf = lltype.malloc(rffi.CCHARP.TO, out_bufsize, flavor='raw',
                                zero=True)

        try:
    
            self.bzs.c_next_out = out_buf
            rffi.setintfield(self.bzs, 'c_avail_out', out_bufsize)
        
            total_out = _bzs_total_out(self.bzs)
            
            temp = []
            while True:
                bzerror = BZ2_bzCompress(self.bzs, BZ_FINISH)
                if bzerror == BZ_STREAM_END:
                    break
                elif bzerror != BZ_FINISH_OK:
                    _catch_bz2_error(self.space, bzerror)
                
                if rffi.getintfield(self.bzs, 'c_avail_out') == 0:
                    data = "".join([out_buf[i] for i in range(_bzs_total_out(self.bzs))])
                    temp.append(data)
                    
                    out_bufsize = _new_buffer_size(out_bufsize)
                    out_buf = lltype.malloc(rffi.CCHARP.TO, out_bufsize,
                                            flavor='raw', zero=True)
                    self.bzs.c_next_out = out_buf
                    rffi.setintfield(self.bzs, 'c_avail_out', out_bufsize)
        

            if rffi.getintfield(self.bzs, 'c_avail_out'):
                size = _bzs_total_out(self.bzs) - total_out
                res = "".join([out_buf[i] for i in range(size)])
            else:
                total_out = _bzs_total_out(self.bzs)
                res = "".join([out_buf[i] for i in range(total_out)])
            if not temp:
                return self.space.wrap(res)
            else:
                temp.append(res)
                return self.space.wrap("".join(temp))
        finally:
            lltype.free(out_buf, flavor='raw')
Beispiel #19
0
def test_image_pixels():
    for filename in ["demo.jpg", "demo.png"]:
        image = RIMG.Load(os.path.join(autopath.this_dir, filename))
        assert image
        assert rffi.getintfield(image.c_format, 'c_BytesPerPixel') in (3, 4)
        RSDL.LockSurface(image)
        result = {}
        try:
            rgb = lltype.malloc(rffi.CArray(RSDL.Uint8), 3, flavor='raw')
            try:
                for y in range(23):
                    for x in range(y % 13, 17, 13):
                        color = RSDL_helper.get_pixel(image, x, y)
                        RSDL.GetRGB(color, image.c_format, rffi.ptradd(rgb, 0),
                                    rffi.ptradd(rgb, 1), rffi.ptradd(rgb, 2))
                        r = rffi.cast(lltype.Signed, rgb[0])
                        g = rffi.cast(lltype.Signed, rgb[1])
                        b = rffi.cast(lltype.Signed, rgb[2])
                        result[x, y] = r, g, b
            finally:
                lltype.free(rgb, flavor='raw')
        finally:
            RSDL.UnlockSurface(image)
        RSDL.FreeSurface(image)
        for x, y in result:
            f = (x * 17 + y * 23) / float(17 * 17 + 23 * 23)
            expected_r = int(255.0 * (1.0 - f))
            expected_g = 0
            expected_b = int(255.0 * f)
            r, g, b = result[x, y]
            assert abs(r - expected_r) < 10
            assert abs(g - expected_g) < 10
            assert abs(b - expected_b) < 10
Beispiel #20
0
def gethost_common(hostname, hostent, addr=None):
    if not hostent:
        raise HSocketError(hostname)
    family = rffi.getintfield(hostent, 'c_h_addrtype')
    if addr is not None and addr.family != family:
        raise CSocketError(_c.EAFNOSUPPORT)

    h_aliases = hostent.c_h_aliases
    if h_aliases:  # h_aliases can be NULL, according to SF #1511317
        aliases = rffi.charpp2liststr(h_aliases)
    else:
        aliases = []

    address_list = []
    h_addr_list = hostent.c_h_addr_list
    i = 0
    paddr = h_addr_list[0]
    while paddr:
        if family == AF_INET:
            p = rffi.cast(lltype.Ptr(_c.in_addr), paddr)
            addr = INETAddress.from_in_addr(p)
        elif AF_INET6 is not None and family == AF_INET6:
            p = rffi.cast(lltype.Ptr(_c.in6_addr), paddr)
            addr = INET6Address.from_in6_addr(p)
        else:
            raise RSocketError("unknown address family")
        address_list.append(addr)
        i += 1
        paddr = h_addr_list[i]
    return (rffi.charp2str(hostent.c_h_name), aliases, address_list)
Beispiel #21
0
def gethost_common(hostname, hostent, addr=None):
    if not hostent:
        raise HSocketError(hostname)
    family = rffi.getintfield(hostent, 'c_h_addrtype')
    if addr is not None and addr.family != family:
        raise CSocketError(_c.EAFNOSUPPORT)

    h_aliases = hostent.c_h_aliases
    if h_aliases:   # h_aliases can be NULL, according to SF #1511317
        aliases = rffi.charpp2liststr(h_aliases)
    else:
        aliases = []

    address_list = []
    h_addr_list = hostent.c_h_addr_list
    i = 0
    paddr = h_addr_list[0]
    while paddr:
        if family == AF_INET:
            p = rffi.cast(lltype.Ptr(_c.in_addr), paddr)
            addr = INETAddress.from_in_addr(p)
        elif AF_INET6 is not None and family == AF_INET6:
            p = rffi.cast(lltype.Ptr(_c.in6_addr), paddr)
            addr = INET6Address.from_in6_addr(p)
        else:
            raise RSocketError("unknown address family")
        address_list.append(addr)
        i += 1
        paddr = h_addr_list[i]
    return (rffi.charp2str(hostent.c_h_name), aliases, address_list)
Beispiel #22
0
 def make_result_string(self):
     count_unoccupied = rffi.getintfield(self.bzs, 'c_avail_out')
     s = self._get_chunk(self.current_size - count_unoccupied)
     if self.temp:
         self.temp.append(s)
         return ''.join(self.temp)
     else:
         return s
Beispiel #23
0
    def decompress(self, data):
        """decompress(data) -> string

        Provide more data to the decompressor object. It will return chunks
        of decompressed data whenever possible. If you try to decompress data
        after the end of stream is found, EOFError will be raised. If any data
        was found after the end of stream, it'll be ignored and saved in
        unused_data attribute."""

        if data == '':
            return self.space.wrap('')
        if not self.running:
            raise OperationError(
                self.space.w_EOFError,
                self.space.wrap("end of stream was already found"))

        in_bufsize = len(data)

        with lltype.scoped_alloc(rffi.CCHARP.TO, in_bufsize) as in_buf:
            for i in range(in_bufsize):
                in_buf[i] = data[i]
            self.bzs.c_next_in = in_buf
            rffi.setintfield(self.bzs, 'c_avail_in', in_bufsize)

            with OutBuffer(self.bzs) as out:
                while True:
                    bzerror = BZ2_bzDecompress(self.bzs)
                    if bzerror == BZ_STREAM_END:
                        if rffi.getintfield(self.bzs, 'c_avail_in') != 0:
                            unused = [
                                self.bzs.c_next_in[i] for i in range(
                                    rffi.getintfield(self.bzs, 'c_avail_in'))
                            ]
                            self.unused_data = "".join(unused)
                        self.running = False
                        break
                    if bzerror != BZ_OK:
                        _catch_bz2_error(self.space, bzerror)

                    if rffi.getintfield(self.bzs, 'c_avail_in') == 0:
                        break
                    elif rffi.getintfield(self.bzs, 'c_avail_out') == 0:
                        out.prepare_next_chunk()

                res = out.make_result_string()
                return self.space.wrap(res)
Beispiel #24
0
    def decompress(self, data):
        """decompress(data) -> string

        Provide more data to the decompressor object. It will return chunks
        of decompressed data whenever possible. If you try to decompress data
        after the end of stream is found, EOFError will be raised. If any data
        was found after the end of stream, it'll be ignored and saved in
        unused_data attribute."""

        if data == '':
            return self.space.wrap('')
        if not self.running:
            raise OperationError(self.space.w_EOFError,
                self.space.wrap("end of stream was already found"))

        in_bufsize = len(data)

        with lltype.scoped_alloc(rffi.CCHARP.TO, in_bufsize) as in_buf:
            for i in range(in_bufsize):
                in_buf[i] = data[i]
            self.bzs.c_next_in = in_buf
            rffi.setintfield(self.bzs, 'c_avail_in', in_bufsize)

            with OutBuffer(self.bzs) as out:
                while True:
                    bzerror = BZ2_bzDecompress(self.bzs)
                    if bzerror == BZ_STREAM_END:
                        if rffi.getintfield(self.bzs, 'c_avail_in') != 0:
                            unused = [self.bzs.c_next_in[i]
                                      for i in range(
                                          rffi.getintfield(self.bzs,
                                                           'c_avail_in'))]
                            self.unused_data = "".join(unused)
                        self.running = False
                        break
                    if bzerror != BZ_OK:
                        _catch_bz2_error(self.space, bzerror)

                    if rffi.getintfield(self.bzs, 'c_avail_in') == 0:
                        break
                    elif rffi.getintfield(self.bzs, 'c_avail_out') == 0:
                        out.prepare_next_chunk()

                res = out.make_result_string()
                return self.space.wrap(res)
Beispiel #25
0
def _tm_to_tuple(space, t):
    time_tuple = [
        space.wrap(rffi.getintfield(t, 'c_tm_year') + 1900),
        space.wrap(rffi.getintfield(t, 'c_tm_mon') + 1), # want january == 1
        space.wrap(rffi.getintfield(t, 'c_tm_mday')),
        space.wrap(rffi.getintfield(t, 'c_tm_hour')),
        space.wrap(rffi.getintfield(t, 'c_tm_min')),
        space.wrap(rffi.getintfield(t, 'c_tm_sec')),
        space.wrap((rffi.getintfield(t, 'c_tm_wday') + 6) % 7), # want monday == 0
        space.wrap(rffi.getintfield(t, 'c_tm_yday') + 1), # want january, 1 == 1
        space.wrap(rffi.getintfield(t, 'c_tm_isdst'))]

    w_struct_time = _get_module_object(space, 'struct_time')
    w_time_tuple = space.newtuple(time_tuple)
    return space.call_function(w_struct_time, w_time_tuple)
def _tm_to_tuple(space, t):
    time_tuple = [
        space.wrap(rffi.getintfield(t, 'c_tm_year') + 1900),
        space.wrap(rffi.getintfield(t, 'c_tm_mon') + 1), # want january == 1
        space.wrap(rffi.getintfield(t, 'c_tm_mday')),
        space.wrap(rffi.getintfield(t, 'c_tm_hour')),
        space.wrap(rffi.getintfield(t, 'c_tm_min')),
        space.wrap(rffi.getintfield(t, 'c_tm_sec')),
        space.wrap((rffi.getintfield(t, 'c_tm_wday') + 6) % 7), # want monday == 0
        space.wrap(rffi.getintfield(t, 'c_tm_yday') + 1), # want january, 1 == 1
        space.wrap(rffi.getintfield(t, 'c_tm_isdst'))]
    
    w_struct_time = _get_module_object(space, 'struct_time')
    w_time_tuple = space.newtuple(time_tuple)
    return space.call_function(w_struct_time, w_time_tuple)
Beispiel #27
0
 def update(self, event):
     if not constants.USE_RSDL: return 
     # fetch the event from sdl
     type = rffi.getintfield(event, 'c_type')
     if type == RSDL.KEYDOWN:
         self.create_called_key(event)
         self.on_key_down()
     elif type == RSDL.KEYUP:
         self.create_called_key(event)
         self.on_key_up()
Beispiel #28
0
 def update(self, event):
     # fetch the event from sdl
     type = rffi.getintfield(event, 'c_type')
     if type == RSDL.KEYDOWN:
         self.create_called_key(event)
         self.on_key_down()
     elif type == RSDL.KEYUP:
         self.create_called_key(event)
         self.on_key_up()
     pass
Beispiel #29
0
    def semlock_acquire(self, space, block, w_timeout):
        if not block:
            deadline = lltype.nullptr(TIMESPECP.TO)
        elif space.is_w(w_timeout, space.w_None):
            deadline = lltype.nullptr(TIMESPECP.TO)
        else:
            timeout = space.float_w(w_timeout)
            sec = int(timeout)
            nsec = int(1e9 * (timeout - sec) + 0.5)

            now_sec, now_usec = gettimeofday()

            deadline = lltype.malloc(TIMESPECP.TO, 1, flavor='raw')
            rffi.setintfield(deadline[0], 'c_tv_sec', now_sec + sec)
            rffi.setintfield(deadline[0], 'c_tv_nsec', now_usec * 1000 + nsec)
            val = rffi.getintfield(deadline[0], 'c_tv_sec') + \
                                rffi.getintfield(deadline[0], 'c_tv_nsec') / 1000000000
            rffi.setintfield(deadline[0], 'c_tv_sec', val)
            val = rffi.getintfield(deadline[0], 'c_tv_nsec') % 1000000000
            rffi.setintfield(deadline[0], 'c_tv_nsec', val)
        try:
            while True:
                try:
                    if not block:
                        sem_trywait(self.handle)
                    elif not deadline:
                        sem_wait(self.handle)
                    else:
                        sem_timedwait(self.handle, deadline)
                except OSError, e:
                    if e.errno == errno.EINTR:
                        # again
                        continue
                    elif e.errno in (errno.EAGAIN, errno.ETIMEDOUT):
                        return False
                    raise
                _check_signals(space)

                return True
        finally:
            if deadline:
                lltype.free(deadline, flavor='raw')
Beispiel #30
0
    def semlock_acquire(self, space, block, w_timeout):
        if not block:
            deadline = lltype.nullptr(TIMESPECP.TO)
        elif space.is_w(w_timeout, space.w_None):
            deadline = lltype.nullptr(TIMESPECP.TO)
        else:
            timeout = space.float_w(w_timeout)
            sec = int(timeout)
            nsec = int(1e9 * (timeout - sec) + 0.5)

            now_sec, now_usec = gettimeofday()

            deadline = lltype.malloc(TIMESPECP.TO, 1, flavor='raw')
            rffi.setintfield(deadline[0], 'c_tv_sec', now_sec + sec)
            rffi.setintfield(deadline[0], 'c_tv_nsec', now_usec * 1000 + nsec)
            val = rffi.getintfield(deadline[0], 'c_tv_sec') + \
                                rffi.getintfield(deadline[0], 'c_tv_nsec') / 1000000000
            rffi.setintfield(deadline[0], 'c_tv_sec', val)
            val = rffi.getintfield(deadline[0], 'c_tv_nsec') % 1000000000
            rffi.setintfield(deadline[0], 'c_tv_nsec', val)
        try:
            while True:
                try:
                    if not block:
                        sem_trywait(self.handle)
                    elif not deadline:
                        sem_wait(self.handle)
                    else:
                        sem_timedwait(self.handle, deadline)
                except OSError, e:
                    if e.errno == errno.EINTR:
                        # again
                        continue
                    elif e.errno in (errno.EAGAIN, errno.ETIMEDOUT):
                        return False
                    raise
                _check_signals(space)

                return True
        finally:
            if deadline:
                lltype.free(deadline, flavor='raw')
Beispiel #31
0
    def compress(self, data):
        """compress(data) -> string

        Provide more data to the compressor object. It will return chunks of
        compressed data whenever possible. When you've finished providing data
        to compress, call the flush() method to finish the compression process,
        and return what is left in the internal buffers."""

        datasize = len(data)

        if datasize == 0:
            return self.space.wrap("")

        if not self.running:
            raise OperationError(
                self.space.w_ValueError,
                self.space.wrap("this object was already flushed"))

        in_bufsize = datasize

        with OutBuffer(self.bzs) as out:
            with lltype.scoped_alloc(rffi.CCHARP.TO, in_bufsize) as in_buf:

                for i in range(datasize):
                    in_buf[i] = data[i]

                self.bzs.c_next_in = in_buf
                rffi.setintfield(self.bzs, 'c_avail_in', in_bufsize)

                while True:
                    bzerror = BZ2_bzCompress(self.bzs, BZ_RUN)
                    if bzerror != BZ_RUN_OK:
                        _catch_bz2_error(self.space, bzerror)

                    if rffi.getintfield(self.bzs, 'c_avail_in') == 0:
                        break
                    elif rffi.getintfield(self.bzs, 'c_avail_out') == 0:
                        out.prepare_next_chunk()

                res = out.make_result_string()
                return self.space.wrap(res)
Beispiel #32
0
def decompress(space, data):
    """decompress(data) -> decompressed data

    Decompress data in one shot. If you want to decompress data sequentially,
    use an instance of BZ2Decompressor instead."""

    in_bufsize = len(data)
    if in_bufsize == 0:
        return space.wrap("")

    with lltype.scoped_alloc(bz_stream.TO, zero=True) as bzs:
        with lltype.scoped_alloc(rffi.CCHARP.TO, in_bufsize) as in_buf:
            for i in range(in_bufsize):
                in_buf[i] = data[i]
            bzs.c_next_in = in_buf
            rffi.setintfield(bzs, 'c_avail_in', in_bufsize)

            with OutBuffer(bzs) as out:
                bzerror = BZ2_bzDecompressInit(bzs, 0, 0)
                if bzerror != BZ_OK:
                    _catch_bz2_error(space, bzerror)

                while True:
                    bzerror = BZ2_bzDecompress(bzs)
                    if bzerror == BZ_STREAM_END:
                        break
                    if bzerror != BZ_OK:
                        BZ2_bzDecompressEnd(bzs)
                    _catch_bz2_error(space, bzerror)

                    if rffi.getintfield(bzs, 'c_avail_in') == 0:
                        BZ2_bzDecompressEnd(bzs)
                        raise OperationError(
                            space.w_ValueError,
                            space.wrap("couldn't find end of stream"))
                    elif rffi.getintfield(bzs, 'c_avail_out') == 0:
                        out.prepare_next_chunk()

                res = out.make_result_string()
                BZ2_bzDecompressEnd(bzs)
                return space.wrap(res)
Beispiel #33
0
def entry_point(argv=None):
    RSDL.Init(RSDL.INIT_VIDEO) >= 0
    screen = RSDL.SetVideoMode(WIDTH, HEIGHT, 32, 0)
    event = lltype.malloc(RSDL.Event, flavor='raw')
    paintpattern = 0
    try:
        while True:
            ok = RSDL.WaitEvent(event)
            assert rffi.cast(lltype.Signed, ok) == 1
            c_type = rffi.getintfield(event, 'c_type')
            if c_type == RSDL.KEYDOWN:
                p = rffi.cast(RSDL.KeyboardEventPtr, event)
                if rffi.getintfield(p.c_keysym, 'c_sym') == RSDL.K_ESCAPE:
                    print 'Escape key'
                    break
            paintpattern += 1
            update_screen(screen, paintpattern)
    finally:
        lltype.free(event, flavor='raw')

    return 0
Beispiel #34
0
def decompress(space, data):
    """decompress(data) -> decompressed data

    Decompress data in one shot. If you want to decompress data sequentially,
    use an instance of BZ2Decompressor instead."""

    in_bufsize = len(data)
    if in_bufsize == 0:
        return space.wrap("")

    with lltype.scoped_alloc(bz_stream.TO, zero=True) as bzs:
        with lltype.scoped_alloc(rffi.CCHARP.TO, in_bufsize) as in_buf:
            for i in range(in_bufsize):
                in_buf[i] = data[i]
            bzs.c_next_in = in_buf
            rffi.setintfield(bzs, 'c_avail_in', in_bufsize)

            with OutBuffer(bzs) as out:
                bzerror = BZ2_bzDecompressInit(bzs, 0, 0)
                if bzerror != BZ_OK:
                    _catch_bz2_error(space, bzerror)

                while True:
                    bzerror = BZ2_bzDecompress(bzs)
                    if bzerror == BZ_STREAM_END:
                        break
                    if bzerror != BZ_OK:
                        BZ2_bzDecompressEnd(bzs)
                    _catch_bz2_error(space, bzerror)

                    if rffi.getintfield(bzs, 'c_avail_in') == 0:
                        BZ2_bzDecompressEnd(bzs)
                        raise OperationError(space.w_ValueError, space.wrap(
                            "couldn't find end of stream"))
                    elif rffi.getintfield(bzs, 'c_avail_out') == 0:
                        out.prepare_next_chunk()

                res = out.make_result_string()
                BZ2_bzDecompressEnd(bzs)
                return space.wrap(res)
Beispiel #35
0
    def compress(self, data):
        """compress(data) -> string

        Provide more data to the compressor object. It will return chunks of
        compressed data whenever possible. When you've finished providing data
        to compress, call the flush() method to finish the compression process,
        and return what is left in the internal buffers."""

        datasize = len(data)

        if datasize == 0:
            return self.space.wrap("")

        if not self.running:
            raise OperationError(self.space.w_ValueError,
                self.space.wrap("this object was already flushed"))

        in_bufsize = datasize

        with OutBuffer(self.bzs) as out:
            with lltype.scoped_alloc(rffi.CCHARP.TO, in_bufsize) as in_buf:

                for i in range(datasize):
                    in_buf[i] = data[i]

                self.bzs.c_next_in = in_buf
                rffi.setintfield(self.bzs, 'c_avail_in', in_bufsize)

                while True:
                    bzerror = BZ2_bzCompress(self.bzs, BZ_RUN)
                    if bzerror != BZ_RUN_OK:
                        _catch_bz2_error(self.space, bzerror)

                    if rffi.getintfield(self.bzs, 'c_avail_in') == 0:
                        break
                    elif rffi.getintfield(self.bzs, 'c_avail_out') == 0:
                        out.prepare_next_chunk()

                res = out.make_result_string()
                return self.space.wrap(res)
Beispiel #36
0
 def test_mousebutton_wheel(self):
     if not self.is_interactive:
         py.test.skip("interactive test only")
     print
     print "Press the given MouseButtons:"
     print "        Use Escape to pass tests."
     
     event_tests = [("left button",   RSDL.BUTTON_LEFT),
                    ("middle button", RSDL.BUTTON_MIDDLE),
                    ("right button",  RSDL.BUTTON_RIGHT),
                    ("scroll up",     RSDL.BUTTON_WHEELUP),
                    ("scroll down",   RSDL.BUTTON_WHEELDOWN)]
     test_success = []
     event = lltype.malloc(RSDL.Event, flavor='raw')
     try:
         for button_test in event_tests:
             print "    press %s:" % button_test[0]
             while True:
                 ok = RSDL.WaitEvent(event)
                 assert rffi.cast(lltype.Signed, ok) == 1
                 c_type = rffi.getintfield(event, 'c_type')
                 if c_type == RSDL.MOUSEBUTTONDOWN:
                     pass
                 elif c_type == RSDL.MOUSEBUTTONUP:
                     b = rffi.cast(RSDL.MouseButtonEventPtr, event)
                     if rffi.getintfield(b, 'c_button') == button_test[1]:
                         test_success.append(True)
                         break
                 elif c_type == RSDL.KEYUP:
                     p = rffi.cast(RSDL.KeyboardEventPtr, event)
                     if rffi.getintfield(p.c_keysym, 'c_sym') == RSDL.K_ESCAPE:
                         test_success.append(False) 
                         print "        manually aborted"
                         break
                     #break
         if False in test_success:
             py.test.fail("")
     finally:
         lltype.free(event, flavor='raw')
Beispiel #37
0
    def __init__(self, space, name):
        self.name = name
        digest_type = self.digest_type_by_name(space)
        self.digest_size = rffi.getintfield(digest_type, 'c_md_size')

        # Allocate a lock for each HASH object.
        # An optimization would be to not release the GIL on small requests,
        # and use a custom lock only when needed.
        self.lock = Lock(space)

        ctx = lltype.malloc(ropenssl.EVP_MD_CTX.TO, flavor='raw')
        rgc.add_memory_pressure(HASH_MALLOC_SIZE + self.digest_size)
        ropenssl.EVP_DigestInit(ctx, digest_type)
        self.ctx = ctx
Beispiel #38
0
def mktime(space, w_tup):
    """mktime(tuple) -> floating point number

    Convert a time tuple in local time to seconds since the Epoch."""

    buf = _gettmarg(space, w_tup, allowNone=False)
    rffi.setintfield(buf, "c_tm_wday", -1)
    tt = c_mktime(buf)
    # A return value of -1 does not necessarily mean an error, but tm_wday
    # cannot remain set to -1 if mktime succeeds.
    if tt == -1 and rffi.getintfield(buf, "c_tm_wday") == -1:
        raise OperationError(space.w_OverflowError, space.wrap("mktime argument out of range"))

    return space.wrap(float(tt))
Beispiel #39
0
def mktime(space, w_tup):
    """mktime(tuple) -> floating point number

    Convert a time tuple in local time to seconds since the Epoch."""

    buf = _gettmarg(space, w_tup, allowNone=False)
    rffi.setintfield(buf, "c_tm_wday", -1)
    tt = c_mktime(buf)
    # A return value of -1 does not necessarily mean an error, but tm_wday
    # cannot remain set to -1 if mktime succeeds.
    if tt == -1 and rffi.getintfield(buf, "c_tm_wday") == -1:
        raise OperationError(space.w_OverflowError,
                             space.wrap("mktime argument out of range"))

    return space.wrap(float(tt))
Beispiel #40
0
    def _sem_timedwait_save(sem, deadline):
        delay = 0
        void = lltype.nullptr(rffi.VOIDP.TO)
        with lltype.scoped_alloc(TIMEVALP.TO, 1) as tvdeadline:
            while True:
                # poll
                if _sem_trywait(sem) == 0:
                    return 0
                elif rposix.get_errno() != errno.EAGAIN:
                    return -1

                now = gettimeofday()
                c_tv_sec = rffi.getintfield(deadline[0], 'c_tv_sec')
                c_tv_nsec = rffi.getintfield(deadline[0], 'c_tv_nsec')
                if (c_tv_sec < now[0] or
                    (c_tv_sec == now[0] and c_tv_nsec <= now[1])):
                    rposix.set_errno(errno.ETIMEDOUT)
                    return -1


                # calculate how much time is left
                difference = ((c_tv_sec - now[0]) * 1000000 +
                                    (c_tv_nsec - now[1]))

                # check delay not too long -- maximum is 20 msecs
                if delay > 20000:
                    delay = 20000
                if delay > difference:
                    delay = difference
                delay += 1000

                # sleep
                rffi.setintfield(tvdeadline[0], 'c_tv_sec', delay / 1000000)
                rffi.setintfield(tvdeadline[0], 'c_tv_usec', delay % 1000000)
                if _select(0, void, void, void, tvdeadline) < 0:
                    return -1
Beispiel #41
0
    def flush(self):
        if not self.running:
            raise OperationError(self.space.w_ValueError, self.space.wrap("this object was already flushed"))
        self.running = False

        with OutBuffer(self.bzs) as out:
            while True:
                bzerror = BZ2_bzCompress(self.bzs, BZ_FINISH)
                if bzerror == BZ_STREAM_END:
                    break
                elif bzerror != BZ_FINISH_OK:
                    _catch_bz2_error(self.space, bzerror)

                if rffi.getintfield(self.bzs, "c_avail_out") == 0:
                    out.prepare_next_chunk()

            res = out.make_result_string()
            return self.space.wrap(res)
Beispiel #42
0
def compress(space, data, compresslevel=9):
    """compress(data [, compresslevel=9]) -> string

    Compress data in one shot. If you want to compress data sequentially,
    use an instance of BZ2Compressor instead. The compresslevel parameter, if
    given, must be a number between 1 and 9."""

    if compresslevel < 1 or compresslevel > 9:
        raise OperationError(
            space.w_ValueError,
            space.wrap("compresslevel must be between 1 and 9"))

    with lltype.scoped_alloc(bz_stream.TO, zero=True) as bzs:
        in_bufsize = len(data)

        with lltype.scoped_alloc(rffi.CCHARP.TO, in_bufsize) as in_buf:
            for i in range(in_bufsize):
                in_buf[i] = data[i]
            bzs.c_next_in = in_buf
            rffi.setintfield(bzs, 'c_avail_in', in_bufsize)

            # conforming to bz2 manual, this is large enough to fit compressed
            # data in one shot. We will check it later anyway.
            with OutBuffer(bzs,
                           in_bufsize + (in_bufsize / 100 + 1) + 600) as out:

                bzerror = BZ2_bzCompressInit(bzs, compresslevel, 0, 0)
                if bzerror != BZ_OK:
                    _catch_bz2_error(space, bzerror)

                while True:
                    bzerror = BZ2_bzCompress(bzs, BZ_FINISH)
                    if bzerror == BZ_STREAM_END:
                        break
                    elif bzerror != BZ_FINISH_OK:
                        BZ2_bzCompressEnd(bzs)
                        _catch_bz2_error(space, bzerror)

                    if rffi.getintfield(bzs, 'c_avail_out') == 0:
                        out.prepare_next_chunk()

                res = out.make_result_string()
                BZ2_bzCompressEnd(bzs)
                return space.wrap(res)
Beispiel #43
0
def compress(space, data, compresslevel=9):
    """compress(data [, compresslevel=9]) -> string

    Compress data in one shot. If you want to compress data sequentially,
    use an instance of BZ2Compressor instead. The compresslevel parameter, if
    given, must be a number between 1 and 9."""

    if compresslevel < 1 or compresslevel > 9:
        raise OperationError(space.w_ValueError,
            space.wrap("compresslevel must be between 1 and 9"))

    with lltype.scoped_alloc(bz_stream.TO, zero=True) as bzs:
        in_bufsize = len(data)

        with lltype.scoped_alloc(rffi.CCHARP.TO, in_bufsize) as in_buf:
            for i in range(in_bufsize):
                in_buf[i] = data[i]
            bzs.c_next_in = in_buf
            rffi.setintfield(bzs, 'c_avail_in', in_bufsize)

            # conforming to bz2 manual, this is large enough to fit compressed
            # data in one shot. We will check it later anyway.
            with OutBuffer(bzs,
                           in_bufsize + (in_bufsize / 100 + 1) + 600) as out:

                bzerror = BZ2_bzCompressInit(bzs, compresslevel, 0, 0)
                if bzerror != BZ_OK:
                    _catch_bz2_error(space, bzerror)

                while True:
                    bzerror = BZ2_bzCompress(bzs, BZ_FINISH)
                    if bzerror == BZ_STREAM_END:
                        break
                    elif bzerror != BZ_FINISH_OK:
                        BZ2_bzCompressEnd(bzs)
                        _catch_bz2_error(space, bzerror)

                    if rffi.getintfield(bzs, 'c_avail_out') == 0:
                        out.prepare_next_chunk()

                res = out.make_result_string()
                BZ2_bzCompressEnd(bzs)
                return space.wrap(res)
Beispiel #44
0
    def flush(self):
        if not self.running:
            raise OperationError(self.space.w_ValueError,
                self.space.wrap("this object was already flushed"))
        self.running = False

        with OutBuffer(self.bzs) as out:
            while True:
                bzerror = BZ2_bzCompress(self.bzs, BZ_FINISH)
                if bzerror == BZ_STREAM_END:
                    break
                elif bzerror != BZ_FINISH_OK:
                    _catch_bz2_error(self.space, bzerror)

                if rffi.getintfield(self.bzs, 'c_avail_out') == 0:
                    out.prepare_next_chunk()

            res = out.make_result_string()
            return self.space.wrap(res)
Beispiel #45
0
def getaddrinfo(host,
                port_or_service,
                family=AF_UNSPEC,
                socktype=0,
                proto=0,
                flags=0,
                address_to_fill=None):
    # port_or_service is a string, not an int (but try str(port_number)).
    assert port_or_service is None or isinstance(port_or_service, str)
    hints = lltype.malloc(_c.addrinfo, flavor='raw', zero=True)
    rffi.setintfield(hints, 'c_ai_family', family)
    rffi.setintfield(hints, 'c_ai_socktype', socktype)
    rffi.setintfield(hints, 'c_ai_protocol', proto)
    rffi.setintfield(hints, 'c_ai_flags', flags)
    # XXX need to lock around getaddrinfo() calls?
    p_res = lltype.malloc(rffi.CArray(_c.addrinfo_ptr), 1, flavor='raw')
    error = intmask(_c.getaddrinfo(host, port_or_service, hints, p_res))
    res = p_res[0]
    lltype.free(p_res, flavor='raw')
    lltype.free(hints, flavor='raw')
    if error:
        raise GAIError(error)
    try:
        result = []
        info = res
        while info:
            addr = make_address(info.c_ai_addr,
                                rffi.getintfield(info, 'c_ai_addrlen'),
                                address_to_fill)
            if info.c_ai_canonname:
                canonname = rffi.charp2str(info.c_ai_canonname)
            else:
                canonname = ""
            result.append((rffi.cast(lltype.Signed, info.c_ai_family),
                           rffi.cast(lltype.Signed, info.c_ai_socktype),
                           rffi.cast(lltype.Signed,
                                     info.c_ai_protocol), canonname, addr))
            info = info.c_ai_next
            address_to_fill = None  # don't fill the same address repeatedly
    finally:
        _c.freeaddrinfo(res)
    return result
Beispiel #46
0
 def _get_interior_descr(self, ffitype, width, offset):
     kind = libffi.types.getkind(ffitype)
     is_pointer = is_float = is_signed = False
     if ffitype is libffi.types.pointer:
         is_pointer = True
     elif kind == 'i':
         is_signed = True
     elif kind == 'f' or kind == 'I' or kind == 'U':
         # longlongs are treated as floats, see
         # e.g. llsupport/descr.py:getDescrClass
         is_float = True
     elif kind == 'u' or kind == 's':
         # they're all False
         pass
     else:
         raise NotImplementedError("unsupported ffitype or kind: %s" % kind)
     #
     fieldsize = rffi.getintfield(ffitype, 'c_size')
     return self.optimizer.cpu.interiorfielddescrof_dynamic(
         offset, width, fieldsize, is_pointer, is_float, is_signed)
Beispiel #47
0
 def _get_interior_descr(self, ffitype, width, offset):
     kind = libffi.types.getkind(ffitype)
     is_pointer = is_float = is_signed = False
     if ffitype is libffi.types.pointer:
         is_pointer = True
     elif kind == 'i':
         is_signed = True
     elif kind == 'f' or kind == 'I' or kind == 'U':
         # longlongs are treated as floats, see
         # e.g. llsupport/descr.py:getDescrClass
         is_float = True
     elif kind == 'u' or kind == 's':
         # they're all False
         pass
     else:
         raise NotImplementedError("unsupported ffitype or kind: %s" % kind)
     #
     fieldsize = rffi.getintfield(ffitype, 'c_size')
     return self.optimizer.cpu.interiorfielddescrof_dynamic(
         offset, width, fieldsize, is_pointer, is_float, is_signed
     )
Beispiel #48
0
def getaddrinfo(host, port_or_service,
                family=AF_UNSPEC, socktype=0, proto=0, flags=0,
                address_to_fill=None):
    # port_or_service is a string, not an int (but try str(port_number)).
    assert port_or_service is None or isinstance(port_or_service, str)
    hints = lltype.malloc(_c.addrinfo, flavor='raw', zero=True)
    rffi.setintfield(hints, 'c_ai_family',   family)
    rffi.setintfield(hints, 'c_ai_socktype', socktype)
    rffi.setintfield(hints, 'c_ai_protocol', proto)
    rffi.setintfield(hints, 'c_ai_flags'   , flags)
    # XXX need to lock around getaddrinfo() calls?
    p_res = lltype.malloc(rffi.CArray(_c.addrinfo_ptr), 1, flavor='raw')
    error = intmask(_c.getaddrinfo(host, port_or_service, hints, p_res))
    res = p_res[0]
    lltype.free(p_res, flavor='raw')
    lltype.free(hints, flavor='raw')
    if error:
        raise GAIError(error)
    try:
        result = []
        info = res
        while info:
            addr = make_address(info.c_ai_addr,
                                rffi.getintfield(info, 'c_ai_addrlen'),
                                address_to_fill)
            if info.c_ai_canonname:
                canonname = rffi.charp2str(info.c_ai_canonname)
            else:
                canonname = ""
            result.append((rffi.cast(lltype.Signed, info.c_ai_family),
                           rffi.cast(lltype.Signed, info.c_ai_socktype),
                           rffi.cast(lltype.Signed, info.c_ai_protocol),
                           canonname,
                           addr))
            info = info.c_ai_next
            address_to_fill = None    # don't fill the same address repeatedly
    finally:
        _c.freeaddrinfo(res)
    return result
def test_image_pixels():
    for filename in ["demo.jpg", "demo.png"]:
        image = RIMG.Load(os.path.join(autopath.this_dir, filename))
        assert image
        assert rffi.getintfield(image.c_format, 'c_BytesPerPixel') in (3, 4)
        RSDL.LockSurface(image)
        result = {}
        try:
            rgb = lltype.malloc(rffi.CArray(RSDL.Uint8), 3, flavor='raw')
            try:
                for y in range(23):
                    for x in range(y % 13, 17, 13):
                        color = RSDL_helper.get_pixel(image, x, y)
                        RSDL.GetRGB(color,
                                    image.c_format,
                                    rffi.ptradd(rgb, 0),
                                    rffi.ptradd(rgb, 1),
                                    rffi.ptradd(rgb, 2))
                        r = rffi.cast(lltype.Signed, rgb[0])
                        g = rffi.cast(lltype.Signed, rgb[1])
                        b = rffi.cast(lltype.Signed, rgb[2])
                        result[x, y] = r, g, b
            finally:
                lltype.free(rgb, flavor='raw')
        finally:
            RSDL.UnlockSurface(image)
        RSDL.FreeSurface(image)
        for x, y in result:
            f = (x*17 + y*23) / float(17*17+23*23)
            expected_r = int(255.0 * (1.0-f))
            expected_g = 0
            expected_b = int(255.0 * f)
            r, g, b = result[x, y]
            assert abs(r-expected_r) < 10
            assert abs(g-expected_g) < 10
            assert abs(b-expected_b) < 10
Beispiel #50
0
def double_from_timeval(tv):
    return rffi.getintfield(tv, 'c_tv_sec') + (
        rffi.getintfield(tv, 'c_tv_usec') / 1000000.0)
Beispiel #51
0
 def _bzs_total_out(bzs):
     return (rffi.getintfield(bzs, 'c_total_out_hi32') << 32) + \
            rffi.getintfield(bzs, 'c_total_out_lo32')
Beispiel #52
0
 def _bzs_total_out(bzs):
     if rffi.getintfield(bzs, 'c_total_out_hi32') != 0 or \
            rffi.getintfield(bzs, 'c_total_out_lo32') > sys.maxint:
         raise MemoryError
     return rffi.getintfield(bzs, 'c_total_out_lo32')