File: values.py

package info (click to toggle)
haskell-futhark 0.25.32-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 18,236 kB
  • sloc: haskell: 100,484; ansic: 12,100; python: 3,440; yacc: 785; sh: 561; javascript: 558; lisp: 399; makefile: 277
file content (836 lines) | stat: -rw-r--r-- 21,260 bytes parent folder | download | duplicates (2)
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
# Start of values.py.

# Hacky parser/reader/writer for values written in Futhark syntax.
# Used for reading stdin when compiling standalone programs with the
# Python code generator.

import numpy as np
import string
import struct
import sys


class ReaderInput:
    def __init__(self, f):
        self.f = f
        self.lookahead_buffer = []

    def get_char(self):
        if len(self.lookahead_buffer) == 0:
            return self.f.read(1)
        else:
            c = self.lookahead_buffer[0]
            self.lookahead_buffer = self.lookahead_buffer[1:]
            return c

    def unget_char(self, c):
        self.lookahead_buffer = [c] + self.lookahead_buffer

    def get_chars(self, n):
        n1 = min(n, len(self.lookahead_buffer))
        s = b"".join(self.lookahead_buffer[:n1])
        self.lookahead_buffer = self.lookahead_buffer[n1:]
        n2 = n - n1
        if n2 > 0:
            s += self.f.read(n2)
        return s

    def peek_char(self):
        c = self.get_char()
        if c:
            self.unget_char(c)
        return c


def skip_spaces(f):
    c = f.get_char()
    while c != None:
        if c.isspace():
            c = f.get_char()
        elif c == b"-":
            # May be line comment.
            if f.peek_char() == b"-":
                # Yes, line comment. Skip to end of line.
                while c != b"\n" and c != None:
                    c = f.get_char()
            else:
                break
        else:
            break
    if c:
        f.unget_char(c)


def parse_specific_char(f, expected):
    got = f.get_char()
    if got != expected:
        f.unget_char(got)
        raise ValueError
    return True


def parse_specific_string(f, s):
    # This funky mess is intended, and is caused by the fact that if `type(b) ==
    # bytes` then `type(b[0]) == int`, but we need to match each element with a
    # `bytes`, so therefore we make each character an array element
    b = s.encode("utf8")
    bs = [b[i : i + 1] for i in range(len(b))]
    read = []
    try:
        for c in bs:
            parse_specific_char(f, c)
            read.append(c)
        return True
    except ValueError:
        for c in read[::-1]:
            f.unget_char(c)
        raise


def optional(p, *args):
    try:
        return p(*args)
    except ValueError:
        return None


def optional_specific_string(f, s):
    c = f.peek_char()
    # This funky mess is intended, and is caused by the fact that if `type(b) ==
    # bytes` then `type(b[0]) == int`, but we need to match each element with a
    # `bytes`, so therefore we make each character an array element
    b = s.encode("utf8")
    bs = [b[i : i + 1] for i in range(len(b))]
    if c == bs[0]:
        return parse_specific_string(f, s)
    else:
        return False


def sepEndBy(p, sep, *args):
    elems = []
    x = optional(p, *args)
    if x != None:
        elems += [x]
        while optional(sep, *args) != None:
            x = optional(p, *args)
            if x == None:
                break
            else:
                elems += [x]
    return elems


# Assumes '0x' has already been read
def parse_hex_int(f):
    s = b""
    c = f.get_char()
    while c != None:
        if c in b"01234556789ABCDEFabcdef":
            s += c
            c = f.get_char()
        elif c == b"_":
            c = f.get_char()  # skip _
        else:
            f.unget_char(c)
            break
    return str(int(s, 16)).encode("utf8")  # ugh


def parse_int(f):
    s = b""
    c = f.get_char()
    if c == b"0" and f.peek_char() in b"xX":
        c = f.get_char()  # skip X
        return parse_hex_int(f)
    else:
        while c != None:
            if c.isdigit():
                s += c
                c = f.get_char()
            elif c == b"_":
                c = f.get_char()  # skip _
            else:
                f.unget_char(c)
                break
        if len(s) == 0:
            raise ValueError
        return s


def parse_int_signed(f):
    s = b""
    c = f.get_char()

    if c == b"-" and f.peek_char().isdigit():
        return c + parse_int(f)
    else:
        if c != b"+":
            f.unget_char(c)
        return parse_int(f)


def read_str_comma(f):
    skip_spaces(f)
    parse_specific_char(f, b",")
    return b","


def read_str_int(f, s):
    skip_spaces(f)
    x = int(parse_int_signed(f))
    optional_specific_string(f, s)
    return x


def read_str_uint(f, s):
    skip_spaces(f)
    x = int(parse_int(f))
    optional_specific_string(f, s)
    return x


def read_str_i8(f):
    return np.int8(read_str_int(f, "i8"))


def read_str_i16(f):
    return np.int16(read_str_int(f, "i16"))


def read_str_i32(f):
    return np.int32(read_str_int(f, "i32"))


def read_str_i64(f):
    return np.int64(read_str_int(f, "i64"))


def read_str_u8(f):
    return np.uint8(read_str_int(f, "u8"))


def read_str_u16(f):
    return np.uint16(read_str_int(f, "u16"))


def read_str_u32(f):
    return np.uint32(read_str_int(f, "u32"))


def read_str_u64(f):
    return np.uint64(read_str_int(f, "u64"))


def read_char(f):
    skip_spaces(f)
    parse_specific_char(f, b"'")
    c = f.get_char()
    parse_specific_char(f, b"'")
    return c


def read_str_hex_float(f, sign):
    int_part = parse_hex_int(f)
    parse_specific_char(f, b".")
    frac_part = parse_hex_int(f)
    parse_specific_char(f, b"p")
    exponent = parse_int(f)

    int_val = int(int_part, 16)
    frac_val = float(int(frac_part, 16)) / (16 ** len(frac_part))
    exp_val = int(exponent)

    total_val = (int_val + frac_val) * (2.0**exp_val)
    if sign == b"-":
        total_val = -1 * total_val

    return float(total_val)


def read_str_decimal(f):
    skip_spaces(f)
    c = f.get_char()
    if c == b"-":
        sign = b"-"
    else:
        f.unget_char(c)
        sign = b""

    # Check for hexadecimal float
    c = f.get_char()
    if c == "0" and (f.peek_char() in ["x", "X"]):
        f.get_char()
        return read_str_hex_float(f, sign)
    else:
        f.unget_char(c)

    bef = optional(parse_int, f)
    if bef == None:
        bef = b"0"
        parse_specific_char(f, b".")
        aft = parse_int(f)
    elif optional(parse_specific_char, f, b"."):
        aft = parse_int(f)
    else:
        aft = b"0"
    if optional(parse_specific_char, f, b"E") or optional(
        parse_specific_char, f, b"e"
    ):
        expt = parse_int_signed(f)
    else:
        expt = b"0"
    return float(sign + bef + b"." + aft + b"E" + expt)


def read_str_f16(f):
    skip_spaces(f)
    try:
        parse_specific_string(f, "f16.nan")
        return np.float32(np.nan)
    except ValueError:
        try:
            parse_specific_string(f, "f16.inf")
            return np.float32(np.inf)
        except ValueError:
            try:
                parse_specific_string(f, "-f16.inf")
                return np.float32(-np.inf)
            except ValueError:
                x = read_str_decimal(f)
                optional_specific_string(f, "f16")
                return x


def read_str_f32(f):
    skip_spaces(f)
    try:
        parse_specific_string(f, "f32.nan")
        return np.float32(np.nan)
    except ValueError:
        try:
            parse_specific_string(f, "f32.inf")
            return np.float32(np.inf)
        except ValueError:
            try:
                parse_specific_string(f, "-f32.inf")
                return np.float32(-np.inf)
            except ValueError:
                x = read_str_decimal(f)
                optional_specific_string(f, "f32")
                return x


def read_str_f64(f):
    skip_spaces(f)
    try:
        parse_specific_string(f, "f64.nan")
        return np.float64(np.nan)
    except ValueError:
        try:
            parse_specific_string(f, "f64.inf")
            return np.float64(np.inf)
        except ValueError:
            try:
                parse_specific_string(f, "-f64.inf")
                return np.float64(-np.inf)
            except ValueError:
                x = read_str_decimal(f)
                optional_specific_string(f, "f64")
                return x


def read_str_bool(f):
    skip_spaces(f)
    if f.peek_char() == b"t":
        parse_specific_string(f, "true")
        return True
    elif f.peek_char() == b"f":
        parse_specific_string(f, "false")
        return False
    else:
        raise ValueError


def read_str_empty_array(f, type_name, rank):
    parse_specific_string(f, "empty")
    parse_specific_char(f, b"(")
    dims = []
    for i in range(rank):
        parse_specific_string(f, "[")
        dims += [int(parse_int(f))]
        parse_specific_string(f, "]")
    if np.prod(dims) != 0:
        raise ValueError
    parse_specific_string(f, type_name)
    parse_specific_char(f, b")")

    return tuple(dims)


def read_str_array_elems(f, elem_reader, type_name, rank):
    skip_spaces(f)
    try:
        parse_specific_char(f, b"[")
    except ValueError:
        return read_str_empty_array(f, type_name, rank)
    else:
        xs = sepEndBy(elem_reader, read_str_comma, f)
        skip_spaces(f)
        parse_specific_char(f, b"]")
        return xs


def read_str_array_helper(f, elem_reader, type_name, rank):
    def nested_row_reader(_):
        return read_str_array_helper(f, elem_reader, type_name, rank - 1)

    if rank == 1:
        row_reader = elem_reader
    else:
        row_reader = nested_row_reader
    return read_str_array_elems(f, row_reader, type_name, rank)


def expected_array_dims(l, rank):
    if rank > 1:
        n = len(l)
        if n == 0:
            elem = []
        else:
            elem = l[0]
        return [n] + expected_array_dims(elem, rank - 1)
    else:
        return [len(l)]


def verify_array_dims(l, dims):
    if dims[0] != len(l):
        raise ValueError
    if len(dims) > 1:
        for x in l:
            verify_array_dims(x, dims[1:])


def read_str_array(f, elem_reader, type_name, rank, bt):
    elems = read_str_array_helper(f, elem_reader, type_name, rank)
    if type(elems) == tuple:
        # Empty array
        return np.empty(elems, dtype=bt)
    else:
        dims = expected_array_dims(elems, rank)
        verify_array_dims(elems, dims)
        return np.array(elems, dtype=bt)


################################################################################

READ_BINARY_VERSION = 2

# struct format specified at
# https://docs.python.org/2/library/struct.html#format-characters


def mk_bin_scalar_reader(t):
    def bin_reader(f):
        fmt = FUTHARK_PRIMTYPES[t]["bin_format"]
        size = FUTHARK_PRIMTYPES[t]["size"]
        tf = FUTHARK_PRIMTYPES[t]["numpy_type"]
        return tf(struct.unpack("<" + fmt, f.get_chars(size))[0])

    return bin_reader


read_bin_i8 = mk_bin_scalar_reader("i8")
read_bin_i16 = mk_bin_scalar_reader("i16")
read_bin_i32 = mk_bin_scalar_reader("i32")
read_bin_i64 = mk_bin_scalar_reader("i64")

read_bin_u8 = mk_bin_scalar_reader("u8")
read_bin_u16 = mk_bin_scalar_reader("u16")
read_bin_u32 = mk_bin_scalar_reader("u32")
read_bin_u64 = mk_bin_scalar_reader("u64")

read_bin_f16 = mk_bin_scalar_reader("f16")
read_bin_f32 = mk_bin_scalar_reader("f32")
read_bin_f64 = mk_bin_scalar_reader("f64")

read_bin_bool = mk_bin_scalar_reader("bool")


def read_is_binary(f):
    skip_spaces(f)
    c = f.get_char()
    if c == b"b":
        bin_version = read_bin_u8(f)
        if bin_version != READ_BINARY_VERSION:
            panic(
                1,
                "binary-input: File uses version %i, but I only understand version %i.\n",
                bin_version,
                READ_BINARY_VERSION,
            )
        return True
    else:
        f.unget_char(c)
        return False


FUTHARK_PRIMTYPES = {
    "i8": {
        "binname": b"  i8",
        "size": 1,
        "bin_reader": read_bin_i8,
        "str_reader": read_str_i8,
        "bin_format": "b",
        "numpy_type": np.int8,
    },
    "i16": {
        "binname": b" i16",
        "size": 2,
        "bin_reader": read_bin_i16,
        "str_reader": read_str_i16,
        "bin_format": "h",
        "numpy_type": np.int16,
    },
    "i32": {
        "binname": b" i32",
        "size": 4,
        "bin_reader": read_bin_i32,
        "str_reader": read_str_i32,
        "bin_format": "i",
        "numpy_type": np.int32,
    },
    "i64": {
        "binname": b" i64",
        "size": 8,
        "bin_reader": read_bin_i64,
        "str_reader": read_str_i64,
        "bin_format": "q",
        "numpy_type": np.int64,
    },
    "u8": {
        "binname": b"  u8",
        "size": 1,
        "bin_reader": read_bin_u8,
        "str_reader": read_str_u8,
        "bin_format": "B",
        "numpy_type": np.uint8,
    },
    "u16": {
        "binname": b" u16",
        "size": 2,
        "bin_reader": read_bin_u16,
        "str_reader": read_str_u16,
        "bin_format": "H",
        "numpy_type": np.uint16,
    },
    "u32": {
        "binname": b" u32",
        "size": 4,
        "bin_reader": read_bin_u32,
        "str_reader": read_str_u32,
        "bin_format": "I",
        "numpy_type": np.uint32,
    },
    "u64": {
        "binname": b" u64",
        "size": 8,
        "bin_reader": read_bin_u64,
        "str_reader": read_str_u64,
        "bin_format": "Q",
        "numpy_type": np.uint64,
    },
    "f16": {
        "binname": b" f16",
        "size": 2,
        "bin_reader": read_bin_f16,
        "str_reader": read_str_f16,
        "bin_format": "e",
        "numpy_type": np.float16,
    },
    "f32": {
        "binname": b" f32",
        "size": 4,
        "bin_reader": read_bin_f32,
        "str_reader": read_str_f32,
        "bin_format": "f",
        "numpy_type": np.float32,
    },
    "f64": {
        "binname": b" f64",
        "size": 8,
        "bin_reader": read_bin_f64,
        "str_reader": read_str_f64,
        "bin_format": "d",
        "numpy_type": np.float64,
    },
    "bool": {
        "binname": b"bool",
        "size": 1,
        "bin_reader": read_bin_bool,
        "str_reader": read_str_bool,
        "bin_format": "b",
        "numpy_type": bool,
    },
}


def read_bin_read_type(f):
    read_binname = f.get_chars(4)

    for k, v in FUTHARK_PRIMTYPES.items():
        if v["binname"] == read_binname:
            return k
    panic(1, "binary-input: Did not recognize the type '%s'.\n", read_binname)


def numpy_type_to_type_name(t):
    for k, v in FUTHARK_PRIMTYPES.items():
        if v["numpy_type"] == t:
            return k
    raise Exception("Unknown Numpy type: {}".format(t))


def read_bin_ensure_scalar(f, expected_type):
    dims = read_bin_i8(f)

    if dims != 0:
        panic(
            1,
            "binary-input: Expected scalar (0 dimensions), but got array with %i dimensions.\n",
            dims,
        )

    bin_type = read_bin_read_type(f)
    if bin_type != expected_type:
        panic(
            1,
            "binary-input: Expected scalar of type %s but got scalar of type %s.\n",
            expected_type,
            bin_type,
        )


# ------------------------------------------------------------------------------
# General interface for reading Primitive Futhark Values
# ------------------------------------------------------------------------------


def read_scalar(f, ty):
    if read_is_binary(f):
        read_bin_ensure_scalar(f, ty)
        return FUTHARK_PRIMTYPES[ty]["bin_reader"](f)
    return FUTHARK_PRIMTYPES[ty]["str_reader"](f)


def read_array(f, expected_type, rank):
    if not read_is_binary(f):
        str_reader = FUTHARK_PRIMTYPES[expected_type]["str_reader"]
        return read_str_array(
            f,
            str_reader,
            expected_type,
            rank,
            FUTHARK_PRIMTYPES[expected_type]["numpy_type"],
        )

    bin_rank = read_bin_u8(f)

    if bin_rank != rank:
        panic(
            1,
            "binary-input: Expected %i dimensions, but got array with %i dimensions.\n",
            rank,
            bin_rank,
        )

    bin_type_enum = read_bin_read_type(f)
    if expected_type != bin_type_enum:
        panic(
            1,
            "binary-input: Expected %iD-array with element type '%s' but got %iD-array with element type '%s'.\n",
            rank,
            expected_type,
            bin_rank,
            bin_type_enum,
        )

    shape = []
    elem_count = 1
    for i in range(rank):
        bin_size = read_bin_i64(f)
        elem_count *= bin_size
        shape.append(bin_size)

    bin_fmt = FUTHARK_PRIMTYPES[bin_type_enum]["bin_format"]

    # We first read the expected number of types into a bytestring,
    # then use np.frombuffer.  This is because np.fromfile does not
    # work on things that are insufficiently file-like, like a network
    # stream.
    bytes = f.get_chars(elem_count * FUTHARK_PRIMTYPES[expected_type]["size"])
    arr = np.frombuffer(
        bytes, dtype=FUTHARK_PRIMTYPES[bin_type_enum]["numpy_type"]
    )
    arr.shape = shape

    return arr.copy()  # To ensure it is writeable.


if sys.version_info >= (3, 0):
    input_reader = ReaderInput(sys.stdin.buffer)
else:
    input_reader = ReaderInput(sys.stdin)

import re


def read_value(type_desc, reader=input_reader):
    """Read a value of the given type.  The type is a string
    representation of the Futhark type."""
    m = re.match(r"((?:\[\])*)([a-z0-9]+)$", type_desc)
    if m:
        dims = int(len(m.group(1)) / 2)
        basetype = m.group(2)
    assert m and basetype in FUTHARK_PRIMTYPES, "Unknown type: {}".format(
        type_desc
    )
    if dims > 0:
        return read_array(reader, basetype, dims)
    else:
        return read_scalar(reader, basetype)


def end_of_input(entry, f=input_reader):
    skip_spaces(f)
    if f.get_char() != b"":
        panic(1, 'Expected EOF on stdin after reading input for "%s".', entry)


def write_value_text(v, out=sys.stdout):
    if type(v) == np.uint8:
        out.write("%uu8" % v)
    elif type(v) == np.uint16:
        out.write("%uu16" % v)
    elif type(v) == np.uint32:
        out.write("%uu32" % v)
    elif type(v) == np.uint64:
        out.write("%uu64" % v)
    elif type(v) == np.int8:
        out.write("%di8" % v)
    elif type(v) == np.int16:
        out.write("%di16" % v)
    elif type(v) == np.int32:
        out.write("%di32" % v)
    elif type(v) == np.int64:
        out.write("%di64" % v)
    elif type(v) in [bool, np.bool_]:
        if v:
            out.write("true")
        else:
            out.write("false")
    elif type(v) == np.float16:
        if np.isnan(v):
            out.write("f16.nan")
        elif np.isinf(v):
            if v >= 0:
                out.write("f16.inf")
            else:
                out.write("-f16.inf")
        else:
            out.write("%.6ff16" % v)
    elif type(v) == np.float32:
        if np.isnan(v):
            out.write("f32.nan")
        elif np.isinf(v):
            if v >= 0:
                out.write("f32.inf")
            else:
                out.write("-f32.inf")
        else:
            out.write("%.6ff32" % v)
    elif type(v) == np.float64:
        if np.isnan(v):
            out.write("f64.nan")
        elif np.isinf(v):
            if v >= 0:
                out.write("f64.inf")
            else:
                out.write("-f64.inf")
        else:
            out.write("%.6ff64" % v)
    elif type(v) == np.ndarray:
        if np.prod(v.shape) == 0:
            tname = numpy_type_to_type_name(v.dtype)
            out.write(
                "empty({}{})".format(
                    "".join(["[{}]".format(d) for d in v.shape]), tname
                )
            )
        else:
            first = True
            out.write("[")
            for x in v:
                if not first:
                    out.write(", ")
                first = False
                write_value(x, out=out)
            out.write("]")
    else:
        raise Exception("Cannot print value of type {}: {}".format(type(v), v))


type_strs = {
    np.dtype("int8"): b"  i8",
    np.dtype("int16"): b" i16",
    np.dtype("int32"): b" i32",
    np.dtype("int64"): b" i64",
    np.dtype("uint8"): b"  u8",
    np.dtype("uint16"): b" u16",
    np.dtype("uint32"): b" u32",
    np.dtype("uint64"): b" u64",
    np.dtype("float16"): b" f16",
    np.dtype("float32"): b" f32",
    np.dtype("float64"): b" f64",
    np.dtype("bool"): b"bool",
}


def construct_binary_value(v):
    t = v.dtype
    shape = v.shape

    elems = 1
    for d in shape:
        elems *= d

    num_bytes = 1 + 1 + 1 + 4 + len(shape) * 8 + elems * t.itemsize
    bytes = bytearray(num_bytes)
    bytes[0] = np.int8(ord("b"))
    bytes[1] = 2
    bytes[2] = np.int8(len(shape))
    bytes[3:7] = type_strs[t]

    for i in range(len(shape)):
        bytes[7 + i * 8 : 7 + (i + 1) * 8] = np.int64(shape[i]).tobytes()

    bytes[7 + len(shape) * 8 :] = np.ascontiguousarray(v).tobytes()

    return bytes


def write_value_binary(v, out=sys.stdout):
    if sys.version_info >= (3, 0):
        out = out.buffer
    out.write(construct_binary_value(v))


def write_value(v, out=sys.stdout, binary=False):
    if binary:
        return write_value_binary(v, out=out)
    else:
        return write_value_text(v, out=out)


# End of values.py.