"mmap" --- メモリマップファイルのサポート
*****************************************

======================================================================

利用可能な環境: WASI 以外。

このモジュールは WebAssembly では動作しないか、利用不可です。詳しくは
、WebAssembly プラットフォーム を見てください。

メモリにマップされたファイルオブジェクトは、 "bytearray" と *ファイル
オブジェクト* の両方のように振舞います。しかし通常の文字列オブジェクト
とは異なり、これらは可変です。 "bytearray" が期待されるほとんどの場所
で mmap オブジェクトを利用できます。例えば、メモリマップファイルを探索
するために "re" モジュールを使うことができます。それらは可変なので、
"obj[index] = 97" のように文字を変換できますし、スライスを使うことで
"obj[i1:i2] = b'...'" のように部分文字列を変換することができます。現在
のファイル位置をデータの始めとする読込みや書込み、ファイルの異なる位置
へ "seek()" することもできます。

メモリマップドファイルは Unix と Windows で異なる "mmap" コンストラク
タで生成されます。どちらの場合も、更新用に開かれたファイル記述子を渡さ
なければなりません。既存の Python ファイルオブジェクトをマップしたけれ
ば、 "fileno()" メソッドを使って *fileno* パラメータの正しい値を取得し
てください。そうでなければ、 "os.open()" 関数を使ってファイルを開けま
す。この関数はファイルディスクリプタを直接返します(処理が終わったら、
やはりファイルを閉じる必要があります)。

注釈:

  書き込み可能でバッファされたファイルへのメモリマップファイルを作りた
  いのであれば、まず最初にファイルの "flush()" を呼び出すべきです。こ
  れはバッファへのローカルな修正がマッピングで実際に利用可能になること
  を保障するために必要です。

Unix バージョンと Windows バージョンのどちらのコンストラクタについても
、オプションのキーワード・パラメータとして *access* を指定できます。
*access* は4つの値の内の1つを受け入れます。 "ACCESS_READ" は読み出し専
用、 "ACCESS_WRITE" は書き込み可能、 "ACCESS_COPY" はコピーした上での
書き込み、"ACCESS_DEFAULT" は *prot* に従います。 *access* は Unix と
Windows の両方で使用することができます。 *access* が指定されない場合、
Windows の mmap は書き込み可能マップを返します。 3つのアクセス型すべて
に対する初期メモリ値は、指定されたファイルから得られます。
"ACCESS_READ" 型のメモリマップに対して書き込むと "TypeError" 例外を送
出します。 "ACCESS_WRITE" 型のメモリマップへの書き込みはメモリと元のフ
ァイルの両方に影響を与えます。 "ACCESS_COPY" 型のメモリマップへの書き
込みはメモリに影響を与えますが、元のファイルを更新することはありません
。

バージョン 3.7 で変更: 定数 "ACCESS_DEFAULT" が追加されました。

無名メモリ(anonymous memory)にマップするためには fileno として -1 を渡
し、length を与えてください。

class mmap.mmap(fileno, length, tagname=None, access=ACCESS_DEFAULT, offset=0)

   **(Windows バージョン)** ファイルハンドル *fileno* によって指定され
   たファイルから *length* バイトをマップして、 mmap オブジェクトを生
   成します。 *length* が現在のファイルサイズより大きな場合、ファイル
   サイズは *length* を含む大きさにまで拡張されます。 *length* が "0"
   の場合、マップの最大の長さは現在のファイルサイズになります。ただし
   、ファイル自体が空のときは Windows が例外を送出します (Windows では
   空のマップを作成することができません)。

   *tagname* は、 "None" 以外で指定された場合、マップのタグ名を与える
   文字列となります。 Windows は同じファイルに対する様々なマップを持つ
   ことを可能にします。既存のタグの名前を指定すればそのタグがオープン
   され、そうでなければこの名前の新しいタグが作成されます。もしこのパ
   ラメータを省略したり "None" を与えたりしたならば、マップは名前なし
   で作成されます。 "tagname" パラメータの使用の回避は、あなたのコード
   を Unix と Windows の間で移植可能にしておくのを助けてくれるでしょう
   。

   *offset* は非負整数のオフセットとして指定できます。mmap の参照はフ
   ァイルの先頭からのオフセットに相対的になります。*offset* のデフォル
   トは 0 です。*offset* は  "ALLOCATIONGRANULARITY" の倍数でなければ
   なりません。

   引数 "fileno", "length", "access", "offset" 付きで 監査イベント
   "mmap.__new__" を送出します。

class mmap.mmap(fileno, length, flags=MAP_SHARED, prot=PROT_WRITE | PROT_READ, access=ACCESS_DEFAULT, offset=0, *, trackfd=True)

   **(Unix バージョン)** ファイルディスクリプタ *fileno* で指定された
   ファイルから *length* バイトをマップし、mmap オブジェクトを返します
   。*length* が "0" の場合、マップの最大の長さは "mmap" が呼ばれた時
   点でのファイルサイズになります。

   *flags* specifies the nature of the mapping. "MAP_PRIVATE" creates
   a private copy-on-write mapping, so changes to the contents of the
   mmap object will be private to this process, and "MAP_SHARED"
   creates a mapping that's shared with all other processes mapping
   the same areas of the file.  The default value is "MAP_SHARED".
   Some systems have additional possible flags with the full list
   specified in MAP_* constants.

   *prot* が指定された場合、希望のメモリ保護を与えます。 2つの最も有用
   な値は、 "PROT_READ" と "PROT_WRITE" です。これは、読込み可能または
   書込み可能を指定するものです。 *prot* のデフォルトは "PROT_READ |
   PROT_WRITE" です。

   *access* はオプションのキーワード・パラメータとして、 *flags* と
   *prot* の代わりに指定してもかまいません。 *flags*, *prot* と
   *access* の両方を指定することは間違っています。このパラメータの使用
   法についての情報は、先に述べた *access* の記述を参照してください。

   *offset* may be specified as a non-negative integer offset. mmap
   references will be relative to the offset from the beginning of the
   file. *offset* defaults to 0. *offset* must be a multiple of
   "ALLOCATIONGRANULARITY" which is equal to "PAGESIZE" on Unix
   systems.

   If *trackfd* is "False", the file descriptor specified by *fileno*
   will not be duplicated, and the resulting "mmap" object will not be
   associated with the map's underlying file. This means that the
   "size()" and "resize()" methods will fail. This mode is useful to
   limit the number of open file descriptors.

   macOS において、作成された memory mapping の正当性を確実にするため
   に *fileno* で指定されたファイルディスクリプタは内部で自動的に物理
   的なストレージ (physical backing store) と同期されます。

   バージョン 3.13 で変更: *trackfd* パラメータが追加されました。

   この例は "mmap" の簡潔な使い方を示すものです:

      import mmap

      # write a simple example file
      with open("hello.txt", "wb") as f:
          f.write(b"Hello Python!\n")

      with open("hello.txt", "r+b") as f:
          # memory-map the file, size 0 means whole file
          mm = mmap.mmap(f.fileno(), 0)
          # read content via standard file methods
          print(mm.readline())  # prints b"Hello Python!\n"
          # read content via slice notation
          print(mm[:5])  # prints b"Hello"
          # update content using slice notation;
          # note that new content must have same size
          mm[6:] = b" world!\n"
          # ... and read again using standard file methods
          mm.seek(0)
          print(mm.readline())  # prints b"Hello  world!\n"
          # close the map
          mm.close()

   "mmap" は "with" 文の中でコンテキストマネージャとしても使えます:

      import mmap

      with mmap.mmap(-1, 13) as mm:
          mm.write(b"Hello world!")

   Added in version 3.2: コンテキストマネージャのサポート。

   次の例では無名マップを作り親プロセスと子プロセスの間でデータのやり
   とりをしてみせます:

      import mmap
      import os

      mm = mmap.mmap(-1, 13)
      mm.write(b"Hello world!")

      pid = os.fork()

      if pid == 0:  # In a child process
          mm.seek(0)
          print(mm.readline())

          mm.close()

   引数 "fileno", "length", "access", "offset" 付きで 監査イベント
   "mmap.__new__" を送出します。

   メモリマップファイルオブジェクトは以下のメソッドをサポートしていま
   す:

   close()

      メモリマップファイルを閉じます。この呼出しの後にオブジェクトの他
      のメソッドの呼出すことは、 "ValueError" 例外の送出を引き起こしま
      す。このメソッドは開いたファイルのクローズはしません。

   closed

      ファイルが閉じている場合 "True" となります。

      Added in version 3.2.

   find(sub[, start[, end]])

      オブジェクト内の [*start*, *end*] の範囲に含まれている部分シーケ
      ンス *sub* が見つかった場所の最も小さいインデックスを返します。
      オプションの引数 *start* と *end* はスライスに使われるときのよう
      に解釈されます。失敗したときには "-1" を返します。

      バージョン 3.5 で変更: 書き込み可能な *bytes-like object* を使用
      できるようになりました。

   flush([offset[, size]])

      Flushes changes made to the in-memory copy of a file back to
      disk. Without use of this call there is no guarantee that
      changes are written back before the object is destroyed.  If
      *offset* and *size* are specified, only changes to the given
      range of bytes will be flushed to disk; otherwise, the whole
      extent of the mapping is flushed.  *offset* must be a multiple
      of the "PAGESIZE" or "ALLOCATIONGRANULARITY".

      "None" が返されたら成功を意味します。呼び出しが失敗すると例外が
      送出されます。

      バージョン 3.8 で変更: Previously, a nonzero value was returned
      on success; zero was returned on error under Windows.  A zero
      value was returned on success; an exception was raised on error
      under Unix.

   madvise(option[, start[, length]])

      Send advice *option* to the kernel about the memory region
      beginning at *start* and extending *length* bytes.  *option*
      must be one of the MADV_* constants available on the system.  If
      *start* and *length* are omitted, the entire mapping is spanned.
      On some systems (including Linux), *start* must be a multiple of
      the "PAGESIZE".

      Availability: Systems with the "madvise()" system call.

      Added in version 3.8.

   move(dest, src, count)

      オフセット *src* から始まる *count* バイトをインデックス *dest*
      の位置へコピーします。もし mmap が "ACCESS_READ" で作成されてい
      た場合、 "TypeError" 例外を発生させます。

   read([n])

      現在のファイル位置からの最大 *n* バイトを含む "bytes" を返します
      。引数が省略されるか、 "None" もしくは負の値が指定された場合、現
      在のファイル位置からマップ終端までの全てのバイト列を返します。フ
      ァイル位置は返されたバイト列の直後を指すように更新されます。

      バージョン 3.3 で変更: 引数が省略可能になり、 "None" も受け付け
      るようになりました。

   read_byte()

      現在のファイル位置のバイトを整数値として返し、ファイル位置を 1
      進めます。

   readline()

      Returns a single line, starting at the current file position and
      up to the next newline. The file position is updated to point
      after the bytes that were returned.

   resize(newsize)

      Resizes the map and the underlying file, if any.

      Resizing a map created with *access* of "ACCESS_READ" or
      "ACCESS_COPY", will raise a "TypeError" exception. Resizing a
      map created with with *trackfd* set to "False", will raise a
      "ValueError" exception.

      **On Windows**: Resizing the map will raise an "OSError" if
      there are other maps against the same named file. Resizing an
      anonymous map (ie against the pagefile) will silently create a
      new map with the original data copied over up to the length of
      the new size.

      バージョン 3.11 で変更: Correctly fails if attempting to resize
      when another map is held Allows resize against an anonymous map
      on Windows

   rfind(sub[, start[, end]])

      オブジェクト内の [*start*, *end*] の範囲に含まれている部分シーケ
      ンス *sub* が見つかった場所の最も大きいインデックスを返します。
      オプションの引数 *start* と *end* はスライスに使われるときのよう
      に解釈されます。失敗したときには "-1" を返します。

      バージョン 3.5 で変更: 書き込み可能な *bytes-like object* を使用
      できるようになりました。

   seek(pos[, whence])

      ファイルの現在位置をセットします。 *whence* 引数はオプションであ
      り、デフォルトは "os.SEEK_SET" つまり "0" (絶対位置)です。その他
      の値として、 "os.SEEK_CUR" つまり "1" (現在位置からの相対位置)と
      "os.SEEK_END" つまり "2" (ファイルの終わりからの相対位置)があり
      ます。

      バージョン 3.13 で変更: "None" ではなく新しい絶対位置を返します
      。

   seekable()

      Return whether the file supports seeking, and the return value
      is always "True".

      Added in version 3.13.

   size()

      ファイルの長さを返します。メモリマップ領域のサイズより大きいかも
      しれません。

   tell()

      ファイルポインタの現在位置を返します。

   write(bytes)

      メモリ内のファイルポイントの現在位置に *bytes* のバイト列を書き
      込み、書き込まれたバイト数を返します(もし書き込みが失敗したら
      "ValueError" が送出されるため、"len(bytes)" より少なくなりません
      )。ファイル位置はバイト列が書き込まれた位置に更新されます。もし
      mmapが "ACCESS_READ" とともに作成されていた場合は、書き込みは
      "TypeError" 例外を送出するでしょう。

      バージョン 3.5 で変更: 書き込み可能な *bytes-like object* を使用
      できるようになりました。

      バージョン 3.6 で変更: 書きこまれたバイト数を返すようになりまし
      た。

   write_byte(byte)

      メモリ内のファイル・ポインタの現在位置に整数 *byte* を書き込みま
      す。ファイル位置は "1" だけ進みます。もし mmap が "ACCESS_READ"
      で作成されていた場合、書き込み時に "TypeError" 例外を発生させる
      でしょう。


MADV_* 定数
===========

mmap.MADV_NORMAL
mmap.MADV_RANDOM
mmap.MADV_SEQUENTIAL
mmap.MADV_WILLNEED
mmap.MADV_DONTNEED
mmap.MADV_REMOVE
mmap.MADV_DONTFORK
mmap.MADV_DOFORK
mmap.MADV_HWPOISON
mmap.MADV_MERGEABLE
mmap.MADV_UNMERGEABLE
mmap.MADV_SOFT_OFFLINE
mmap.MADV_HUGEPAGE
mmap.MADV_NOHUGEPAGE
mmap.MADV_DONTDUMP
mmap.MADV_DODUMP
mmap.MADV_FREE
mmap.MADV_NOSYNC
mmap.MADV_AUTOSYNC
mmap.MADV_NOCORE
mmap.MADV_CORE
mmap.MADV_PROTECT
mmap.MADV_FREE_REUSABLE
mmap.MADV_FREE_REUSE

   These options can be passed to "mmap.madvise()".  Not every option
   will be present on every system.

   Availability: Systems with the madvise() system call.

   Added in version 3.8.


MAP_* 定数
==========

mmap.MAP_SHARED
mmap.MAP_PRIVATE
mmap.MAP_32BIT
mmap.MAP_ALIGNED_SUPER
mmap.MAP_ANON
mmap.MAP_ANONYMOUS
mmap.MAP_CONCEAL
mmap.MAP_DENYWRITE
mmap.MAP_EXECUTABLE
mmap.MAP_HASSEMAPHORE
mmap.MAP_JIT
mmap.MAP_NOCACHE
mmap.MAP_NOEXTEND
mmap.MAP_NORESERVE
mmap.MAP_POPULATE
mmap.MAP_RESILIENT_CODESIGN
mmap.MAP_RESILIENT_MEDIA
mmap.MAP_STACK
mmap.MAP_TPRO
mmap.MAP_TRANSLATED_ALLOW_EXECUTE
mmap.MAP_UNIX03

   These are the various flags that can be passed to "mmap.mmap()".
   "MAP_ALIGNED_SUPER" is only available at FreeBSD and "MAP_CONCEAL"
   is only available at OpenBSD.  Note that some options might not be
   present on some systems.

   バージョン 3.10 で変更: Added "MAP_POPULATE" constant.

   Added in version 3.11: Added "MAP_STACK" constant.

   Added in version 3.12: Added "MAP_ALIGNED_SUPER" and "MAP_CONCEAL"
   constants.

   Added in version 3.13: Added "MAP_32BIT", "MAP_HASSEMAPHORE",
   "MAP_JIT", "MAP_NOCACHE", "MAP_NOEXTEND", "MAP_NORESERVE",
   "MAP_RESILIENT_CODESIGN", "MAP_RESILIENT_MEDIA", "MAP_TPRO",
   "MAP_TRANSLATED_ALLOW_EXECUTE", and "MAP_UNIX03" constants.
