"struct" — Interpret strings as packed binary data
**************************************************

This module performs conversions between Python values and C structs
represented as Python strings.  This can be used in handling binary
data stored in files or from network connections, among other sources.
It uses 書式文字列 as compact descriptions of the layout of the C
structs and the intended conversion to/from Python values.

注釈: デフォルトでは、与えられた C の構造体をパックする際に、関連す
  る C デ ータ型を適切にアラインメント(alignment)するために数バイトの
  パディン グを行うことがあります。この挙動が選択されたのは、パックさ
  れた構造体 のバイト表現を対応する C 構造体のメモリレイアウトに正確に
  対応させる ためです。プラットフォーム独立のデータフォーマットを扱っ
  たり、隠れた パディングを排除したりするには、サイズ及びアラインメン
  トとして "native" の代わりに "standard" を使うようにします: 詳しくは
  バイトオ ーダ、サイズ、アラインメント を参照して下さい。


関数と例外
==========

このモジュールは以下の例外と関数を定義しています:

exception struct.error

   様々な状況で送出される例外です。引数は何が問題なのかを記述する文字
   列です。

struct.pack(fmt, v1, v2, ...)

   Return a string containing the values "v1, v2, ..." packed
   according to the given format.  The arguments must match the values
   required by the format exactly.

struct.pack_into(fmt, buffer, offset, v1, v2, ...)

   Pack the values "v1, v2, ..." according to the given format, write
   the packed bytes into the writable *buffer* starting at *offset*.
   Note that the offset is a required argument.

   バージョン 2.5 で追加.

struct.unpack(fmt, string)

   Unpack the string (presumably packed by "pack(fmt, ...)") according
   to the given format.  The result is a tuple even if it contains
   exactly one item. The string must contain exactly the amount of
   data required by the format ("len(string)" must equal
   "calcsize(fmt)").

struct.unpack_from(fmt, buffer[, offset=0])

   Unpack the *buffer* according to the given format. The result is a
   tuple even if it contains exactly one item. The *buffer* must
   contain at least the amount of data required by the format
   ("len(buffer[offset:])" must be at least "calcsize(fmt)").

   バージョン 2.5 で追加.

struct.calcsize(fmt)

   Return the size of the struct (and hence of the string)
   corresponding to the given format.


書式文字列
==========

書式文字列はデータをパックしたりアンパックしたりするときの期待されるレ
イアウトを指定するためのメカニズムです。文字列はパック/アンパックされ
るデータの型を指定する 書式指定文字 から組み立てられます。さらに、 バ
イトオーダ、サイズ、アラインメント を制御するための特殊文字もあります
。


バイトオーダ、サイズ、アラインメント
------------------------------------

デフォルトでは、C での型はマシンのネイティブ (native) の形式およびバイ
トオーダ (byte order) で表され、適切にアラインメント (alignment) する
ために、必要に応じて数バイトのパディングを行ってスキップします (これは
C コンパイラが用いるルールに従います)。

これに代わって、フォーマット文字列の最初の文字を使って、バイトオーダや
サイズ、アラインメントを指定することができます。指定できる文字を以下の
テーブルに示します:

+-------------+--------------------------+------------+-------------+
| 文字        | バイトオーダ             | サイズ     | アラインメ  |
|             |                          |            | ント        |
+=============+==========================+============+=============+
| "@"         | native                   | native     | native      |
+-------------+--------------------------+------------+-------------+
| "="         | native                   | standard   | none        |
+-------------+--------------------------+------------+-------------+
| "<"         | リトルエンディアン       | standard   | none        |
+-------------+--------------------------+------------+-------------+
| ">"         | ビッグエンディアン       | standard   | none        |
+-------------+--------------------------+------------+-------------+
| "!"         | ネットワーク (= ビッグエ | standard   | none        |
|             | ンディアン)              |            |             |
+-------------+--------------------------+------------+-------------+

フォーマット文字列の最初の文字が上のいずれかでない場合、"'@'" であると
みなされます。

ネイティブのバイトオーダはビッグエンディアンかリトルエンディアンで、ホ
スト計算機に依存します。例えば、Intel x86 および AMD64 (x86-64) はリト
ルエンディアンです。Motorola 68000 および PowerPC G5 はビッグエンディ
アンです。ARM および Intel Itanium はエンディアンを切り替えられる機能
を備えています (バイエンディアン)。使っているシステムでのエンディアン
は "sys.byteorder" を使って調べて下さい。

ネイティブのサイズおよびアラインメントは C コンパイラの "sizeof" 式で
決定されます。ネイティブのサイズおよびアラインメントはネイティブのバイ
トオーダと同時に使われます。

標準のサイズはフォーマット文字だけで決まります。 書式指定文字 の表を参
照して下さい。

"'@'" と "'='" の違いに注意してください: 両方ともネイティブのバイトオ
ーダですが、後者のバイトサイズとアラインメントは標準のものに合わせてあ
ります。

"'!'" 表記は、ネットワークバイトオーダがビッグエンディアンかリトルエン
ディアンか忘れてしまったという不運な方のために用意されています。

バイトオーダに関して、「(強制的にバイトスワップを行う)ネイティブの逆」
を指定する方法はありません。"'<'" または "'>'" のうちふさわしい方を選
んでください。

注釈:

1. パディングは構造体のメンバの並びの中にだけ自動で追加されます。最
   初 や最後にパディングが追加されることはありません。

2. ネイティブでないサイズおよびアラインメントが使われる場合にはパデ
   ィ ングは行われません (たとえば 『<』, 『>』, 『=』, 『!』 を使った
   場 合です)。

3. 特定の型によるアラインメント要求に従うように構造体の末端をそろえ
   る には、繰り返し回数をゼロにした特定の型でフォーマットを終端します
   。 使用例 を参照して下さい。


書式指定文字
------------

フォーマット文字 (format character) は以下の意味を持っています; C と
Python の間の変換では、値は正確に以下に指定された型でなくてはなりませ
ん: 「標準のサイズ」列は standard サイズ使用時にパックされた値が何バイ
トかを示します。つまり、フォーマット文字列が "'<'", "'>'", "'!'",
"'='" のいずれかで始まっている場合のものです。native サイズ使用時には
パックされた値の大きさはプラットフォーム依存です。

+----------+----------------------------+----------------------+------------------+--------------+
| フォーマ | C の型                     | Python の型          | 標準のサイズ     | 注釈         |
| ット     |                            |                      |                  |              |
+==========+============================+======================+==================+==============+
| "x"      | パディングバイト           | 値なし               |                  |              |
+----------+----------------------------+----------------------+------------------+--------------+
| "c"      | "char"                     | string of length 1   | 1                |              |
+----------+----------------------------+----------------------+------------------+--------------+
| "b"      | "signed char"              | 整数                 | 1                | (3)          |
+----------+----------------------------+----------------------+------------------+--------------+
| "B"      | "unsigned char"            | 整数                 | 1                | (3)          |
+----------+----------------------------+----------------------+------------------+--------------+
| "?"      | "_Bool"                    | 真偽値型(bool)       | 1                | (1)          |
+----------+----------------------------+----------------------+------------------+--------------+
| "h"      | "short"                    | 整数                 | 2                | (3)          |
+----------+----------------------------+----------------------+------------------+--------------+
| "H"      | "unsigned short"           | 整数                 | 2                | (3)          |
+----------+----------------------------+----------------------+------------------+--------------+
| "i"      | "int"                      | 整数                 | 4                | (3)          |
+----------+----------------------------+----------------------+------------------+--------------+
| "I"      | "unsigned int"             | 整数                 | 4                | (3)          |
+----------+----------------------------+----------------------+------------------+--------------+
| "l"      | "long"                     | 整数                 | 4                | (3)          |
+----------+----------------------------+----------------------+------------------+--------------+
| "L"      | "unsigned long"            | 整数                 | 4                | (3)          |
+----------+----------------------------+----------------------+------------------+--------------+
| "q"      | "long long"                | 整数                 | 8                | (2), (3)     |
+----------+----------------------------+----------------------+------------------+--------------+
| "Q"      | "unsigned long long"       | 整数                 | 8                | (2), (3)     |
+----------+----------------------------+----------------------+------------------+--------------+
| "f"      | "float"                    | 浮動小数点数         | 4                | (4)          |
+----------+----------------------------+----------------------+------------------+--------------+
| "d"      | "double"                   | 浮動小数点数         | 8                | (4)          |
+----------+----------------------------+----------------------+------------------+--------------+
| "s"      | "char[]"                   | string               |                  |              |
+----------+----------------------------+----------------------+------------------+--------------+
| "p"      | "char[]"                   | string               |                  |              |
+----------+----------------------------+----------------------+------------------+--------------+
| "P"      | "void *"                   | 整数                 |                  | (5), (3)     |
+----------+----------------------------+----------------------+------------------+--------------+

注釈:

1. "'?'" 変換コードは C99 で定義された "_Bool" 型に対応します。その
   型 が利用できない場合は、 "char" で代用されます。標準モードでは常に
   1バ イトで表現されます。

   バージョン 2.6 で追加.

2. 変換コード "'q'" および "'Q'" は、ネイティブモードではプラットフ
   ォ ームの C コンパイラが C の "long long" 型をサポートする場合、ま
   たは Windows では "__int64" をサポートする場合にのみ利用できます。
   標準モ ードでは常に利用できます。

   バージョン 2.2 で追加.

3. When attempting to pack a non-integer using any of the integer
   conversion codes, if the non-integer has a "__index__()" method
   then that method is called to convert the argument to an integer
   before packing.  If no "__index__()" method exists, or the call to
   "__index__()" raises "TypeError", then the "__int__()" method is
   tried.  However, the use of "__int__()" is deprecated, and will
   raise "DeprecationWarning".

   バージョン 2.7 で変更: Use of the "__index__()" method for non-
   integers is new in 2.7.

   バージョン 2.7 で変更: Prior to version 2.7, not all integer
   conversion codes would use the "__int__()" method to convert, and
   "DeprecationWarning" was raised only for float arguments.

4. For the "'f'" and "'d'" conversion codes, the packed
   representation uses the IEEE 754 binary32 (for "'f'") or binary64
   (for "'d'") format, regardless of the floating-point format used by
   the platform.

5. "'P'" フォーマット文字はネイティブバイトオーダでのみ利用可能です
   ( デフォルトのネットワークバイトオーダに設定するか、"'@'" バイトオ
   ー ダ指定文字を指定しなければなりません)。"'='" を指定した場合、ホ
   スト 計算機のバイトオーダに基づいてリトルエンディアンとビッグエンデ
   ィア ンのどちらを使うかを決めます。struct モジュールはこの設定をネ
   イティ ブのオーダ設定として解釈しないので、"'P'" を使うことはできま
   せん。

フォーマット文字の前に整数をつけ、繰り返し回数 (count) を指定すること
ができます。例えば、フォーマット文字列 "'4h'" は "'hhhh'" と全く同じ意
味です。

フォーマット文字間の空白文字は無視されます; count とフォーマット文字の
間にはスペースを入れてはいけません。

For the "'s'" format character, the count is interpreted as the size
of the string, not a repeat count like for the other format
characters; for example, "'10s'" means a single 10-byte string, while
"'10c'" means 10 characters. If a count is not given, it defaults to
1.  For packing, the string is truncated or padded with null bytes as
appropriate to make it fit. For unpacking, the resulting string always
has exactly the specified number of bytes.  As a special case, "'0s'"
means a single, empty string (while "'0c'" means 0 characters).

The "'p'" format character encodes a 「Pascal string」, meaning a
short variable-length string stored in a *fixed number of bytes*,
given by the count. The first byte stored is the length of the string,
or 255, whichever is smaller. The bytes of the string follow.  If the
string passed in to "pack()" is too long (longer than the count minus
1), only the leading "count-1" bytes of the string are stored.  If the
string is shorter than "count-1", it is padded with null bytes so that
exactly count bytes in all are used.  Note that for "unpack()", the
"'p'" format character consumes count bytes, but that the string
returned can never contain more than 255 characters.

For the "'P'" format character, the return value is a Python integer
or long integer, depending on the size needed to hold a pointer when
it has been cast to an integer type.  A *NULL* pointer will always be
returned as the Python integer "0". When packing pointer-sized values,
Python integer or long integer objects may be used.  For example, the
Alpha and Merced processors use 64-bit pointer values, meaning a
Python long integer will be used to hold the pointer; other platforms
use 32-bit pointers and will use a Python integer.

"'?'" フォーマット文字では、返り値は "True" または "False" です。パッ
クするときには、引数オブジェクトの論理値としての値が使われます。 0 ま
たは 1 のネイティブや標準の真偽値表現でパックされ、アンパックされると
きはゼロでない値は "True" になります。


使用例
------

注釈: 全ての例は、ビッグエンディアンのマシンで、ネイティブのバイトオ
  ーダ、 サイズおよびアラインメントを仮定します。

基本的な例として、三つの整数をパック/アンパックします:

   >>> from struct import *
   >>> pack('hhl', 1, 2, 3)
   '\x00\x01\x00\x02\x00\x00\x00\x03'
   >>> unpack('hhl', '\x00\x01\x00\x02\x00\x00\x00\x03')
   (1, 2, 3)
   >>> calcsize('hhl')
   8

アンパックした結果のフィールドは、変数に割り当てるか named tuple でラ
ップすることによって名前を付けることができます:

   >>> record = 'raymond   \x32\x12\x08\x01\x08'
   >>> name, serialnum, school, gradelevel = unpack('<10sHHb', record)

   >>> from collections import namedtuple
   >>> Student = namedtuple('Student', 'name serialnum school gradelevel')
   >>> Student._make(unpack('<10sHHb', record))
   Student(name='raymond   ', serialnum=4658, school=264, gradelevel=8)

アラインメントの要求を満たすために必要なパディングが異なるという理由に
より、フォーマット文字の順番がサイズの違いを生み出すことがあります:

   >>> pack('ci', '*', 0x12131415)
   '*\x00\x00\x00\x12\x13\x14\x15'
   >>> pack('ic', 0x12131415, '*')
   '\x12\x13\x14\x15*'
   >>> calcsize('ci')
   8
   >>> calcsize('ic')
   5

以下のフォーマット "'llh0l'" は、long 型が 4 バイトを境界としてそろえ
られていると仮定して、末端に 2 バイトをパディングします:

   >>> pack('llh0l', 1, 2, 3)
   '\x00\x00\x00\x01\x00\x00\x00\x02\x00\x03\x00\x00'

この例はネイティブのサイズとアラインメントが使われているときだけ思った
通りに動きます。標準のサイズとアラインメントはアラインメントの設定では
いかなるアラインメントも行いません。

参考:

  "array" モジュール
     一様なデータ型からなるバイナリ記録データのパック。

  "xdrlib" モジュール
     XDR データのパックおよびアンパック。


クラス
======

"struct" モジュールは次の型を定義します:

class struct.Struct(format)

   フォーマット文字列 *format* に従ってバイナリデータを読み書きする、
   新しい Struct オブジェクトを返します。 Struct オブジェクトを一度作
   ってからそのメソッドを使うと、フォーマット文字列のコンパイルが一度
   で済むので、 "struct" モジュールの関数を同じフォーマットで何度も呼
   び出すよりも効率的です。

   バージョン 2.5 で追加.

   コンパイルされた Struct オブジェクトは以下のメソッドと属性をサポー
   トします:

   pack(v1, v2, ...)

      Identical to the "pack()" function, using the compiled format.
      ("len(result)" will equal "self.size".)

   pack_into(buffer, offset, v1, v2, ...)

      "pack_into()" 関数と同じ、コンパイルされたフォーマットを利用する
      メソッドです。

   unpack(string)

      Identical to the "unpack()" function, using the compiled format.
      ("len(string)" must equal "self.size").

   unpack_from(buffer, offset=0)

      Identical to the "unpack_from()" function, using the compiled
      format. ("len(buffer[offset:])" must be at least "self.size").

   format

      この Struct オブジェクトを作成する時に利用されたフォーマット文字
      列です。

   size

      The calculated size of the struct (and hence of the string)
      corresponding to "format".
