streams.h 61.3 KB
Newer Older
藤森雅人's avatar
藤森雅人 committed
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 (C) Microsoft. All rights reserved.
 * Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
 *
 * =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
 *
 * Asynchronous I/O: streams API, used for formatted input and output, based on unformatted I/O using stream buffers
 *
 * For the latest on this and related APIs, please see: https://github.com/Microsoft/cpprestsdk
 *
 * =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
 ****/
#pragma once

#ifndef CASA_STREAMS_H
#define CASA_STREAMS_H

#include "cpprest/astreambuf.h"
#include <iosfwd>

namespace Concurrency
{
namespace streams
{
template<typename CharType>
class basic_ostream;
template<typename CharType>
class basic_istream;

namespace details
{
template<typename CharType>
class basic_ostream_helper
{
public:
    basic_ostream_helper(streams::streambuf<CharType> buffer) : m_buffer(buffer) {}

    ~basic_ostream_helper() {}

private:
    template<typename CharType1>
    friend class streams::basic_ostream;

    concurrency::streams::streambuf<CharType> m_buffer;
};

template<typename CharType>
class basic_istream_helper
{
public:
    basic_istream_helper(streams::streambuf<CharType> buffer) : m_buffer(buffer) {}

    ~basic_istream_helper() {}

private:
    template<typename CharType1>
    friend class streams::basic_istream;

    concurrency::streams::streambuf<CharType> m_buffer;
};

template<typename CharType>
struct Value2StringFormatter
{
    template<typename T>
    static std::basic_string<CharType> format(const T& val)
    {
        std::basic_ostringstream<CharType> ss;
        ss << val;
        return ss.str();
    }
};

template<>
struct Value2StringFormatter<uint8_t>
{
    template<typename T>
    static std::basic_string<uint8_t> format(const T& val)
    {
        std::basic_ostringstream<char> ss;
        ss << val;
        return reinterpret_cast<const uint8_t*>(ss.str().c_str());
    }

    static std::basic_string<uint8_t> format(const utf16string& val)
    {
        return format(utility::conversions::utf16_to_utf8(val));
    }
};

static const char* _in_stream_msg = "stream not set up for input of data";
static const char* _in_streambuf_msg = "stream buffer not set up for input of data";
static const char* _out_stream_msg = "stream not set up for output of data";
static const char* _out_streambuf_msg = "stream buffer not set up for output of data";
} // namespace details

/// <summary>
/// Base interface for all asynchronous output streams.
/// </summary>
template<typename CharType>
class basic_ostream
{
public:
    typedef char_traits<CharType> traits;
    typedef typename traits::int_type int_type;
    typedef typename traits::pos_type pos_type;
    typedef typename traits::off_type off_type;

    /// <summary>
    /// Default constructor
    /// </summary>
    basic_ostream() {}

    /// <summary>
    /// Copy constructor
    /// </summary>
    /// <param name="other">The source object</param>
    basic_ostream(const basic_ostream& other) : m_helper(other.m_helper) {}

    /// <summary>
    /// Assignment operator
    /// </summary>
    /// <param name="other">The source object</param>
    /// <returns>A reference to the stream object that contains the result of the assignment.</returns>
    basic_ostream& operator=(const basic_ostream& other)
    {
        m_helper = other.m_helper;
        return *this;
    }

    /// <summary>
    /// Constructor
    /// </summary>
    /// <param name="buffer">A stream buffer.</param>
    basic_ostream(streams::streambuf<CharType> buffer)
        : m_helper(std::make_shared<details::basic_ostream_helper<CharType>>(buffer))
    {
        _verify_and_throw(details::_out_streambuf_msg);
    }

    /// <summary>
    /// Close the stream, preventing further write operations.
    /// </summary>
    pplx::task<void> close() const
    {
        return is_valid() ? helper()->m_buffer.close(std::ios_base::out) : pplx::task_from_result();
    }

    /// <summary>
    /// Close the stream with exception, preventing further write operations.
    /// </summary>
    /// <param name="eptr">Pointer to the exception.</param>
    pplx::task<void> close(std::exception_ptr eptr) const
    {
        return is_valid() ? helper()->m_buffer.close(std::ios_base::out, eptr) : pplx::task_from_result();
    }

    /// <summary>
    /// Put a single character into the stream.
    /// </summary>
    /// <param name="ch">A character</param>
    pplx::task<int_type> write(CharType ch) const
    {
        pplx::task<int_type> result;
        if (!_verify_and_return_task(details::_out_stream_msg, result)) return result;
        return helper()->m_buffer.putc(ch);
    }

    /// <summary>
    /// Write a single value of "blittable" type T into the stream.
    /// </summary>
    /// <param name="value">A value of type T.</param>
    /// <remarks>
    /// This is not a replacement for a proper binary serialization solution, but it may
    /// form the foundation for one. Writing data bit-wise to a stream is a primitive
    /// operation of binary serialization.
    /// Currently, no attention is paid to byte order. All data is written in the platform's
    /// native byte order, which means little-endian on all platforms that have been tested.
    /// This function is only available for streams using a single-byte character size.
    /// </remarks>
    template<typename T>
    CASABLANCA_DEPRECATED(
        "Unsafe API that will be removed in future releases, use one of the other write overloads instead.")
    pplx::task<size_t> write(T value) const
    {
        static_assert(sizeof(CharType) == 1, "binary write is only supported for single-byte streams");
        static_assert(std::is_trivial<T>::value, "unsafe to use with non-trivial types");

        pplx::task<size_t> result;
        if (!_verify_and_return_task(details::_out_stream_msg, result)) return result;

        auto copy = std::make_shared<T>(std::move(value));
        return helper()
            ->m_buffer.putn_nocopy((CharType*)copy.get(), sizeof(T))
            .then([copy](pplx::task<size_t> op) -> size_t { return op.get(); });
    }

    /// <summary>
    /// Write a number of characters from a given stream buffer into the stream.
    /// </summary>
    /// <param name="source">A source stream buffer.</param>
    /// <param name="count">The number of characters to write.</param>
    pplx::task<size_t> write(streams::streambuf<CharType> source, size_t count) const
    {
        pplx::task<size_t> result;
        if (!_verify_and_return_task(details::_out_stream_msg, result)) return result;
        if (!source.can_read())
            return pplx::task_from_exception<size_t>(
                std::make_exception_ptr(std::runtime_error("source buffer not set up for input of data")));

        if (count == 0) return pplx::task_from_result((size_t)0);

        auto buffer = helper()->m_buffer;
        auto data = buffer.alloc(count);

        if (data != nullptr)
        {
            auto post_read = [buffer](pplx::task<size_t> op) -> pplx::task<size_t> {
                auto b = buffer;
                b.commit(op.get());
                return op;
            };
            return source.getn(data, count).then(post_read);
        }
        else
        {
            size_t available = 0;

            const bool acquired = source.acquire(data, available);
            if (available >= count)
            {
                auto post_write = [source, data](pplx::task<size_t> op) -> pplx::task<size_t> {
                    auto s = source;
                    s.release(data, op.get());
                    return op;
                };
                return buffer.putn_nocopy(data, count).then(post_write);
            }
            else
            {
                // Always have to release if acquire returned true.
                if (acquired)
                {
                    source.release(data, 0);
                }

                std::shared_ptr<CharType> buf(new CharType[count], [](CharType* buf) { delete[] buf; });

                auto post_write = [buf](pplx::task<size_t> op) -> pplx::task<size_t> { return op; };
                auto post_read = [buf, post_write, buffer](pplx::task<size_t> op) -> pplx::task<size_t> {
                    auto b = buffer;
                    return b.putn_nocopy(buf.get(), op.get()).then(post_write);
                };

                return source.getn(buf.get(), count).then(post_read);
            }
        }
    }

    /// <summary>
    /// Write the specified string to the output stream.
    /// </summary>
    /// <param name="str">Input string.</param>
    pplx::task<size_t> print(const std::basic_string<CharType>& str) const
    {
        pplx::task<size_t> result;
        if (!_verify_and_return_task(details::_out_stream_msg, result)) return result;

        if (str.empty())
        {
            return pplx::task_from_result<size_t>(0);
        }
        else
        {
            auto sharedStr = std::make_shared<std::basic_string<CharType>>(str);
            return helper()->m_buffer.putn_nocopy(sharedStr->c_str(), sharedStr->size()).then([sharedStr](size_t size) {
                return size;
            });
        }
    }

    /// <summary>
    /// Write a value of type <c>T</c> to the output stream.
    /// </summary>
    /// <typeparam name="T">
    /// The data type of the object to be written to the stream
    /// </typeparam>
    /// <param name="val">Input object.</param>
    template<typename T>
    pplx::task<size_t> print(const T& val) const
    {
        pplx::task<size_t> result;
        if (!_verify_and_return_task(details::_out_stream_msg, result)) return result;
        // TODO in the future this could be improved to have Value2StringFormatter avoid another unnecessary copy
        // by putting the string on the heap before calling the print string overload.
        return print(details::Value2StringFormatter<CharType>::format(val));
    }

    /// <summary>
    /// Write a value of type <c>T</c> to the output stream and append a newline character.
    /// </summary>
    /// <typeparam name="T">
    /// The data type of the object to be written to the stream
    /// </typeparam>
    /// <param name="val">Input object.</param>
    template<typename T>
    pplx::task<size_t> print_line(const T& val) const
    {
        pplx::task<size_t> result;
        if (!_verify_and_return_task(details::_out_stream_msg, result)) return result;
        auto str = details::Value2StringFormatter<CharType>::format(val);
        str.push_back(CharType('\n'));
        return print(str);
    }

    /// <summary>
    /// Flush any buffered output data.
    /// </summary>
    pplx::task<void> flush() const
    {
        pplx::task<void> result;
        if (!_verify_and_return_task(details::_out_stream_msg, result)) return result;
        return helper()->m_buffer.sync();
    }

    /// <summary>
    /// Seeks to the specified write position.
    /// </summary>
    /// <param name="pos">An offset relative to the beginning of the stream.</param>
    /// <returns>The new position in the stream.</returns>
    pos_type seek(pos_type pos) const
    {
        _verify_and_throw(details::_out_stream_msg);
        return helper()->m_buffer.seekpos(pos, std::ios_base::out);
    }

    /// <summary>
    /// Seeks to the specified write position.
    /// </summary>
    /// <param name="off">An offset relative to the beginning, current write position, or the end of the stream.</param>
    /// <param name="way">The starting point (beginning, current, end) for the seek.</param>
    /// <returns>The new position in the stream.</returns>
    pos_type seek(off_type off, std::ios_base::seekdir way) const
    {
        _verify_and_throw(details::_out_stream_msg);
        return helper()->m_buffer.seekoff(off, way, std::ios_base::out);
    }

    /// <summary>
    /// Get the current write position, i.e. the offset from the beginning of the stream.
    /// </summary>
    /// <returns>The current write position.</returns>
    pos_type tell() const
    {
        _verify_and_throw(details::_out_stream_msg);
        return helper()->m_buffer.getpos(std::ios_base::out);
    }

    /// <summary>
    /// <c>can_seek<c/> is used to determine whether the stream supports seeking.
    /// </summary>
    /// <returns><c>true</c> if the stream supports seeking, <c>false</c> otherwise.</returns>
    bool can_seek() const { return is_valid() && m_helper->m_buffer.can_seek(); }

    /// <summary>
    /// Test whether the stream has been initialized with a valid stream buffer.
    /// </summary>
    /// <returns><c>true</c> if the stream has been initialized with a valid stream buffer, <c>false</c>
    /// otherwise.</returns>
    bool is_valid() const { return (m_helper != nullptr) && ((bool)m_helper->m_buffer); }

    /// <summary>
    /// Test whether the stream has been initialized or not.
    /// </summary>
    operator bool() const { return is_valid(); }

    /// <summary>
    /// Test whether the stream is open for writing.
    /// </summary>
    /// <returns><c>true</c> if the stream is open for writing, <c>false</c> otherwise.</returns>
    bool is_open() const { return is_valid() && m_helper->m_buffer.can_write(); }

    /// <summary>
    /// Get the underlying stream buffer.
    /// </summary>
    /// <returns>The underlying stream buffer.</returns>
    concurrency::streams::streambuf<CharType> streambuf() const { return helper()->m_buffer; }

protected:
    void set_helper(std::shared_ptr<details::basic_ostream_helper<CharType>> helper) { m_helper = helper; }

private:
    template<typename T>
    bool _verify_and_return_task(const char* msg, pplx::task<T>& tsk) const
    {
        auto buffer = helper()->m_buffer;
        if (!(buffer.exception() == nullptr))
        {
            tsk = pplx::task_from_exception<T>(buffer.exception());
            return false;
        }
        if (!buffer.can_write())
        {
            tsk = pplx::task_from_exception<T>(std::make_exception_ptr(std::runtime_error(msg)));
            return false;
        }
        return true;
    }

    void _verify_and_throw(const char* msg) const
    {
        auto buffer = helper()->m_buffer;
        if (!(buffer.exception() == nullptr)) std::rethrow_exception(buffer.exception());
        if (!buffer.can_write()) throw std::runtime_error(msg);
    }

    std::shared_ptr<details::basic_ostream_helper<CharType>> helper() const
    {
        if (!m_helper) throw std::logic_error("uninitialized stream object");
        return m_helper;
    }

    std::shared_ptr<details::basic_ostream_helper<CharType>> m_helper;
};

template<typename int_type>
struct _type_parser_integral_traits
{
    typedef std::false_type _is_integral;
    typedef std::false_type _is_unsigned;
};

#ifdef _WIN32
#define _INT_TRAIT(_t, _low, _high)                                                                                    \
    template<>                                                                                                         \
    struct _type_parser_integral_traits<_t>                                                                            \
    {                                                                                                                  \
        typedef std::true_type _is_integral;                                                                           \
        typedef std::false_type _is_unsigned;                                                                          \
        static const int64_t _min = _low;                                                                              \
        static const int64_t _max = _high;                                                                             \
    };
#define _UINT_TRAIT(_t, _low, _high)                                                                                   \
    template<>                                                                                                         \
    struct _type_parser_integral_traits<_t>                                                                            \
    {                                                                                                                  \
        typedef std::true_type _is_integral;                                                                           \
        typedef std::true_type _is_unsigned;                                                                           \
        static const uint64_t _max = _high;                                                                            \
    };

_INT_TRAIT(char, INT8_MIN, INT8_MAX)
_INT_TRAIT(signed char, INT8_MIN, INT8_MAX)
_INT_TRAIT(short, INT16_MIN, INT16_MAX)
#if defined(_NATIVE_WCHAR_T_DEFINED)
_INT_TRAIT(wchar_t, WCHAR_MIN, WCHAR_MAX)
#endif
_INT_TRAIT(int, INT32_MIN, INT32_MAX)
_INT_TRAIT(long, LONG_MIN, LONG_MAX)
_INT_TRAIT(long long, LLONG_MIN, LLONG_MAX)
_UINT_TRAIT(unsigned char, UINT8_MIN, UINT8_MAX)
_UINT_TRAIT(unsigned short, UINT16_MIN, UINT16_MAX)
_UINT_TRAIT(unsigned int, UINT32_MIN, UINT32_MAX)
_UINT_TRAIT(unsigned long, ULONG_MIN, ULONG_MAX)
_UINT_TRAIT(unsigned long long, ULLONG_MIN, ULLONG_MAX)
#else
#define _INT_TRAIT(_t)                                                                                                 \
    template<>                                                                                                         \
    struct _type_parser_integral_traits<_t>                                                                            \
    {                                                                                                                  \
        typedef std::true_type _is_integral;                                                                           \
        typedef std::false_type _is_unsigned;                                                                          \
        static const int64_t _min = std::numeric_limits<_t>::min();                                                    \
        static const int64_t _max = (std::numeric_limits<_t>::max)();                                                  \
    };
#define _UINT_TRAIT(_t)                                                                                                \
    template<>                                                                                                         \
    struct _type_parser_integral_traits<_t>                                                                            \
    {                                                                                                                  \
        typedef std::true_type _is_integral;                                                                           \
        typedef std::true_type _is_unsigned;                                                                           \
        static const uint64_t _max = (std::numeric_limits<_t>::max)();                                                 \
    };

_INT_TRAIT(char)
_INT_TRAIT(signed char)
_INT_TRAIT(short)
_INT_TRAIT(utf16char)
_INT_TRAIT(int)
_INT_TRAIT(long)
_INT_TRAIT(long long)
_UINT_TRAIT(unsigned char)
_UINT_TRAIT(unsigned short)
_UINT_TRAIT(unsigned int)
_UINT_TRAIT(unsigned long)
_UINT_TRAIT(unsigned long long)
#endif

template<typename CharType>
class _type_parser_base
{
public:
    typedef char_traits<CharType> traits;
    typedef typename traits::int_type int_type;

    _type_parser_base() {}

protected:
    // Aid in parsing input: skipping whitespace characters.
    static pplx::task<void> _skip_whitespace(streams::streambuf<CharType> buffer);

    // Aid in parsing input: peek at a character at a time, call type-specific code to examine, extract value when done.
    // <remark>AcceptFunctor should model std::function<bool(std::shared_ptr<X>, int_type)></remark>
    // <remark>ExtractFunctor should model std::function<pplx::task<ReturnType>(std::shared_ptr<X>)></remark>
    template<typename StateType, typename ReturnType, typename AcceptFunctor, typename ExtractFunctor>
    static pplx::task<ReturnType> _parse_input(streams::streambuf<CharType> buffer,
                                               AcceptFunctor accept_character,
                                               ExtractFunctor extract);
};

/// <summary>
/// Class used to handle asynchronous parsing for basic_istream::extract. To support new
/// types create a new template specialization and implement the parse function.
/// </summary>
template<typename CharType, typename T>
class type_parser
{
public:
    static pplx::task<T> parse(streams::streambuf<CharType> buffer)
    {
        typename _type_parser_integral_traits<T>::_is_integral ii;
        typename _type_parser_integral_traits<T>::_is_unsigned ui;
        return _parse(buffer, ii, ui);
    }

private:
    static pplx::task<T> _parse(streams::streambuf<CharType> buffer, std::false_type, std::false_type)
    {
        _parse_floating_point(buffer);
    }

    static pplx::task<T> _parse(streams::streambuf<CharType>, std::false_type, std::true_type)
    {
#ifdef _WIN32
        static_assert(false, "type is not supported for extraction from a stream");
#else
        throw std::runtime_error("type is not supported for extraction from a stream");
#endif
    }

    static pplx::task<T> _parse(streams::streambuf<CharType> buffer, std::true_type, std::false_type)
    {
        return type_parser<CharType, int64_t>::parse(buffer).then([](pplx::task<int64_t> op) -> T {
            int64_t val = op.get();
            if (val <= _type_parser_integral_traits<T>::_max && val >= _type_parser_integral_traits<T>::_min)
                return (T)val;
            else
                throw std::range_error("input out of range for target type");
        });
    }

    static pplx::task<T> _parse(streams::streambuf<CharType> buffer, std::true_type, std::true_type)
    {
        return type_parser<CharType, uint64_t>::parse(buffer).then([](pplx::task<uint64_t> op) -> T {
            uint64_t val = op.get();
            if (val <= _type_parser_integral_traits<T>::_max)
                return (T)val;
            else
                throw std::range_error("input out of range for target type");
        });
    }
};

/// <summary>
/// Base interface for all asynchronous input streams.
/// </summary>
template<typename CharType>
class basic_istream
{
public:
    typedef char_traits<CharType> traits;
    typedef typename traits::int_type int_type;
    typedef typename traits::pos_type pos_type;
    typedef typename traits::off_type off_type;

    /// <summary>
    /// Default constructor
    /// </summary>
    basic_istream() {}

    /// <summary>
    /// Constructor
    /// </summary>
    /// <typeparam name="CharType">
    /// The data type of the basic element of the stream.
    /// </typeparam>
    /// <param name="buffer">A stream buffer.</param>
    template<class AlterCharType>
    basic_istream(streams::streambuf<AlterCharType> buffer)
        : m_helper(std::make_shared<details::basic_istream_helper<CharType>>(std::move(buffer)))
    {
        _verify_and_throw(details::_in_streambuf_msg);
    }

    /// <summary>
    /// Copy constructor
    /// </summary>
    /// <param name="other">The source object</param>
    basic_istream(const basic_istream& other) : m_helper(other.m_helper) {}

    /// <summary>
    /// Assignment operator
    /// </summary>
    /// <param name="other">The source object</param>
    /// <returns>A reference to the stream object that contains the result of the assignment.</returns>
    basic_istream& operator=(const basic_istream& other)
    {
        m_helper = other.m_helper;
        return *this;
    }

    /// <summary>
    /// Close the stream, preventing further read operations.
    /// </summary>
    pplx::task<void> close() const
    {
        return is_valid() ? helper()->m_buffer.close(std::ios_base::in) : pplx::task_from_result();
    }

    /// <summary>
    /// Close the stream with exception, preventing further read operations.
    /// </summary>
    /// <param name="eptr">Pointer to the exception.</param>
    pplx::task<void> close(std::exception_ptr eptr) const
    {
        return is_valid() ? m_helper->m_buffer.close(std::ios_base::in, eptr) : pplx::task_from_result();
    }

    /// <summary>
    /// Tests whether last read cause the stream reach EOF.
    /// </summary>
    /// <returns>True if the read head has reached the end of the stream, false otherwise.</returns>
    bool is_eof() const { return is_valid() ? m_helper->m_buffer.is_eof() : false; }

    /// <summary>
    /// Get the next character and return it as an int_type. Advance the read position.
    /// </summary>
    /// <returns>A <c>task</c> that holds the next character as an <c>int_type</c> on successful completion.</returns>
    pplx::task<int_type> read() const
    {
        pplx::task<int_type> result;
        if (!_verify_and_return_task(details::_in_stream_msg, result)) return result;
        return helper()->m_buffer.bumpc();
    }

    /// <summary>
    /// Read a single value of "blittable" type T from the stream.
    /// </summary>
    /// <returns>A value of type T.</returns>
    /// <remarks>
    /// This is not a replacement for a proper binary serialization solution, but it may
    /// form the foundation for one. Reading data bit-wise to a stream is a primitive
    /// operation of binary serialization.
    /// Currently, no attention is paid to byte order. All data is read in the platform's
    /// native byte order, which means little-endian on all platforms that have been tested.
    /// This function is only available for streams using a single-byte character size.
    /// </remarks>
    template<typename T>
    CASABLANCA_DEPRECATED(
        "Unsafe API that will be removed in future releases, use one of the other read overloads instead.")
    pplx::task<T> read() const
    {
        static_assert(sizeof(CharType) == 1, "binary read is only supported for single-byte streams");
        static_assert(std::is_trivial<T>::value, "unsafe to use with non-trivial types");

        pplx::task<T> result;
        if (!_verify_and_return_task(details::_in_stream_msg, result)) return result;

        auto copy = std::make_shared<T>();
        return helper()->m_buffer.getn((CharType*)copy.get(), sizeof(T)).then([copy](pplx::task<size_t>) -> T {
            return std::move(*copy);
        });
    }

    /// <summary>
    /// Reads up to <c>count</c> characters and place into the provided buffer.
    /// </summary>
    /// <param name="target">An async stream buffer supporting write operations.</param>
    /// <param name="count">The maximum number of characters to read</param>
    /// <returns>A <c>task</c> that holds the number of characters read. This number is 0 if the end of the stream is
    /// reached.</returns>
    pplx::task<size_t> read(streams::streambuf<CharType> target, size_t count) const
    {
        pplx::task<size_t> result;
        if (!_verify_and_return_task(details::_in_stream_msg, result)) return result;
        if (!target.can_write())
            return pplx::task_from_exception<size_t>(
                std::make_exception_ptr(std::runtime_error("target not set up for output of data")));

        // Capture 'buffer' rather than 'helper' here due to VC++ 2010 limitations.
        auto buffer = helper()->m_buffer;

        auto data = target.alloc(count);

        if (data != nullptr)
        {
            auto post_read = [target](pplx::task<size_t> op) -> pplx::task<size_t> {
                auto t = target;
                t.commit(op.get());
                return op;
            };
            return buffer.getn(data, count).then(post_read);
        }
        else
        {
            size_t available = 0;

            const bool acquired = buffer.acquire(data, available);
            if (available >= count)
            {
                auto post_write = [buffer, data](pplx::task<size_t> op) -> pplx::task<size_t> {
                    auto b = buffer;
                    b.release(data, op.get());
                    return op;
                };
                return target.putn_nocopy(data, count).then(post_write);
            }
            else
            {
                // Always have to release if acquire returned true.
                if (acquired)
                {
                    buffer.release(data, 0);
                }

                std::shared_ptr<CharType> buf(new CharType[count], [](CharType* buf) { delete[] buf; });

                auto post_write = [buf](pplx::task<size_t> op) -> pplx::task<size_t> { return op; };
                auto post_read = [buf, target, post_write](pplx::task<size_t> op) -> pplx::task<size_t> {
                    auto trg = target;
                    return trg.putn_nocopy(buf.get(), op.get()).then(post_write);
                };

                return helper()->m_buffer.getn(buf.get(), count).then(post_read);
            }
        }
    }

    /// <summary>
    /// Get the next character and return it as an int_type. Do not advance the read position.
    /// </summary>
    /// <returns>A <c>task</c> that holds the character, widened to an integer. This character is EOF when the peek
    /// operation fails.</returns>
    pplx::task<int_type> peek() const
    {
        pplx::task<int_type> result;
        if (!_verify_and_return_task(details::_in_stream_msg, result)) return result;
        return helper()->m_buffer.getc();
    }

    /// <summary>
    /// Read characters until a delimiter or EOF is found, and place them into the target.
    /// Proceed past the delimiter, but don't include it in the target buffer.
    /// </summary>
    /// <param name="target">An async stream buffer supporting write operations.</param>
    /// <param name="delim">The delimiting character to stop the read at.</param>
    /// <returns>A <c>task</c> that holds the number of characters read.</returns>
    pplx::task<size_t> read_to_delim(streams::streambuf<CharType> target, int_type delim) const
    {
        pplx::task<size_t> result;
        if (!_verify_and_return_task(details::_in_stream_msg, result)) return result;
        if (!target.can_write())
            return pplx::task_from_exception<size_t>(
                std::make_exception_ptr(std::runtime_error("target not set up for output of data")));

        // Capture 'buffer' rather than 'helper' here due to VC++ 2010 limitations.
        auto buffer = helper()->m_buffer;

        int_type req_async = traits::requires_async();

        std::shared_ptr<_read_helper> _locals = std::make_shared<_read_helper>();

        auto flush = [=]() mutable {
            return target.putn_nocopy(_locals->outbuf, _locals->write_pos).then([=](size_t wrote) mutable {
                _locals->total += wrote;
                _locals->write_pos = 0;
                return target.sync();
            });
        };

        auto update = [=](int_type ch) mutable {
            if (ch == traits::eof()) return false;
            if (ch == delim) return false;

            _locals->outbuf[_locals->write_pos] = static_cast<CharType>(ch);
            _locals->write_pos += 1;

            if (_locals->is_full())
            {
                // Flushing synchronously because performance is terrible if we
                // schedule an empty task. This isn't on a user's thread.
                flush().get();
            }

            return true;
        };

        auto loop = pplx::details::_do_while([=]() mutable -> pplx::task<bool> {
            while (buffer.in_avail() > 0)
            {
                int_type ch = buffer.sbumpc();

                if (ch == req_async)
                {
                    break;
                }

                if (!update(ch))
                {
                    return pplx::task_from_result(false);
                }
            }
            return buffer.bumpc().then(update);
        });

        return loop.then([=](bool) mutable { return flush().then([=] { return _locals->total; }); });
    }

    /// <summary>
    /// Read until reaching a newline character. The newline is not included in the target.
    /// </summary>
    /// <param name="target">An asynchronous stream buffer supporting write operations.</param>
    /// <returns>A <c>task</c> that holds the number of characters read. This number is 0 if the end of the stream is
    /// reached.</returns>
    pplx::task<size_t> read_line(streams::streambuf<CharType> target) const
    {
        pplx::task<size_t> result;
        if (!_verify_and_return_task(details::_in_stream_msg, result)) return result;
        if (!target.can_write())
            return pplx::task_from_exception<size_t>(
                std::make_exception_ptr(std::runtime_error("target not set up for receiving data")));

        // Capture 'buffer' rather than 'helper' here due to VC++ 2010 limitations.
        concurrency::streams::streambuf<CharType> buffer = helper()->m_buffer;

        int_type req_async = traits::requires_async();

        std::shared_ptr<_read_helper> _locals = std::make_shared<_read_helper>();

        auto flush = [=]() mutable {
            return target.putn_nocopy(_locals->outbuf, _locals->write_pos).then([=](size_t wrote) mutable {
                _locals->total += wrote;
                _locals->write_pos = 0;
                return target.sync();
            });
        };

        auto update = [=](int_type ch) mutable {
            if (ch == traits::eof()) return false;
            if (ch == '\n') return false;
            if (ch == '\r')
            {
                _locals->saw_CR = true;
                return true;
            }

            _locals->outbuf[_locals->write_pos] = static_cast<CharType>(ch);
            _locals->write_pos += 1;

            if (_locals->is_full())
            {
                // Flushing synchronously because performance is terrible if we
                // schedule an empty task. This isn't on a user's thread.
                flush().wait();
            }

            return true;
        };

        auto update_after_cr = [=](int_type ch) mutable -> pplx::task<bool> {
            if (ch == traits::eof()) return pplx::task_from_result(false);
            if (ch == '\n')
            {
                return buffer.bumpc().then([](int_type) { return false; });
            }
            return pplx::task_from_result(false);
        };

        auto loop = pplx::details::_do_while([=]() mutable -> pplx::task<bool> {
            while (buffer.in_avail() > 0)
            {
                int_type ch;

                if (_locals->saw_CR)
                {
                    ch = buffer.sgetc();
                    if (ch == '\n') buffer.sbumpc();
                    return pplx::task_from_result(false);
                }

                ch = buffer.sbumpc();

                if (ch == req_async) break;

                if (!update(ch))
                {
                    return pplx::task_from_result(false);
                }
            }

            if (_locals->saw_CR)
            {
                return buffer.getc().then(update_after_cr);
            }
            return buffer.bumpc().then(update);
        });

        return loop.then([=](bool) mutable { return flush().then([=] { return _locals->total; }); });
    }

    /// <summary>
    /// Read until reaching the end of the stream.
    /// </summary>
    /// <param name="target">An asynchronous stream buffer supporting write operations.</param>
    /// <returns>The number of characters read.</returns>
    pplx::task<size_t> read_to_end(streams::streambuf<CharType> target) const
    {
        pplx::task<size_t> result;
        if (!_verify_and_return_task("stream not set up for output of data", result)) return result;
        if (!target.can_write())
            return pplx::task_from_exception<size_t>(
                std::make_exception_ptr(std::runtime_error("source buffer not set up for input of data")));

        auto l_buffer = helper()->m_buffer;
        auto l_buf_size = this->buf_size;
        std::shared_ptr<_read_helper> l_locals = std::make_shared<_read_helper>();

        auto copy_to_target = [l_locals, target, l_buffer, l_buf_size]() mutable -> pplx::task<bool> {
            // We need to capture these, because the object itself may go away
            // before we're done processing the data.
            // auto locs = _locals;
            // auto trg = target;

            return l_buffer.getn(l_locals->outbuf, l_buf_size).then([=](size_t rd) mutable -> pplx::task<bool> {
                if (rd == 0) return pplx::task_from_result(false);

                // Must be nested to capture rd
                return target.putn_nocopy(l_locals->outbuf, rd)
                    .then([target, l_locals, rd](size_t wr) mutable -> pplx::task<bool> {
                        l_locals->total += wr;

                        if (rd != wr)
                            // Number of bytes written is less than number of bytes received.
                            throw std::runtime_error("failed to write all bytes");

                        return target.sync().then([]() { return true; });
                    });
            });
        };

        auto loop = pplx::details::_do_while(copy_to_target);

        return loop.then([=](bool) mutable -> size_t { return l_locals->total; });
    }

    /// <summary>
    /// Seeks to the specified write position.
    /// </summary>
    /// <param name="pos">An offset relative to the beginning of the stream.</param>
    /// <returns>The new position in the stream.</returns>
    pos_type seek(pos_type pos) const
    {
        _verify_and_throw(details::_in_stream_msg);
        return helper()->m_buffer.seekpos(pos, std::ios_base::in);
    }

    /// <summary>
    /// Seeks to the specified write position.
    /// </summary>
    /// <param name="off">An offset relative to the beginning, current write position, or the end of the stream.</param>
    /// <param name="way">The starting point (beginning, current, end) for the seek.</param>
    /// <returns>The new position in the stream.</returns>
    pos_type seek(off_type off, std::ios_base::seekdir way) const
    {
        _verify_and_throw(details::_in_stream_msg);
        return helper()->m_buffer.seekoff(off, way, std::ios_base::in);
    }

    /// <summary>
    /// Get the current write position, i.e. the offset from the beginning of the stream.
    /// </summary>
    /// <returns>The current write position.</returns>
    pos_type tell() const
    {
        _verify_and_throw(details::_in_stream_msg);
        return helper()->m_buffer.getpos(std::ios_base::in);
    }

    /// <summary>
    /// <c>can_seek<c/> is used to determine whether the stream supports seeking.
For faster browsing, not all history is shown. View entire blame