바이트열 객체
*************

이 함수들은 바이트열 매개 변수가 필요할 때 바이트열이 아닌 매개 변수로
호출하면 "TypeError"를 발생시킵니다.

type PyBytesObject

   이 "PyObject"의 서브 형은 파이썬 바이트열 객체를 나타냅니다.

PyTypeObject PyBytes_Type
    * Part of the 안정 ABI.*

   이 "PyTypeObject"의 인스턴스는 파이썬 바이트열 형을 나타냅니다; 파
   이썬 계층의 "bytes"와 같은 객체입니다.

int PyBytes_Check(PyObject *o)

   객체 *o*가 바이트열 객체이거나 바이트열 형의 서브 형의 인스턴스면
   참을 반환합니다. 이 함수는 항상 성공합니다.

int PyBytes_CheckExact(PyObject *o)

   객체 *o*가 바이트열 객체이지만, 바이트열 형의 서브 형의 인스턴스는
   아니면 참을 반환합니다. 이 함수는 항상 성공합니다.

PyObject *PyBytes_FromString(const char *v)
    *반환값: 새 참조.** Part of the 안정 ABI.** Thread safety:
   Atomic.*

   성공하면 값으로 *v* 문자열의 복사본을 갖는 새 바이트열 객체를 반환
   하고, 실패하면 "NULL"을 반환합니다. 매개 변수 *v*는 "NULL"이 아니어
   야 합니다; 검사하지 않습니다.

PyObject *PyBytes_FromStringAndSize(const char *v, Py_ssize_t len)
    *반환값: 새 참조.** Part of the 안정 ABI.** Thread safety:
   Atomic.*

   성공하면 값이 *v* 문자열의 복사본이고 길이가 *len*인 새 바이트열 객
   체를 반환하고, 실패하면 "NULL"을 반환합니다. *v*가 "NULL"이면, 바이
   트열 객체의 내용은 초기화되지 않습니다.

   Soft deprecated since version 3.15: Use the "PyBytesWriter" API
   instead of "PyBytes_FromStringAndSize(NULL, len)".

PyObject *PyBytes_FromFormat(const char *format, ...)
    *반환값: 새 참조.** Part of the 안정 ABI.** Thread safety:
   Atomic.*

   C "printf()"-스타일 *format* 문자열과 가변 개수의 인자를 받아서, 결
   과 파이썬 바이트열 객체의 크기를 계산하고 그 안에 값이 포맷된 바이
   트열 객체를 반환합니다. 가변 인자는 C 형이어야 하며 *format* 문자열
   에 있는 포맷 문자들과 정확히 대응해야 합니다. 허용되는 포맷 문자는
   다음과 같습니다:

   +---------------------+-----------------+----------------------------------+
   | 포맷 문자           | 형              | 주석                             |
   |=====================|=================|==================================|
   | "%%"                | *n/a*           | 리터럴 % 문자.                   |
   +---------------------+-----------------+----------------------------------+
   | "%c"                | int             | 단일 바이트, C int로 표현됩니다. |
   +---------------------+-----------------+----------------------------------+
   | "%d"                | int             | "printf("%d")"와 동등합니다. [1] |
   +---------------------+-----------------+----------------------------------+
   | "%u"                | unsigned int    | "printf("%u")"와 동등합니다. [1] |
   +---------------------+-----------------+----------------------------------+
   | "%ld"               | long            | "printf("%ld")"와 동등합니다.    |
   |                     |                 | [1]                              |
   +---------------------+-----------------+----------------------------------+
   | "%lu"               | unsigned long   | "printf("%lu")"와 동등합니다.    |
   |                     |                 | [1]                              |
   +---------------------+-----------------+----------------------------------+
   | "%zd"               | "Py_ssize_t"    | "printf("%zd")"와 동등합니다.    |
   |                     |                 | [1]                              |
   +---------------------+-----------------+----------------------------------+
   | "%zu"               | size_t          | "printf("%zu")"와 동등합니다.    |
   |                     |                 | [1]                              |
   +---------------------+-----------------+----------------------------------+
   | "%i"                | int             | "printf("%i")"와 동등합니다. [1] |
   +---------------------+-----------------+----------------------------------+
   | "%x"                | int             | "printf("%x")"와 동등합니다. [1] |
   +---------------------+-----------------+----------------------------------+
   | "%s"                | const char*     | 널-종료 C 문자 배열.             |
   +---------------------+-----------------+----------------------------------+
   | "%p"                | const void*     | C 포인터의 16진수 표현. 플랫폼의 |
   |                     |                 | "printf"가 어떤 결과를 내는지에  |
   |                     |                 | 상 관없이 리터럴 "0x"로 시작함이 |
   |                     |                 | 보장된다는 점을 제외하고는 거의  |
   |                     |                 | "printf("%p")"와 동등합니다.     |
   +---------------------+-----------------+----------------------------------+

   인식할 수 없는 포맷 문자는 포맷 문자열의 나머지 부분이 모두 결과 객
   체에 그대로 복사되게 만들고, 추가 인자는 무시됩니다.

   [1] 정수 지정자 (d, u, ld, lu, zd, zu, i, x)에서: 0-변환 플래그는
       정밀도를 지정해도 영향을 미칩니다.

PyObject *PyBytes_FromFormatV(const char *format, va_list vargs)
    *반환값: 새 참조.** Part of the 안정 ABI.** Thread safety:
   Atomic.*

   정확히 두 개의 인자를 취한다는 것을 제외하고는
   "PyBytes_FromFormat()"과 같습니다.

PyObject *PyBytes_FromObject(PyObject *o)
    *반환값: 새 참조.** Part of the 안정 ABI.** Thread safety: Safe
   for concurrent use on the same object.*

   버퍼 프로토콜을 구현하는 객체 *o*의 바이트열 표현을 반환합니다.

   참고:

     If the object implements the buffer protocol, then the buffer
     must not be mutated while the bytes object is being created.

Py_ssize_t PyBytes_Size(PyObject *o)
    * Part of the 안정 ABI.** Thread safety: Atomic.*

   바이트열 객체 *o*의 길이를 반환합니다.

Py_ssize_t PyBytes_GET_SIZE(PyObject *o)
    * Thread safety: Atomic.*

   "PyBytes_Size()"와 유사하지만, 에러 검사가 없습니다.

char *PyBytes_AsString(PyObject *o)
    * Part of the 안정 ABI.** Thread safety: Safe to call from
   multiple threads with external synchronization only.*

   *o*의 내용에 대한 포인터를 반환합니다. 포인터는 "len(o) + 1" 바이트
   로 구성된 *o*의 내부 버퍼를 가리킵니다. 버퍼의 마지막 바이트는 다른
   널(null) 바이트가 있는지에 관계없이 항상 널입니다. 객체가
   "PyBytes_FromStringAndSize(NULL, size)"를 사용하여 방금 만들어진 경
   우가 아니면 데이터를 수정해서는 안 됩니다. 할당을 해제해서는 안 됩
   니다. *o*가 바이트열 객체가 아니면, "PyBytes_AsString()"은 "NULL"을
   반환하고 "TypeError"를 발생시킵니다.

char *PyBytes_AS_STRING(PyObject *string)
    * Thread safety: Safe to call from multiple threads with external
   synchronization only.*

   "PyBytes_AsString()"와 유사하지만, 에러 검사가 없습니다.

int PyBytes_AsStringAndSize(PyObject *obj, char **buffer, Py_ssize_t *length)
    * Part of the 안정 ABI.** Thread safety: Safe to call from
   multiple threads with external synchronization only.*

   출력 변수 *buffer*와 *length*로 객체 *obj*의 널-종료 내용을 반환합
   니다. 성공하면 "0"을 반환합니다.

   *length*가 "NULL"이면, 바이트열 객체는 내장된 널 바이트를 포함할 수
   없습니다; 만약 그렇다면 함수는 "-1"을 반환하고 "ValueError"를 발생
   시킵니다.

   buffer는 *obj*의 내부 버퍼를 가리키게 되는데, 끝에 추가 널 바이트가
   포함됩니다 (*length*에는 포함되지 않습니다). 객체가
   "PyBytes_FromStringAndSize(NULL, size)"를 사용하여 방금 만들어진 경
   우가 아니면 데이터를 수정해서는 안 됩니다. 할당을 해제해서는 안 됩
   니다. *obj*가 바이트열 객체가 아니면 "PyBytes_AsStringAndSize()"는
   "-1"을 반환하고 "TypeError"를 발생시킵니다.

   버전 3.5에서 변경: 이전에는, 바이트열 객체에 널 바이트가 포함되어
   있으면 "TypeError"가 발생했습니다.

void PyBytes_Concat(PyObject **bytes, PyObject *newpart)
    * Part of the 안정 ABI.** Thread safety: Safe for concurrent use
   on the same object.*

   *bytes*에 *newpart*의 내용을 덧붙인 새 바이트열 객체를 **bytes*에
   만듭니다; 호출자가 새 참조를 소유합니다. *bytes*의 예전 값에 대한
   참조를 훔칩니다. 새 객체가 만들어질 수 없으면, *bytes*에 대한 예전
   참조는 여전히 버려지고 **bytes*의 값은 "NULL"로 설정됩니다; 적절한
   예외가 설정됩니다.

   참고:

     If *newpart* implements the buffer protocol, then the buffer must
     not be mutated while the new bytes object is being created.

void PyBytes_ConcatAndDel(PyObject **bytes, PyObject *newpart)
    * Part of the 안정 ABI.** Thread safety: Safe for concurrent use
   on the same object.*

   *bytes*에 *newpart*의 내용을 덧붙인 새 바이트열 객체를 **bytes*에
   만듭니다. 이 버전은 *newpart*로의 *강한 참조*를 해제합니다 (즉 참조
   횟수를 감소시킵니다).

   참고:

     If *newpart* implements the buffer protocol, then the buffer must
     not be mutated while the new bytes object is being created.

PyObject *PyBytes_Join(PyObject *sep, PyObject *iterable)
    * Thread safety: Safe for concurrent use on the same object.*

   파이썬의 "sep.join(iterable)"와 유사합니다.

   *sep*은 반드시 파이썬의 "bytes" 객체이어야 합니다
   .("PyUnicode_Join()"는 "NULL" 구분자를 허용하고 이를 공백으로 취급
   하는 반면, "PyBytes_Join()"는 "NULL" 구분자를 허용하지 않음에 유의
   하십시오.)

   *iterable*은 반드시 버퍼 프로토콜을 구현하는 객체를 생성하는 반복
   가능한 객체이어야 합니다.

   성공 시 새로운 "bytes" 객체를 반환합니다. 실패 시 예외를 설정하고
   "NULL"을 반환합니다.

   Added in version 3.14.

   참고:

     If *iterable* objects implement the buffer protocol, then the
     buffers must not be mutated while the new bytes object is being
     created.

int _PyBytes_Resize(PyObject **bytes, Py_ssize_t newsize)
    * Thread safety: Safe to call without external synchronization on
   distinct objects.*

   바이트열 객체의 크기를 변경합니다. *newsize*는 바이트열 객체의 새
   길이가 됩니다. 새 바이트열 객체를 생성하고 이전 객체를 파괴한다고
   생각할 수 있습니다. 단지 더 효율적으로 수행합니다. 기존 바이트열 객
   체의 주소를 lvalue(내용을 기록할 수 있습니다)로 전달하고, 원하는 새
   크기를 전달합니다. 성공하면, **bytes*는 크기가 변경된 바이트열 객체
   를 갖게 되고 "0"이 반환됩니다; **bytes*의 주소는 입력값과 다를 수
   있습니다. 재할당이 실패하면, **bytes*에 있는 원래 바이트열 객체는
   할당 해제되고, **bytes*가 "NULL"로 설정되고, "MemoryError"가 설정되
   며 "-1"이 반환됩니다.

   Soft deprecated since version 3.15: Use the "PyBytesWriter" API
   instead.

PyObject *PyBytes_Repr(PyObject *bytes, int smartquotes)
    * Part of the 안정 ABI.** Thread safety: Atomic.*

   Get the string representation of *bytes*. This function is
   currently used to implement "bytes.__repr__()" in Python.

   This function does not do type checking; it is undefined behavior
   to pass *bytes* as a non-bytes object or "NULL".

   If *smartquotes* is true, the representation will use a double-
   quoted string instead of single-quoted string when single-quotes
   are present in *bytes*. For example, the byte string "'Python'"
   would be represented as "b"'Python'"" when *smartquotes* is true,
   or "b'\'Python\''" when it is false.

   On success, this function returns a *strong reference* to a "str"
   object containing the representation. On failure, this returns
   "NULL" with an exception set.

PyObject *PyBytes_DecodeEscape(const char *s, Py_ssize_t len, const char *errors, Py_ssize_t unicode, const char *recode_encoding)
    * Part of the 안정 ABI.** Thread safety: Atomic.*

   Unescape a backslash-escaped string *s*. *s* must not be "NULL".
   *len* must be the size of *s*.

   *errors* must be one of ""strict"", ""replace"", or ""ignore"". If
   *errors* is "NULL", then ""strict"" is used by default.

   On success, this function returns a *strong reference* to a Python
   "bytes" object containing the unescaped string. On failure, this
   function returns "NULL" with an exception set.

   버전 3.9에서 변경: *unicode* and *recode_encoding* are now unused.


PyBytesWriter
*************

The "PyBytesWriter" API can be used to create a Python "bytes" object.

Added in version 3.15.

type PyBytesWriter

   A bytes writer instance.

   The API is **not thread safe**: a writer should only be used by a
   single thread at the same time.

   The instance must be destroyed by "PyBytesWriter_Finish()" on
   success, or "PyBytesWriter_Discard()" on error.


Create, Finish, Discard
=======================

PyBytesWriter *PyBytesWriter_Create(Py_ssize_t size)

   Create a "PyBytesWriter" to write *size* bytes.

   If *size* is greater than zero, allocate *size* bytes, and set the
   writer size to *size*. The caller is responsible to write *size*
   bytes using "PyBytesWriter_GetData()". This function does not
   overallocate.

   On error, set an exception and return "NULL".

   *size* must be positive or zero.

PyObject *PyBytesWriter_Finish(PyBytesWriter *writer)

   Finish a "PyBytesWriter" created by "PyBytesWriter_Create()".

   On success, return a Python "bytes" object. On error, set an
   exception and return "NULL".

   The writer instance is invalid after the call in any case. No API
   can be called on the writer after "PyBytesWriter_Finish()".

PyObject *PyBytesWriter_FinishWithSize(PyBytesWriter *writer, Py_ssize_t size)

   Similar to "PyBytesWriter_Finish()", but resize the writer to
   *size* bytes before creating the "bytes" object.

PyObject *PyBytesWriter_FinishWithPointer(PyBytesWriter *writer, void *buf)

   Similar to "PyBytesWriter_Finish()", but resize the writer using
   *buf* pointer before creating the "bytes" object.

   Set an exception and return "NULL" if *buf* pointer is outside the
   internal buffer bounds.

   Function pseudo-code:

      Py_ssize_t size = (char*)buf - (char*)PyBytesWriter_GetData(writer);
      return PyBytesWriter_FinishWithSize(writer, size);

void PyBytesWriter_Discard(PyBytesWriter *writer)

   Discard a "PyBytesWriter" created by "PyBytesWriter_Create()".

   Do nothing if *writer* is "NULL".

   The writer instance is invalid after the call. No API can be called
   on the writer after "PyBytesWriter_Discard()".


High-level API
==============

int PyBytesWriter_WriteBytes(PyBytesWriter *writer, const void *bytes, Py_ssize_t size)

   Grow the *writer* internal buffer by *size* bytes, write *size*
   bytes of *bytes* at the *writer* end, and add *size* to the
   *writer* size.

   If *size* is equal to "-1", call "strlen(bytes)" to get the string
   length.

   On success, return "0". On error, set an exception and return "-1".

int PyBytesWriter_Format(PyBytesWriter *writer, const char *format, ...)

   Similar to "PyBytes_FromFormat()", but write the output directly at
   the writer end. Grow the writer internal buffer on demand. Then add
   the written size to the writer size.

   On success, return "0". On error, set an exception and return "-1".


Getters
=======

Py_ssize_t PyBytesWriter_GetSize(PyBytesWriter *writer)

   Get the writer size.

   The function cannot fail.

void *PyBytesWriter_GetData(PyBytesWriter *writer)

   Get the writer data: start of the internal buffer.

   The pointer is valid until "PyBytesWriter_Finish()" or
   "PyBytesWriter_Discard()" is called on *writer*.

   The function cannot fail.


Low-level API
=============

int PyBytesWriter_Resize(PyBytesWriter *writer, Py_ssize_t size)

   Resize the writer to *size* bytes. It can be used to enlarge or to
   shrink the writer. This function typically overallocates to achieve
   amortized performance when resizing multiple times.

   Newly allocated bytes are left uninitialized.

   On success, return "0". On error, set an exception and return "-1".

   *size* must be positive or zero.

int PyBytesWriter_Grow(PyBytesWriter *writer, Py_ssize_t grow)

   Resize the writer by adding *grow* bytes to the current writer
   size. This function typically overallocates to achieve amortized
   performance when resizing multiple times.

   Newly allocated bytes are left uninitialized.

   On success, return "0". On error, set an exception and return "-1".

   *size* can be negative to shrink the writer.

void *PyBytesWriter_GrowAndUpdatePointer(PyBytesWriter *writer, Py_ssize_t size, void *buf)

   Similar to "PyBytesWriter_Grow()", but update also the *buf*
   pointer.

   The *buf* pointer is moved if the internal buffer is moved in
   memory. The *buf* relative position within the internal buffer is
   left unchanged.

   On error, set an exception and return "NULL".

   *buf* must not be "NULL".

   Function pseudo-code:

      Py_ssize_t pos = (char*)buf - (char*)PyBytesWriter_GetData(writer);
      if (PyBytesWriter_Grow(writer, size) < 0) {
          return NULL;
      }
      return (char*)PyBytesWriter_GetData(writer) + pos;
