1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
|
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE chapter SYSTEM "chapter.dtd">
<chapter>
<header>
<copyright>
<year>1999</year>
<year>2013</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
The contents of this file are subject to the Erlang Public License,
Version 1.1, (the "License"); you may not use this file except in
compliance with the License. You should have received a copy of the
Erlang Public License along with this software. If not, it can be
retrieved online at http://www.erlang.org/.
Software distributed under the License is distributed on an "AS IS"
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and limitations
under the License.
</legalnotice>
<title>The Erlang I/O-protocol</title>
<prepared>Patrik Nyblom</prepared>
<responsible></responsible>
<docno></docno>
<approved></approved>
<checked></checked>
<date>2009-02-25</date>
<rev>PA1</rev>
<file>io_protocol.xml</file>
</header>
<p>The I/O-protocol in Erlang specifies a way for a client to communicate
with an I/O server and vice versa. The I/O server is a process that handles
the requests and performs the requested task on e.g. an IO device. The
client is any Erlang process wishing to read or write data from/to the
IO device.</p>
<p>The common I/O-protocol has been present in OTP since the
beginning, but has been fairly undocumented and has also somewhat
evolved over the years. In an addendum to Robert Virdings rationale
the original I/O-protocol is described. This document describes the
current I/O-protocol.</p>
<p>The original I/O-protocol was simple and flexible. Demands for spacial
and execution time efficiency has triggered extensions to the protocol
over the years, making the protocol larger and somewhat less easy to
implement than the original. It can certainly be argued that the
current protocol is too complex, but this text describes how it looks
today, not how it should have looked.</p>
<p>The basic ideas from the original protocol still hold. The I/O server
and client communicate with one single, rather simplistic protocol and
no server state is ever present in the client. Any I/O server can be
used together with any client code and client code need not be aware
of the actual IO device the I/O server communicates with.</p>
<section>
<title>Protocol Basics</title>
<p>As described in Robert's paper, I/O servers and clients communicate using
<c>io_request</c>/<c>io_reply</c> tuples as follows:</p>
<p><em>{io_request, From, ReplyAs, Request}</em><br/>
<em>{io_reply, ReplyAs, Reply}</em></p>
<p>The client sends an <c>io_request</c> tuple to the I/O server and
the server eventually sends a corresponding <c>io_reply</c> tuple.</p>
<list type="bulleted">
<item><c>From</c> is the <c>pid()</c> of the client, the process which
the I/O server sends the IO reply to.</item>
<item><c>ReplyAs</c> can be any datum and is returned in the corresponding
<c>io_reply</c>. The <seealso marker="stdlib:io">io</seealso> module simply uses the pid()
of the I/O server as the <c>ReplyAs</c> datum, but a more complicated client
could have several outstanding I/O requests to the same I/O server and
would then use i.e. a <c>reference()</c> or something else to differentiate among
the incoming IO replies. The <c>ReplyAs</c> element should be considered
opaque by the I/O server. Note that the <c>pid()</c> of the I/O server is not
explicitly present in the <c>io_reply</c> tuple. The reply can be sent from any
process, not necessarily the actual I/O server. The <c>ReplyAs</c> element is
the only thing that connects one I/O request with an I/O-reply.</item>
<item><c>Request</c> and <c>Reply</c> are described below.</item>
</list>
<p>When an I/O server receives an <c>io_request</c> tuple, it acts upon the actual
<c>Request</c> part and eventually sends an <c>io_reply</c> tuple with the corresponding
<c>Reply</c> part.</p>
</section>
<section>
<title>Output Requests</title>
<p>To output characters on an IO device, the following <c>Request</c>s exist:</p>
<p>
<em>{put_chars, Encoding, Characters}</em><br/>
<em>{put_chars, Encoding, Module, Function, Args}</em>
</p>
<list type="bulleted">
<item><c>Encoding</c> is either <c>unicode</c> or <c>latin1</c>, meaning that the
characters are (in case of binaries) encoded as either UTF-8 or
ISO-latin-1 (pure bytes). A well behaved I/O server should also
return error if list elements contain integers > 255 when
<c>Encoding</c> is set to <c>latin1</c>. Note that this does not in any way tell
how characters should be put on the actual IO device or how the
I/O server should handle them. Different I/O servers may handle the
characters however they want, this simply tells the I/O server which
format the data is expected to have. In the <c>Module</c>/<c>Function</c>/<c>Args</c>
case, <c>Encoding</c> tells which format the designated function
produces. Note that byte-oriented data is simplest sent using the ISO-latin-1
encoding.</item>
<item>Characters are the data to be put on the IO device. If <c>Encoding</c> is
<c>latin1</c>, this is an <c>iolist()</c>. If <c>Encoding</c> is <c>unicode</c>, this is an
Erlang standard mixed Unicode list (one integer in a list per
character, characters in binaries represented as UTF-8).</item>
<item><c>Module</c>, <c>Function</c>, and <c>Args</c> denote a function which will be called to
produce the data (like <c>io_lib:format/2</c>). <c>Args</c> is a list of arguments
to the function. The function should produce data in the given
<c>Encoding</c>. The I/O server should call the function as
<c>apply(Mod, Func, Args)</c> and will put the returned data on the IO device as if it was sent
in a <c>{put_chars, Encoding, Characters}</c> request. If the function
returns anything else than a binary or list or throws an exception,
an error should be sent back to the client.</item>
</list>
<p>The I/O server replies to the client with an <c>io_reply</c> tuple where the <c>Reply</c>
element is one of:</p>
<p>
<em>ok</em><br/>
<em>{error, Error}</em>
</p>
<list type="bulleted">
<item><c>Error</c> describes the error to the client, which may do whatever
it wants with it. The Erlang <seealso marker="stdlib:io">io</seealso>
module typically returns it as is.</item>
</list>
<p>For backward compatibility the following <c>Request</c>s should also be
handled by an I/O server (these requests should not be present after
R15B of OTP):</p>
<p>
<em>{put_chars, Characters}</em><br/>
<em>{put_chars, Module, Function, Args}</em>
</p>
<p>These should behave as <c>{put_chars, latin1, Characters}</c> and
<c>{put_chars, latin1, Module, Function, Args}</c> respectively. </p>
</section>
<section>
<title>Input Requests</title>
<p>To read characters from an IO device, the following <c>Request</c>s exist:</p>
<p><em>{get_until, Encoding, Prompt, Module, Function, ExtraArgs}</em></p>
<list type="bulleted">
<item><c>Encoding</c> denotes how data is to be sent back to the client and
what data is sent to the function denoted by
<c>Module</c>/<c>Function</c>/<c>ExtraArgs</c>. If the function supplied returns data as a
list, the data is converted to this encoding. If however the
function supplied returns data in some other format, no conversion
can be done and it is up to the client supplied function to return
data in a proper way. If <c>Encoding</c> is <c>latin1</c>, lists of integers
0..255 or binaries containing plain bytes are sent back to the
client when possible; if <c>Encoding</c> is <c>unicode</c>, lists with integers in
the whole Unicode range or binaries encoded in UTF-8 are sent to the
client. The user supplied function will always see lists of integers, never
binaries, but the list may contain numbers > 255 if the <c>Encoding</c> is
<c>unicode</c>.</item>
<item><c>Prompt</c> is a list of characters (not mixed, no binaries) or an atom
to be output as a prompt for input on the IO device. <c>Prompt</c> is
often ignored by the I/O server and if set to <c>''</c> it should always
be ignored (and result in nothing being written to the IO device).</item>
<item><p><c>Module</c>, <c>Function</c>, and <c>ExtraArgs</c> denote a function and arguments to
determine when enough data is written. The function should take two
additional arguments, the last state, and a list of characters. The
function should return one of:</p>
<p>
<em>{done, Result, RestChars}</em><br/>
<em>{more, Continuation}</em>
</p>
<p>The <c>Result</c> can be any Erlang term, but if it is a <c>list()</c>, the
I/O server may convert it to a <c>binary()</c> of appropriate format before
returning it to the client, if the I/O server is set in binary mode (see
below).</p>
<p>The function will be called with the data the I/O server finds on
its IO device, returning <c>{done, Result, RestChars}</c> when enough data is
read (in which case <c>Result</c> is sent to the client and <c>RestChars</c> is
kept in the I/O server as a buffer for subsequent input) or
<c>{more, Continuation}</c>, indicating that more characters are needed to
complete the request. The <c>Continuation</c> will be sent as the state in
subsequent calls to the function when more characters are
available. When no more characters are available, the function
shall return <c>{done, eof, Rest}</c>.
The initial state is the empty list and the data when an
end of file is reached on the IO device is the atom <c>eof</c>. An emulation
of the <c>get_line</c> request could be (inefficiently) implemented using
the following functions:</p>
<code>
-module(demo).
-export([until_newline/3, get_line/1]).
until_newline(_ThisFar,eof,_MyStopCharacter) ->
{done,eof,[]};
until_newline(ThisFar,CharList,MyStopCharacter) ->
case
lists:splitwith(fun(X) -> X =/= MyStopCharacter end, CharList)
of
{L,[]} ->
{more,ThisFar++L};
{L2,[MyStopCharacter|Rest]} ->
{done,ThisFar++L2++[MyStopCharacter],Rest}
end.
get_line(IoServer) ->
IoServer ! {io_request,
self(),
IoServer,
{get_until, unicode, '', ?MODULE, until_newline, [$\n]}},
receive
{io_reply, IoServer, Data} ->
Data
end.
</code>
<p>Note especially that the last element in the <c>Request</c> tuple (<c>[$\n]</c>)
is appended to the argument list when the function is called. The
function should be called like
<c>apply(Module, Function, [ State, Data | ExtraArgs ])</c> by the I/O server</p>
</item>
</list>
<p>A fixed number of characters is requested using this <c>Request</c>:</p>
<p>
<em>{get_chars, Encoding, Prompt, N}</em>
</p>
<list type="bulleted">
<item><c>Encoding</c> and <c>Prompt</c> as for <c>get_until</c>.</item>
<item><c>N</c> is the number of characters to be read from the IO device.</item>
</list>
<p>A single line (like in the example above) is requested with this <c>Request</c>:</p>
<p>
<em>{get_line, Encoding, Prompt}</em>
</p>
<list type="bulleted">
<item><c>Encoding</c> and <c>Prompt</c> as above.</item>
</list>
<p>Obviously, the <c>get_chars</c> and <c>get_line</c> could be implemented with the
<c>get_until</c> request (and indeed they were originally), but demands for
efficiency has made these additions necessary.</p>
<p>The I/O server replies to the client with an <c>io_reply</c> tuple where the <c>Reply</c>
element is one of:</p>
<p>
<em>Data</em><br/>
<em>eof</em><br/>
<em>{error, Error}</em>
</p>
<list type="bulleted">
<item><c>Data</c> is the characters read, in either list or binary form
(depending on the I/O server mode, see below).</item>
<item><c>Error</c> describes the error to the client, which may do whatever it
wants with it. The Erlang <seealso marker="stdlib:io">io</seealso>
module typically returns it as is.</item>
<item><c>eof</c> is returned when input end is reached and no more data is
available to the client process.</item>
</list>
<p>For backward compatibility the following <c>Request</c>s should also be
handled by an I/O server (these reqeusts should not be present after
R15B of OTP):</p>
<p>
<em>{get_until, Prompt, Module, Function, ExtraArgs}</em><br/>
<em>{get_chars, Prompt, N}</em><br/>
<em>{get_line, Prompt}</em><br/>
</p>
<p>These should behave as <c>{get_until, latin1, Prompt, Module, Function,
ExtraArgs}</c>, <c>{get_chars, latin1, Prompt, N}</c> and <c>{get_line, latin1,
Prompt}</c> respectively.</p>
</section>
<section>
<title>I/O-server Modes</title>
<p>Demands for efficiency when reading data from an I/O server has not
only lead to the addition of the <c>get_line</c> and <c>get_chars</c> requests, but
has also added the concept of I/O server options. No options are
mandatory to implement, but all I/O servers in the Erlang standard
libraries honor the <c>binary</c> option, which allows the <c>Data</c> element of the
<c>io_reply</c> tuple to be a binary instead of a list <em>when possible</em>.
If the data is sent as a binary, Unicode data will be sent in the
standard Erlang Unicode
format, i.e. UTF-8 (note that the function of the <c>get_until</c> request still gets
list data regardless of the I/O server mode).</p>
<p>Note that i.e. the <c>get_until</c> request allows for a function with the data specified as always being a list. Also the return value data from such a function can be of any type (as is indeed the case when an <c>io:fread</c> request is sent to an I/O server). The client has to be prepared for data received as answers to those requests to be in a variety of forms, but the I/O server should convert the results to binaries whenever possible (i.e. when the function supplied to <c>get_until</c> actually returns a list). The example shown later in this text does just that.</p>
<p>An I/O-server in binary mode will affect the data sent to the client,
so that it has to be able to handle binary data. For convenience, it
is possible to set and retrieve the modes of an I/O server using the
following I/O requests:</p>
<p>
<em>{setopts, Opts}</em>
</p>
<list type="bulleted">
<item><c>Opts</c> is a list of options in the format recognized by <seealso marker="stdlib:proplists">proplists</seealso> (and
of course by the I/O server itself).</item>
</list>
<p>As an example, the I/O server for the interactive shell (in <c>group.erl</c>)
understands the following options:</p>
<p>
<em>{binary, boolean()}</em> (or <em>binary</em>/<em>list</em>)<br/>
<em>{echo, boolean()}</em><br/>
<em>{expand_fun, fun()}</em><br/>
<em>{encoding, unicode/latin1}</em> (or <em>unicode</em>/<em>latin1</em>)
</p>
<p>- of which the <c>binary</c> and <c>encoding</c> options are common for all
I/O servers in OTP, while <c>echo</c> and <c>expand</c> are valid only for this
I/O server. It is worth noting that the <c>unicode</c> option notifies how
characters are actually put on the physical IO device, i.e. if the
terminal per se is Unicode aware, it does not affect how characters
are sent in the I/O-protocol, where each request contains encoding
information for the provided or returned data.</p>
<p>The I/O server should send one of the following as <c>Reply</c>:</p>
<p>
<em>ok</em><br/>
<em>{error, Error}</em>
</p>
<p>An error (preferably <c>enotsup</c>) is to be expected if the option is
not supported by the I/O server (like if an <c>echo</c> option is sent in a
<c>setopts</c> request to a plain file).</p>
<p>To retrieve options, this request is used:</p>
<p>
<em>getopts</em>
</p>
<p>The <c>getopts</c> request asks for a complete list of all options
supported by the I/O server as well as their current values.</p>
<p>The I/O server replies:</p>
<p>
<em>OptList</em><br/>
<em>{error, Error}</em>
</p>
<list type="bulleted">
<item><c>OptList</c> is a list of tuples <c>{Option, Value}</c> where <c>Option</c> is always
an atom.</item>
</list>
</section>
<section>
<title>Multiple I/O Requests</title>
<p>The <c>Request</c> element can in itself contain several <c>Request</c>s by using
the following format:</p>
<p>
<em>{requests, Requests}</em>
</p>
<list type="bulleted">
<item><c>Requests</c> is a list of valid <c>io_request</c> tuples for the protocol, they
shall be executed in the order in which they appear in the list and
the execution should continue until one of the requests result in an
error or the list is consumed. The result of the last request is
sent back to the client.</item>
</list>
<p>The I/O server can for a list of requests send any of the valid results in
the reply:</p>
<p>
<em>ok</em><br/>
<em>{ok, Data}</em><br/>
<em>{ok, Options}</em><br/>
<em>{error, Error}</em>
</p>
<p>- depending on the actual requests in the list.</p>
</section>
<section>
<title>Optional I/O Requests</title>
<p>The following I/O request is optional to implement and a client
should be prepared for an error return:</p>
<p>
<em>{get_geometry, Geometry}</em>
</p>
<list type="bulleted">
<item><c>Geometry</c> is either the atom <c>rows</c> or the atom <c>columns</c>.</item>
</list>
<p>The I/O server should send the <c>Reply</c> as:</p>
<p>
<em>{ok, N}</em><br/>
<em>{error, Error}</em>
</p>
<list type="bulleted">
<item><c>N</c> is the number of character rows or columns the IO device has, if
applicable to the IO device the I/O server handles, otherwise <c>{error,
enotsup}</c> is a good answer.</item>
</list>
</section>
<section>
<title>Unimplemented Request Types</title>
<p>If an I/O server encounters a request it does not recognize (i.e. the
<c>io_request</c> tuple is in the expected format, but the actual <c>Request</c> is
unknown), the I/O server should send a valid reply with the error tuple:</p>
<p>
<em>{error, request}</em>
</p>
<p>This makes it possible to extend the protocol with optional requests
and for the clients to be somewhat backwards compatible.</p>
</section>
<section>
<title>An Annotated and Working Example I/O Server</title>
<p>An I/O server is any process capable of handling the I/O protocol. There is
no generic I/O server behavior, but could well be. The framework is
simple enough, a process handling incoming requests, usually both
I/O-requests and other IO device-specific requests (for i.e. positioning,
closing etc.).</p>
<p>Our example I/O server stores characters in an ETS table, making up a
fairly crude ram-file (it is probably not useful, but working).</p>
<p>The module begins with the usual directives, a function to start the
I/O server and a main loop handling the requests:</p>
<code>
-module(ets_io_server).
-export([start_link/0, init/0, loop/1, until_newline/3, until_enough/3]).
-define(CHARS_PER_REC, 10).
-record(state, {
table,
position, % absolute
mode % binary | list
}).
start_link() ->
spawn_link(?MODULE,init,[]).
init() ->
Table = ets:new(noname,[ordered_set]),
?MODULE:loop(#state{table = Table, position = 0, mode=list}).
loop(State) ->
receive
{io_request, From, ReplyAs, Request} ->
case request(Request,State) of
{Tag, Reply, NewState} when Tag =:= ok; Tag =:= error ->
reply(From, ReplyAs, Reply),
?MODULE:loop(NewState);
{stop, Reply, _NewState} ->
reply(From, ReplyAs, Reply),
exit(Reply)
end;
%% Private message
{From, rewind} ->
From ! {self(), ok},
?MODULE:loop(State#state{position = 0});
_Unknown ->
?MODULE:loop(State)
end.
</code>
<p>The main loop receives messages from the client (which might be using
the <seealso marker="stdlib:io">io</seealso> module to send requests).
For each request the function
<c>request/2</c> is called and a reply is eventually sent using the <c>reply/3</c>
function.</p>
<p>The "private" message <c>{From, rewind}</c> results in the
current position in the pseudo-file to be reset to 0 (the beginning of
the "file"). This is a typical example of IO device-specific
messages not being part of the I/O-protocol. It is usually a bad idea
to embed such private messages in <c>io_request</c> tuples, as that might be
confusing to the reader.</p>
<p>Let us look at the reply function first...</p>
<code>
reply(From, ReplyAs, Reply) ->
From ! {io_reply, ReplyAs, Reply}.
</code>
<p>Simple enough, it sends the <c>io_reply</c> tuple back to the client,
providing the <c>ReplyAs</c> element received in the request along with the
result of the request, as described above.</p>
<p>Now look at the different requests we need to handle. First the
requests for writing characters:</p>
<code>
request({put_chars, Encoding, Chars}, State) ->
put_chars(unicode:characters_to_list(Chars,Encoding),State);
request({put_chars, Encoding, Module, Function, Args}, State) ->
try
request({put_chars, Encoding, apply(Module, Function, Args)}, State)
catch
_:_ ->
{error, {error,Function}, State}
end;
</code>
<p>The <c>Encoding</c> tells us how the characters in the request are
represented. We want to store the characters as lists in the
ETS table, so we convert them to lists using the
<seealso marker="stdlib:unicode#characters_to_list/2"><c>unicode:characters_to_list/2</c></seealso> function. The conversion function
conveniently accepts the encoding types <c>unicode</c> or <c>latin1</c>, so we can
use <c>Encoding</c> directly.</p>
<p>When <c>Module</c>, <c>Function</c> and <c>Arguments</c> are provided, we simply apply it
and do the same thing with the result as if the data was provided
directly.</p>
<p>Let us handle the requests for retrieving data too:</p>
<code>
request({get_until, Encoding, _Prompt, M, F, As}, State) ->
get_until(Encoding, M, F, As, State);
request({get_chars, Encoding, _Prompt, N}, State) ->
%% To simplify the code, get_chars is implemented using get_until
get_until(Encoding, ?MODULE, until_enough, [N], State);
request({get_line, Encoding, _Prompt}, State) ->
%% To simplify the code, get_line is implemented using get_until
get_until(Encoding, ?MODULE, until_newline, [$\n], State);
</code>
<p>Here we have cheated a little by more or less only implementing
<c>get_until</c> and using internal helpers to implement <c>get_chars</c> and
<c>get_line</c>. In production code, this might be too inefficient, but that
of course depends on the frequency of the different requests. Before
we start actually implementing the functions <c>put_chars/2</c> and
<c>get_until/5</c>, let us look into the few remaining requests:</p>
<code>
request({get_geometry,_}, State) ->
{error, {error,enotsup}, State};
request({setopts, Opts}, State) ->
setopts(Opts, State);
request(getopts, State) ->
getopts(State);
request({requests, Reqs}, State) ->
multi_request(Reqs, {ok, ok, State});
</code>
<p>The <c>get_geometry</c> request has no meaning for this I/O server, so the
reply will be <c>{error, enotsup}</c>. The only option we handle is the
<c>binary</c>/<c>list</c> option, which is done in separate functions.</p>
<p>The multi-request tag (<c>requests</c>) is handled in a separate loop
function applying the requests in the list one after another,
returning the last result.</p>
<p>What is left is to handle backward compatibility and the <seealso marker="kernel:file">file</seealso> module
(which uses the old requests until backward compatibility with pre-R13
nodes is no longer needed). Note that the I/O server will not work with
a simple <c>file:write/2</c> if these are not added:</p>
<code>
request({put_chars,Chars}, State) ->
request({put_chars,latin1,Chars}, State);
request({put_chars,M,F,As}, State) ->
request({put_chars,latin1,M,F,As}, State);
request({get_chars,Prompt,N}, State) ->
request({get_chars,latin1,Prompt,N}, State);
request({get_line,Prompt}, State) ->
request({get_line,latin1,Prompt}, State);
request({get_until, Prompt,M,F,As}, State) ->
request({get_until,latin1,Prompt,M,F,As}, State);
</code>
<p>OK, what is left now is to return <c>{error, request}</c> if the request is
not recognized:</p>
<code>
request(_Other, State) ->
{error, {error, request}, State}.
</code>
<p>Let us move further and actually handle the different requests, first
the fairly generic multi-request type:</p>
<code>
multi_request([R|Rs], {ok, _Res, State}) ->
multi_request(Rs, request(R, State));
multi_request([_|_], Error) ->
Error;
multi_request([], Result) ->
Result.
</code>
<p>We loop through the requests one at the time, stopping when we either
encounter an error or the list is exhausted. The last return value is
sent back to the client (it is first returned to the main loop and then
sent back by the function <c>io_reply</c>).</p>
<p>The <c>getopts</c> and <c>setopts</c> requests are also simple to handle, we just
change or read our state record:</p>
<code>
setopts(Opts0,State) ->
Opts = proplists:unfold(
proplists:substitute_negations(
[{list,binary}],
Opts0)),
case check_valid_opts(Opts) of
true ->
case proplists:get_value(binary, Opts) of
true ->
{ok,ok,State#state{mode=binary}};
false ->
{ok,ok,State#state{mode=binary}};
_ ->
{ok,ok,State}
end;
false ->
{error,{error,enotsup},State}
end.
check_valid_opts([]) ->
true;
check_valid_opts([{binary,Bool}|T]) when is_boolean(Bool) ->
check_valid_opts(T);
check_valid_opts(_) ->
false.
getopts(#state{mode=M} = S) ->
{ok,[{binary, case M of
binary ->
true;
_ ->
false
end}],S}.
</code>
<p>As a convention, all I/O servers handle both <c>{setopts, [binary]}</c>,
<c>{setopts, [list]}</c> and <c>{setopts,[{binary, boolean()}]}</c>, hence the trick
with <c>proplists:substitute_negations/2</c> and <c>proplists:unfold/1</c>. If
invalid options are sent to us, we send <c>{error, enotsup}</c> back to the
client.</p>
<p>The <c>getopts</c> request should return a list of <c>{Option, Value}</c> tuples,
which has the twofold function of providing both the current values
and the available options of this I/O server. We have only one option,
and hence return that.</p>
<p>So far our I/O server has been fairly generic (except for the <c>rewind</c>
request handled in the main loop and the creation of an ETS table).
Most I/O servers contain code similar to the one above.</p>
<p>To make the example runnable, we now start implementing the actual
reading and writing of the data to/from the ETS table. First the
<c>put_chars/3</c> function:</p>
<code>
put_chars(Chars, #state{table = T, position = P} = State) ->
R = P div ?CHARS_PER_REC,
C = P rem ?CHARS_PER_REC,
[ apply_update(T,U) || U <- split_data(Chars, R, C) ],
{ok, ok, State#state{position = (P + length(Chars))}}.
</code>
<p>We already have the data as (Unicode) lists and therefore just split
the list in runs of a predefined size and put each run in the
table at the current position (and forward). The functions
<c>split_data/3</c> and <c>apply_update/2</c> are implemented below.</p>
<p>Now we want to read data from the table. The <c>get_until/5</c> function reads
data and applies the function until it says it is done. The result is
sent back to the client:</p>
<code>
get_until(Encoding, Mod, Func, As,
#state{position = P, mode = M, table = T} = State) ->
case get_loop(Mod,Func,As,T,P,[]) of
{done,Data,_,NewP} when is_binary(Data); is_list(Data) ->
if
M =:= binary ->
{ok,
unicode:characters_to_binary(Data, unicode, Encoding),
State#state{position = NewP}};
true ->
case check(Encoding,
unicode:characters_to_list(Data, unicode))
of
{error, _} = E ->
{error, E, State};
List ->
{ok, List,
State#state{position = NewP}}
end
end;
{done,Data,_,NewP} ->
{ok, Data, State#state{position = NewP}};
Error ->
{error, Error, State}
end.
get_loop(M,F,A,T,P,C) ->
{NewP,L} = get(P,T),
case catch apply(M,F,[C,L|A]) of
{done, List, Rest} ->
{done, List, [], NewP - length(Rest)};
{more, NewC} ->
get_loop(M,F,A,T,NewP,NewC);
_ ->
{error,F}
end.
</code>
<p>Here we also handle the mode (<c>binary</c> or <c>list</c>) that can be set by
the <c>setopts</c> request. By default, all OTP I/O servers send data back to
the client as lists, but switching mode to <c>binary</c> might increase
efficiency if the I/O server handles it in an appropriate way. The
implementation of <c>get_until</c> is hard to get efficient as the supplied
function is defined to take lists as arguments, but <c>get_chars</c> and
<c>get_line</c> can be optimized for binary mode. This example does not
optimize anything however. It is important though that the returned
data is of the right type depending on the options set, so we convert
the lists to binaries in the correct encoding <em>if possible</em>
before returning. The function supplied in the <c>get_until</c> request tuple may,
as its final result return anything, so only functions actually
returning lists can get them converted to binaries. If the request
contained the encoding tag <c>unicode</c>, the lists can contain all Unicode
codepoints and the binaries should be in UTF-8, if the encoding tag
was <c>latin1</c>, the client should only get characters in the range
0..255. The function <c>check/2</c> takes care of not returning arbitrary
Unicode codepoints in lists if the encoding was given as <c>latin1</c>. If
the function did not return a list, the check cannot be performed and
the result will be that of the supplied function untouched.</p>
<p>Now we are more or less done. We implement the utility functions below
to actually manipulate the table:</p>
<code>
check(unicode, List) ->
List;
check(latin1, List) ->
try
[ throw(not_unicode) || X <- List,
X > 255 ],
List
catch
throw:_ ->
{error,{cannot_convert, unicode, latin1}}
end.
</code>
<p>The function check takes care of providing an error tuple if Unicode
codepoints above 255 is to be returned if the client requested
latin1.</p>
<p>The two functions <c>until_newline/3</c> and <c>until_enough/3</c> are helpers used
together with the <c>get_until/5</c> function to implement <c>get_chars</c> and
<c>get_line</c> (inefficiently):</p>
<code>
until_newline([],eof,_MyStopCharacter) ->
{done,eof,[]};
until_newline(ThisFar,eof,_MyStopCharacter) ->
{done,ThisFar,[]};
until_newline(ThisFar,CharList,MyStopCharacter) ->
case
lists:splitwith(fun(X) -> X =/= MyStopCharacter end, CharList)
of
{L,[]} ->
{more,ThisFar++L};
{L2,[MyStopCharacter|Rest]} ->
{done,ThisFar++L2++[MyStopCharacter],Rest}
end.
until_enough([],eof,_N) ->
{done,eof,[]};
until_enough(ThisFar,eof,_N) ->
{done,ThisFar,[]};
until_enough(ThisFar,CharList,N)
when length(ThisFar) + length(CharList) >= N ->
{Res,Rest} = my_split(N,ThisFar ++ CharList, []),
{done,Res,Rest};
until_enough(ThisFar,CharList,_N) ->
{more,ThisFar++CharList}.
</code>
<p>As can be seen, the functions above are just the type of functions
that should be provided in <c>get_until</c> requests.</p>
<p>Now we only need to read and write the table in an appropriate way to
complete the I/O server:</p>
<code>
get(P,Tab) ->
R = P div ?CHARS_PER_REC,
C = P rem ?CHARS_PER_REC,
case ets:lookup(Tab,R) of
[] ->
{P,eof};
[{R,List}] ->
case my_split(C,List,[]) of
{_,[]} ->
{P+length(List),eof};
{_,Data} ->
{P+length(Data),Data}
end
end.
my_split(0,Left,Acc) ->
{lists:reverse(Acc),Left};
my_split(_,[],Acc) ->
{lists:reverse(Acc),[]};
my_split(N,[H|T],Acc) ->
my_split(N-1,T,[H|Acc]).
split_data([],_,_) ->
[];
split_data(Chars, Row, Col) ->
{This,Left} = my_split(?CHARS_PER_REC - Col, Chars, []),
[ {Row, Col, This} | split_data(Left, Row + 1, 0) ].
apply_update(Table, {Row, Col, List}) ->
case ets:lookup(Table,Row) of
[] ->
ets:insert(Table,{Row, lists:duplicate(Col,0) ++ List});
[{Row, OldData}] ->
{Part1,_} = my_split(Col,OldData,[]),
{_,Part2} = my_split(Col+length(List),OldData,[]),
ets:insert(Table,{Row, Part1 ++ List ++ Part2})
end.
</code>
<p>The table is read or written in chunks of <c>?CHARS_PER_REC</c>, overwriting
when necessary. The implementation is obviously not efficient, it is
just working.</p>
<p>This concludes the example. It is fully runnable and you can read or
write to the I/O server by using i.e. the <seealso marker="stdlib:io">io</seealso> module or even the <seealso marker="kernel:file">file</seealso>
module. It is as simple as that to implement a fully fledged I/O server
in Erlang.</p>
</section>
</chapter>
|