|
| 1 | +# Copyright (C) 2016-present the asyncpg authors and contributors |
| 2 | +# <see AUTHORS file> |
| 3 | +# |
| 4 | +# This module is part of asyncpg and is released under |
| 5 | +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 |
| 6 | + |
| 7 | + |
| 8 | +cdef tid_encode(ConnectionSettings settings, WriteBuffer buf, obj): |
| 9 | + cdef int overflow = 0 |
| 10 | + cdef long block, offset |
| 11 | + |
| 12 | + if not (cpython.PyTuple_Check(obj) or cpython.PyList_Check(obj)): |
| 13 | + raise TypeError( |
| 14 | + 'list or tuple expected (got type {})'.format(type(obj))) |
| 15 | + |
| 16 | + if len(obj) != 2: |
| 17 | + raise ValueError( |
| 18 | + 'invalid number of elements in tid tuple, expecting 2') |
| 19 | + |
| 20 | + try: |
| 21 | + block = cpython.PyLong_AsLong(obj[0]) |
| 22 | + except OverflowError: |
| 23 | + overflow = 1 |
| 24 | + |
| 25 | + # "long" and "long long" have the same size for x86_64, need an extra check |
| 26 | + if overflow or (sizeof(block) > 4 and (block < -2147483648 or |
| 27 | + block > 2147483647)): |
| 28 | + raise OverflowError( |
| 29 | + 'block too big to be encoded as INT4: {!r}'.format(obj[0])) |
| 30 | + |
| 31 | + try: |
| 32 | + offset = cpython.PyLong_AsLong(obj[1]) |
| 33 | + overflow = 0 |
| 34 | + except OverflowError: |
| 35 | + overflow = 1 |
| 36 | + |
| 37 | + if overflow or offset < -32768 or offset > 32767: |
| 38 | + raise OverflowError( |
| 39 | + 'offset too big to be encoded as INT2: {!r}'.format(obj[1])) |
| 40 | + |
| 41 | + buf.write_int32(6) |
| 42 | + buf.write_int32(<int32_t>block) |
| 43 | + buf.write_int16(<int16_t>offset) |
| 44 | + |
| 45 | + |
| 46 | +cdef tid_decode(ConnectionSettings settings, FastReadBuffer buf): |
| 47 | + cdef: |
| 48 | + int32_t block |
| 49 | + int16_t offset |
| 50 | + |
| 51 | + block = hton.unpack_int32(buf.read(4)) |
| 52 | + offset = hton.unpack_int16(buf.read(2)) |
| 53 | + |
| 54 | + return (block, offset) |
| 55 | + |
| 56 | + |
| 57 | +cdef init_tid_codecs(): |
| 58 | + register_core_codec(TIDOID, |
| 59 | + <encode_func>&tid_encode, |
| 60 | + <decode_func>&tid_decode, |
| 61 | + PG_FORMAT_BINARY) |
| 62 | + |
| 63 | + |
| 64 | +init_tid_codecs() |
0 commit comments