-
Notifications
You must be signed in to change notification settings - Fork 22
/
Pervasives.fs
1386 lines (1133 loc) · 42.4 KB
/
Pervasives.fs
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
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(*
Copyright 2005-2009 Microsoft Corporation
Copyright 2012 Jack Pappas
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
// References:
// http://caml.inria.fr/pub/docs/manual-ocaml/libref/Pervasives.html
/// The initially opened module.
[<AutoOpen>]
[<CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)>]
module FSharp.Compatibility.OCaml.Pervasives
open System
open System.Collections.Generic
open System.IO
open System.Text
#nowarn "62" // compatibility warnings
#nowarn "35" // 'deprecated' warning about redefining '<' etc.
#nowarn "86" // 'deprecated' warning about redefining '<' etc.
#nowarn "60" // override implementations in intrinsic extensions
#nowarn "69" // interface implementations in intrinsic extensions
(*** Exceptions ***)
/// <summary>
/// Raise exception <c>Invalid_argument</c> with the given string.
/// </summary>
let invalid_arg (str : string) =
raise <| Invalid_argument "str"
// exception Exit
(*** Comparisons ***)
/// e1 == e2 tests for physical equality of e1 and e2.
let inline ( == ) x y =
LanguagePrimitives.PhysicalEquality x y
/// Negation of (==).
let inline ( != ) x y =
not <| LanguagePrimitives.PhysicalEquality x y
(*** Boolean operations ***)
// NOTE : The 'not', (&&), and (||) operators are already
// provided in the F# Core Library (FSharp.Core).
[<Obsolete("Deprecated. The (&&) operator should be used instead.")>]
let inline (&) (x : bool) (y : bool) =
x && y
[<Obsolete("Deprecated. The (||) operator should be used instead.")>]
let inline (or) (x : bool) (y : bool) =
x || y
(*** Integer arithmetic ***)
let inline succ (x : int) =
x + 1
let inline pred (x : int) =
x - 1
/// Integer remainder. If y is not zero, the result of x mod y satisfies the following properties:
/// x = (x / y) * y + x mod y and abs(x mod y) <= abs(y) - 1.
/// If y = 0, x mod y raises Division_by_zero. Note that x mod y is negative only if x < 0.
let inline (mod) (x : int) (y : int) =
Operators.(%) x y
/// The greatest representable integer.
let [<Literal>] max_int =
System.Int32.MaxValue
/// The smallest representable integer.
let [<Literal>] min_int =
System.Int32.MinValue
(* Bitwise operations *)
/// Bitwise logical and.
let inline (land) (x : int) (y : int) =
Operators.(&&&) x y
/// Bitwise logical or.
let inline (lor) (x : int) (y : int) =
Operators.(|||) x y
/// Bitwise logical exclusive or.
let inline (lxor) (x : int) (y : int) =
Operators.(^^^) x y
/// Bitwise logical negation.
let inline lnot (x : int) =
Operators.(~~~) x
/// n lsl m shifts n to the left by m bits.
/// The result is unspecified if m < 0 or m >= bitsize, where bitsize is 32 on a 32-bit platform and 64 on a 64-bit platform.
let inline (lsl) (x : int) (y : int) =
Operators.(<<<) x y
/// n lsr m shifts n to the right by m bits.
/// This is a logical shift: zeroes are inserted regardless of the sign of n. The result is unspecified if m < 0 or m >= bitsize.
let inline (lsr) (x : int) (y : int) =
int32 (uint32 x >>> y)
/// n asr m shifts n to the right by m bits.
/// This is an arithmetic shift: the sign bit of n is replicated. The result is unspecified if m < 0 or m >= bitsize.
let inline (asr) (x : int) (y : int) =
Operators.(>>>) x y
(*** Floating-point arithmetic ***)
/// Unary negation.
let inline ( ~-. ) (x : float) = -x
/// Unary addition.
let inline ( ~+. ) (x : float) = x
/// Floating-point addition.
let inline ( +. ) (x : float) (y : float) = x + y
/// Floating-point subtraction.
let inline ( -. ) (x : float) (y : float) = x - y
/// Floating-point multiplication.
let inline ( *. ) (x : float) (y : float) = x * y
/// Floating-point division.
let inline ( /. ) (x : float) (y : float) = x / y
/// Exponentiation.
let inline ( ** ) (x : float) (y : float) =
Math.Pow (x, y)
// NOTE : The following functions are already
// provided in the F# Core Library (FSharp.Core):
// sqrt
// exp
// log
// log10
// cos
// sin
// tan
// acos
// asin
// atan
// atan2
// cosh
// sinh
// tanh
// ceil
// floor
/// hypot x y returns sqrt(x * x + y * y), that is, the length of the hypotenuse
/// of a right-angled triangle with sides of length x and y, or, equivalently,
/// the distance of the point (x,y) to origin.
let hypot (x : float) (y : float) =
raise <| System.NotImplementedException "hypot"
//
let expm1 (x : float) =
raise <| System.NotImplementedException "expm1"
//
let log1p (x : float) =
raise <| System.NotImplementedException "log1p"
/// abs_float f returns the absolute value of f.
let inline abs_float (x : float) =
Operators.abs x
/// copysign x y returns a float whose absolute value is that of x and whose sign is that of y.
/// If x is nan, returns nan. If y is nan, returns either x or -. x, but it is not specified which.
let copysign (x : float) (y : float) : float =
raise <| System.NotImplementedException "copysign"
/// mod_float a b returns the remainder of a with respect to b.
/// The returned value is a -. n *. b, where n is the quotient a /. b rounded towards zero to an integer.
let inline mod_float (a : float) (b : float) : float =
a - b * truncate (a / b)
/// frexp f returns the pair of the significant and the exponent of f.
/// When f is zero, the significant x and the exponent n of f are equal to zero.
/// When f is non-zero, they are defined by f = x *. 2 ** n and 0.5 <= x < 1.0.
let frexp (f : float) : float * int =
raise <| System.NotImplementedException "frexp"
/// ldexp x n returns x *. 2 ** n.
let inline ldexp (x : float) (n : int) : float =
x * (2.0 ** float n)
/// modf f returns the pair of the fractional and integral part of f.
let inline modf (f : float) : float * float =
let integral = Operators.floor f
integral, f - integral
/// Convert an integer to floating-point.
let inline float_of_int (value : int) : float =
float value
/// Truncate the given floating-point number to an integer.
/// The result is unspecified if the argument is nan or falls outside the range of representable integers.
let inline int_of_float (value : float) : int =
int32 value
/// Positive infinity.
let [<Literal>] infinity =
System.Double.PositiveInfinity
/// Negative infinity.
let [<Literal>] neg_infinity =
System.Double.NegativeInfinity
//
let [<Literal>] nan =
System.Double.NaN
/// The largest positive finite value of type float.
let [<Literal>] max_float =
System.Double.MaxValue
/// The smallest positive, non-zero, non-denormalized value of type float.
let [<Literal>] min_float =
System.Double.MinValue
/// The difference between 1.0 and the smallest exactly representable floating-point number greater than 1.0.
let [<Literal>] epsilon_float = 0x3CB0000000000000LF // Int64.float_of_bits 4372995238176751616L
/// The five classes of floating-point numbers, as determined by
/// the <see cref="classify_float"/> function.
type fpclass =
/// Normal number.
| FP_normal
/// Number very close to 0.0, has reduced precision.
| FP_subnormal
/// Number is 0.0 or -0.0.
| FP_zero
/// Number is positive or negative infinity.
| FP_infinite
/// Not a number: result of an undefined operation.
| FP_nan
/// Determines if the given floating-point number is a subnormal value.
let private isSubnormal (value : float) =
let rawValue = uint64 <| BitConverter.DoubleToInt64Bits value
let exponent = (rawValue &&& 0x7FF0000000000000UL) >>> 52
let significand = rawValue &&& 0x000FFFFFFFFFFFFFUL
exponent = 0UL
&& significand <> 0UL
/// Return the class of the given floating-point number:
/// normal, subnormal, zero, infinite, or not a number.
let classify_float (value : float) : fpclass =
if value = 0.0 || value = -0.0 then
FP_zero
elif Double.IsNaN value then
FP_nan
elif Double.IsInfinity value then
FP_infinite
elif isSubnormal value then
FP_subnormal
else
FP_normal
(*** String operations ***)
//
let inline (^) (x : string) (y : string) =
System.String.Concat (x, y)
(*** Character operations ***)
/// Return the ASCII code of the argument.
let inline int_of_char (c : char) : int =
int c
/// Return the character with the given ASCII code.
let char_of_int (value : int) : char =
// Preconditions
if value < int Byte.MinValue ||
value > int Byte.MaxValue then
raise <| Invalid_argument "char_of_int"
char value
(*** Unit operations ***)
// NOTE : The 'ignore' function is already provided
// in the F# Core Library (FSharp.Core).
(*** String conversion functions ***)
/// Return the string representation of a boolean.
let inline string_of_bool (value : bool) : string =
if value then "true" else "false"
/// Convert the given string to a boolean.
let bool_of_string (str : string) : bool =
match str with
| "true" -> true
| "false" -> false
| _ ->
raise <| Invalid_argument "bool_of_string"
/// Return the string representation of an integer, in decimal.
let inline string_of_int (value : int) : string =
value.ToString ()
/// Convert the given string to an integer.
/// The string is read in decimal (by default) or in hexadecimal (if it begins with 0x or 0X),
/// octal (if it begins with 0o or 0O), or binary (if it begins with 0b or 0B).
let int_of_string (str : string) : int =
// TODO : This function should also check the parsed value -- if it's
// outside the range of a 31-bit integer, then fail in that case too.
if str.StartsWith ("0x", StringComparison.OrdinalIgnoreCase) then
try Convert.ToInt32 (str.[2..], 16)
with _ -> failwith "int_of_string"
elif str.StartsWith ("0o", StringComparison.OrdinalIgnoreCase) then
try Convert.ToInt32 (str.[2..], 8)
with _ -> failwith "int_of_string"
elif str.StartsWith ("0b", StringComparison.OrdinalIgnoreCase) then
try Convert.ToInt32 (str.[2..], 2)
with _ -> failwith "int_of_string"
else
match Int32.TryParse str with
| true, value ->
value
| false, _ ->
failwith "int_of_string"
/// Return the string representation of a floating-point number.
let string_of_float (value : float) : string =
value.ToString ()
/// Convert the given string to a float.
let float_of_string (str : string) : float =
try float str
with _ ->
failwith "float_of_string"
(*** Pair operations ***)
/// Return the first component of a pair.
let inline fst p = fst p
/// Return the second component of a pair.
let inline snd p = snd p
(*** List operations ***)
// NOTE : The '@' operator is already provided
// in the F# Core Library (FSharp.Core).
(*** Input/output ***)
(* Note: all input/output functions can raise Sys_error when the system calls they invoke fail. *)
/// The type of input channel.
type in_channel = System.IO.TextReader
/// The type of output channel.
type out_channel = TextWriter
/// The standard input for the process.
let stdin : in_channel = stdin
/// The standard output for the process.
let stdout : out_channel = stdout
/// The standard error output for the process.
let stderr : out_channel = stderr
//
type open_flag =
| Open_rdonly | Open_wronly | Open_append
| Open_creat | Open_trunc | Open_excl
| Open_binary | Open_text
#if FX_NO_NONBLOCK_IO
#else
| Open_nonblock
#endif
| Open_encoding of Encoding
//--------------------------------------------------------------------------
// I/O
//
// OCaml-compatible channels conflate binary and text IO. It is very inconvenient to introduce
// out_channel as a new abstract type, as this means functions like fprintf can't be used in
// conjunction with TextWriter values. Hence we pretend that OCaml channels are TextWriters, and
// implement TextWriters in such a way the the implementation contains an optional binary stream
// which is utilized by the OCaml binary I/O methods.
//
// Notes on the implementation: We discriminate between three kinds of
// readers/writers since various operations are possible on each kind.
// StreamReaders/StreamWriters inherit from text readers/writers and
// thus support more functionality. We could just support two
// constructors (Binary and Text) and use dynamic type tests on the underlying .NET
// objects to detect the cases where we have StreamWriters.
//--------------------------------------------------------------------------
type writer =
| StreamW of StreamWriter
| TextW of (unit -> TextWriter)
| BinaryW of BinaryWriter
//
let private defaultEncoding =
#if FX_NO_DEFAULT_ENCODING
// default encoding on Silverlight is UTF8 (to aling with e.g. System.IO.StreamReader)
Encoding.UTF8
#else
Encoding.Default
#endif
//
type OutChannelImpl internal (w : writer) =
inherit TextWriter ()
//
let mutable writer = w
//
override __.Encoding
with get () =
raise <| System.NotImplementedException "OutChannelImpl.get_Encoding"
//
member x.Writer
with get () = writer
and set w = writer <- w
override x.Write(c:char[]) = x.Write(c, 0, c.Length)
override x.Write(s:string) = x.Write(s.ToCharArray())
override x.Write(c:char) = x.Write([| c |])
override x.Write((c:char[]),(index:int),(count:int)) =
match writer with
| StreamW sw ->
(sw :> TextWriter).Write(c,index,count)
| TextW tw ->
(tw ()).Write(c,index,count)
| BinaryW br ->
br.Write(c,index,count)
//
member x.Stream =
match writer with
| TextW _ -> failwith "cannot access a stream for this channel"
| BinaryW bw -> bw.BaseStream
| StreamW sw -> sw.BaseStream
//
member x.TextWriter =
match writer with
| StreamW sw ->
sw :> TextWriter
| TextW tw ->
tw ()
| BinaryW _ ->
failwith "Binary channels created using the OCaml-compatible Pervasives.open_out_bin cannot be used as TextWriters. \
Consider using 'System.IO.BinaryWriter' in preference to creating channels using open_out_bin."
//
member x.StreamWriter =
match writer with
| StreamW sw -> sw
| _ ->
failwith "cannot access a stream writer for this channel"
//
member x.BinaryWriter =
match writer with
| BinaryW w -> w
| _ ->
failwith "cannot access a binary writer for this channel"
interface System.IDisposable with
member x.Dispose() =
match writer with
| TextW tw ->
(tw() :> IDisposable).Dispose()
| BinaryW bw ->
(bw :> IDisposable).Dispose()
| StreamW sw ->
(sw :> IDisposable).Dispose()
//
type reader =
| StreamR of StreamReader
| TextR of (unit -> TextReader)
| BinaryR of BinaryReader
/// See OutChannelImpl
type InChannelImpl internal (r : reader) =
inherit TextReader ()
//
let mutable reader = r
//
member x.Reader
with get () = reader
and set r = reader <- r
//
member x.Stream =
match reader with
| TextR _ -> failwith "cannot access a stream for this channel"
| BinaryR bw -> bw.BaseStream
| StreamR sw -> sw.BaseStream
//
member x.TextReader =
match reader with
| StreamR sw ->
sw :> TextReader
| TextR tw ->
tw ()
| _ ->
failwith "Binary channels created using the OCaml-compatible Pervasives.open_in_bin cannot be used as TextReaders. \
If necessary use the OCaml compatible binary input methods Pervasvies.input etc. to read from this channel. \
Consider using 'System.IO.BinaryReader' in preference to channels created using open_in_bin."
//
member x.StreamReader =
match reader with
| StreamR sw -> sw
| _ -> failwith "cannot access a stream writer for this channel"
//
member x.BinaryReader =
match reader with
| BinaryR w -> w
| _ -> failwith "cannot access a binary writer for this channel"
override x.Peek() =
match reader with
| BinaryR bw -> bw.PeekChar()
| TextR tr -> (tr()).Peek()
| StreamR sr -> sr.Peek()
//
override __.Read () =
match reader with
| StreamR sr ->
sr.Read ()
| BinaryR br ->
br.Read ()
| TextR tr ->
(tr ()).Read ()
//
override __.Read (buffer, index, count) =
match reader with
| StreamR sr ->
sr.Read (buffer, index, count)
| BinaryR br ->
br.Read (buffer, index, count)
| TextR tr ->
(tr ()).Read (buffer, index, count)
interface System.IDisposable with
member x.Dispose() =
match reader with
| TextR tr ->
(tr() :> IDisposable).Dispose()
| BinaryR br ->
(br :> IDisposable).Dispose()
| StreamR sr ->
(sr :> IDisposable).Dispose()
//
let private (!!) (os : out_channel) =
match os with
| :? OutChannelImpl as os ->
os.Writer
| :? StreamWriter as sw ->
StreamW sw
| _ ->
TextW (fun () -> os)
//
let private (<--) (os: out_channel) os' =
match os with
| :? OutChannelImpl as os ->
os.Writer <- os'
| _ ->
failwith "the mode may not be adjusted on a writer not created with one of the Pervasives.open_* functions"
//
let private stream_to_BinaryWriter s =
BinaryW (new BinaryWriter (s))
//
let private stream_to_StreamWriter (encoding : Encoding) (s : Stream) =
// on mono, the StreamWriter constructor will emit a UTF-8 BOM if you pass the encoding to the constructor (even
// if it is the default encoding). For consistency with windows, which does not do this, don't pass the encoding
// unless it differs from the default. (NOTE: if we don't do this, some tests fail because they don't expect a BOM.
// could modify them to watch for the BOM, since it is technically acceptable.)
if encoding = System.Text.Encoding.Default then
StreamW (new StreamWriter (s))
else
StreamW (new StreamWriter (s, encoding))
//
module private OutChannel =
let to_Stream (os : out_channel) =
match !!os with
| BinaryW bw ->
bw.BaseStream
| StreamW sw ->
sw.BaseStream
| TextW _ ->
failwith "to_Stream: cannot access a stream for this channel"
let to_StreamWriter (os : out_channel) =
match !!os with
| StreamW sw -> sw
| _ -> failwith "to_StreamWriter: cannot access a stream writer for this channel"
let to_TextWriter (os : out_channel) =
match !!os with
| StreamW sw ->
sw :> TextWriter
| TextW tw ->
tw ()
| _ -> os
let of_StreamWriter w =
new OutChannelImpl (StreamW w)
:> out_channel
let to_BinaryWriter (os : out_channel) =
match !!os with
| BinaryW bw -> bw
| _ -> failwith "to_BinaryWriter: cannot access a binary writer for this channel"
let of_BinaryWriter w =
new OutChannelImpl (BinaryW w)
:> out_channel
let of_TextWriter (w : TextWriter) =
let absw =
match w with
| :? StreamWriter as sw ->
StreamW sw
| tw ->
TextW (fun () -> tw)
new OutChannelImpl (absw)
:> out_channel
let of_Stream encoding (s : Stream) =
new OutChannelImpl (stream_to_StreamWriter encoding s)
:> out_channel
let private listContains x l =
List.exists ((=) x) l
let open_out_gen flags (_perm : int) (s : string) =
// permissions are ignored
let app = listContains Open_append flags
let access =
match listContains Open_rdonly flags, listContains Open_wronly flags with
| true, true ->
invalidArg "flags" "invalid access for reading"
| true, false ->
invalidArg "flags" "invalid access for writing" // FileAccess.Read
| false, true ->
FileAccess.Write
| false, false ->
if app then FileAccess.Write
else FileAccess.ReadWrite
let mode =
match listContains Open_excl flags, app, listContains Open_creat flags, listContains Open_trunc flags with
| true,false,false,false ->
FileMode.CreateNew
| false,false,true,false ->
FileMode.Create
| false,false,false,false ->
FileMode.OpenOrCreate
| false,false,false,true ->
FileMode.Truncate
| false,false,true,true ->
FileMode.OpenOrCreate
| false,true,false,false ->
FileMode.Append
| _ ->
invalidArg "flags" "invalid mode"
let share = FileShare.Read
let bufferSize = 0x1000
#if FX_NO_NONBLOCK_IO
let stream = new FileStream (s, mode, access, share, bufferSize)
#else
let stream =
let allowAsync = listContains Open_nonblock flags
new FileStream (s, mode, access, share, bufferSize, allowAsync)
#endif
match listContains Open_binary flags, listContains Open_text flags with
| true,true ->
invalidArg "flags" "mixed text/binary flags"
| true,false ->
new OutChannelImpl (stream_to_BinaryWriter stream )
:> out_channel
| false,_ ->
let encoding =
let encoding = List.tryPick (function Open_encoding e -> Some e | _ -> None) flags
defaultArg encoding defaultEncoding
OutChannel.of_Stream encoding (stream :> Stream)
let open_out (s : string) =
open_out_gen [Open_text; Open_wronly; Open_creat] 777 s
// NOTE: equiv to
// new BinaryWriter(new FileStream(s,FileMode.OpenOrCreate,FileAccess.Write,FileShare.Read ,0x1000,false))
let open_out_bin (s : string) =
open_out_gen [Open_binary; Open_wronly; Open_creat] 777 s
let flush (os : out_channel) =
match !!os with
| TextW tw ->
// the default method does not flush, is it overriden for the console?
(tw()).Flush ()
| BinaryW bw ->
bw.Flush ()
| StreamW sw ->
sw.Flush ()
let close_out (os : out_channel) =
match !!os with
| TextW tw ->
(tw ()).Close ()
| BinaryW bw ->
bw.Close ()
| StreamW sw ->
sw.Close ()
let prim_output_newline (os : out_channel) =
match !!os with
| TextW tw ->
(tw()).WriteLine ()
| BinaryW _ ->
invalidArg "os" "the channel is a binary channel"
| StreamW sw ->
sw.WriteLine()
let output_string (os : out_channel) (s : string) =
match !!os with
| TextW tw ->
(tw()).Write s
| BinaryW bw ->
// Write using a char array - writing a string writes it length-prefixed!
Array.init s.Length (fun i -> s.[i])
|> bw.Write
| StreamW sw ->
sw.Write s
let prim_output_int (os : out_channel) (s : int) =
match !!os with
| TextW tw ->
(tw()).Write s
| BinaryW _ ->
invalidArg "os" "the channel is a binary channel"
| StreamW sw ->
sw.Write s
let prim_output_float (os : out_channel) (s : float) =
match !!os with
| TextW tw ->
(tw()).Write s
| BinaryW _ ->
invalidArg "os" "the channel is a binary channel"
| StreamW sw ->
sw.Write s
let output_char (os : out_channel) (c : char) =
match !!os with
| TextW tw ->
(tw()).Write c
| BinaryW bw ->
if int c > 255 then
invalidArg "c" "unicode characters of value > 255 may not be written to binary channels"
bw.Write (byte c)
| StreamW sw ->
sw.Write c
let output_chars (os : out_channel) (c : char[]) start len =
match !!os with
| TextW tw ->
(tw()).Write (c, start, len)
| BinaryW bw ->
bw.Write (c, start, len)
| StreamW sw ->
sw.Write (c, start, len)
let seek_out (os : out_channel) (n : int) =
match !!os with
| StreamW sw ->
sw.Flush ()
(OutChannel.to_Stream os).Seek (int64 n, SeekOrigin.Begin)
|> ignore
| TextW _ ->
(OutChannel.to_Stream os).Seek (int64 n, SeekOrigin.Begin)
|> ignore
| BinaryW bw ->
bw.Flush ()
bw.Seek (n, SeekOrigin.Begin) |> ignore
//
let pos_out (os : out_channel) =
flush os
int32 (OutChannel.to_Stream os).Position
//
let out_channel_length (os : out_channel) =
flush os
int32 (OutChannel.to_Stream os).Length
//
let output (os : out_channel) (buf : byte[]) (x : int) (len : int) =
match !!os with
| BinaryW bw ->
bw.Write (buf, x, len)
| TextW _
| StreamW _ ->
output_string os (defaultEncoding.GetString (buf, x, len))
//
let output_byte (os : out_channel) (x : int) =
match !!os with
| BinaryW bw ->
bw.Write(byte (x % 256))
| TextW _
| StreamW _ ->
output_char os (char (x % 256))
//
let output_binary_int (os : out_channel) (x : int) =
match !!os with
| BinaryW bw ->
bw.Write x
| _ -> failwith "output_binary_int: not a binary stream"
//
let set_binary_mode_out (os : out_channel) b =
match !!os with
| TextW _ when b ->
failwith "cannot set this stream to binary mode"
| TextW _ -> ()
| StreamW _ when not b -> ()
| BinaryW _ when b -> ()
| BinaryW bw ->
os <-- stream_to_StreamWriter defaultEncoding (OutChannel.to_Stream os)
| StreamW bw ->
os <-- stream_to_BinaryWriter (OutChannel.to_Stream os)
#if FX_NO_BINARY_SERIALIZATION
#else
//
let output_value (os : out_channel) (x : 'a) =
let formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter()
formatter.Serialize (OutChannel.to_Stream os, box [x])
flush os
#endif
//
let private (!!!) (c : in_channel) =
match c with
| :? InChannelImpl as c ->
c.Reader
| :? StreamReader as sr ->
StreamR sr
| _ ->
TextR (fun () -> c)
//
let private (<---) (c: in_channel) r =
match c with
| :? InChannelImpl as c ->
c.Reader<- r
| _ -> failwith "the mode may only be adjusted channels created with one of the Pervasives.open_* functions"
//
let private mk_BinaryReader (s: Stream) =
BinaryR (new BinaryReader (s))
//
let private mk_StreamReader e (s: Stream) =
StreamR (new StreamReader (s, e, false))
//
module private InChannel =
let of_Stream (e : Encoding) (s : Stream) =
new InChannelImpl (mk_StreamReader e s)
:> in_channel
let of_StreamReader w =
new InChannelImpl (StreamR w)
:> in_channel
let of_BinaryReader r =
new InChannelImpl (BinaryR r)
:> in_channel
let of_TextReader (r : TextReader) =
let absr =
match r with
| :? StreamReader as sr -> StreamR sr
| tr -> TextR (fun () -> tr)
new InChannelImpl(absr) :> in_channel
let to_StreamReader (c : in_channel) =
match !!!c with
| StreamR sr -> sr
| _ -> failwith "to_StreamReader: cannot access a stream reader for this channel"
let to_BinaryReader (is : in_channel) =
match !!!is with
| BinaryR sr -> sr
| _ -> failwith "to_BinaryReader: cannot access a binary reader for this channel"
let to_TextReader (is : in_channel) =
match !!!is with
| TextR tr -> tr ()
| _ -> is
let to_Stream (is : in_channel) =
match !!!is with
| BinaryR bw -> bw.BaseStream
| StreamR sw -> sw.BaseStream
| _ -> failwith "cannot seek, set position or calculate length of this stream"
// permissions are ignored
let open_in_gen flags (_perm : int) (s : string) =
let access =
match listContains Open_rdonly flags, listContains Open_wronly flags with
| true, true ->
invalidArg "flags" "invalid access"
| true, false ->
FileAccess.Read
| false, true ->
invalidArg "flags" "invalid access for reading"
| false, false ->
FileAccess.ReadWrite
let mode =
match listContains Open_excl flags, listContains Open_append flags, listContains Open_creat flags, listContains Open_trunc flags with
| false, false, false, false ->
FileMode.Open
| _ ->
invalidArg "flags" "invalid mode for reading"
let share = FileShare.Read
let bufferSize = 0x1000
#if FX_NO_NONBLOCK_IO
let stream =
new FileStream(s, mode, access, share, bufferSize)
:> Stream
#else
let stream =
let allowAsync = listContains Open_nonblock flags
new FileStream (s, mode, access, share, bufferSize, allowAsync)
:> Stream
#endif
match listContains Open_binary flags, listContains Open_text flags with
| true, true ->
invalidArg "flags" "mixed text/binary flags specified"
| true, false ->
new InChannelImpl (mk_BinaryReader stream)
:> in_channel
| false, _ ->