LoginSignup
16
1

More than 1 year has passed since last update.

IO data

  • Elixir言語では、IO dataは文字列を効率よく連結する目的でよく活用される
  • バイト(0..255)のリスト

IO data is a data type that can be used as a more efficient alternative to binaries in certain situations.

Building IO data is cheaper than concatenating binaries. Concatenating multiple pieces of IO data just means putting them together inside a list since IO data can be arbitrarily nested, and that's a cheap and efficient operation.

Chardata

  • IO dataと非常に似ている
  • Unicodeの符号点(0..0x10FFFF)のリスト

Chardata is very similar to IO data: the only difference is that integers in IO data represent bytes while integers in chardata represent Unicode code points.

論よりラン

IO.iodata_to_binary/1IO.chardata_to_string/1を使って検証してみます。

迷わず行けよ行けばわかるさ(アントニオ猪木)

人は実行が第一である。書物の如きは心がけさへすれば、実務に服する間には、自然読み得るに至るものなり。(吉田松陰)

似ている点

バイナリのリストを扱うのであれば挙動が全く同じの様子。入れ子になってもOK。

bin1 = <<1, 2, 3>>
bin2 = <<4, 5>>
bin3 = <<6>>

## IO data

IO.iodata_to_binary(bin1)
<<1, 2, 3>>

IO.iodata_to_binary([bin1, 1, [2, 3, bin2], 4 | bin3])
<<1, 2, 3, 1, 2, 3, 4, 5, 4, 6>>

## Chardata

IO.chardata_to_string(bin1)
<<1, 2, 3>>

IO.chardata_to_string([bin1, 1, [2, 3, bin2], 4 | bin3])
<<1, 2, 3, 1, 2, 3, 4, 5, 4, 6>>

異なる点

ASCII文字でないUnicode文字を扱う場合に、IO dataでは対応できない。

## Unicode文字

IO.chardata_to_string('闘魂')
"闘魂"

IO.iodata_to_binary('闘魂')
** (ArgumentError) errors were found at the given arguments:

  * 1st argument: not an iodata term

    :erlang.iolist_to_binary([38360, 39746])
    iex:12: (file)

## ASCII文字

IO.chardata_to_string('fighting spirit')
"fighting spirit"

IO.iodata_to_binary('fighting spirit')
"fighting spirit"

「闘魂」とは己に打ち勝(克)ち、闘いを通じて自分の魂を磨くことである(アントニオ猪木)

符号点の値を探す

豆知識として符号点の値を探す方法をいくつか挙げます。

"闘魂" |> to_charlist
[38360, 39746]

'闘魂'
[38360, 39746]

?闘
38360
?魂
39746

38360 |> IO.inspect(base: :hex)
0x95D8

CJK統合漢字

たまに微妙に変な漢字が出現するのはこれが原因かも?知らんけど。

また収録において、元の各文字集合内で分離されている文字は尊重するが、異なる文字集合に同一の文字が収録されているとみなされるものは、同じ符号位置に割り当てる方針を取っている。この際に集合が膨大であるという理由で、漢字について、中国、日本、韓国の各規格の漢字を統合しCJK統合漢字としたことは大きな議論となった。

ご参考までに

16
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
1