Debian Codegraph @

Release/src/streams/fileio_winrt.cpp

raw
1 /***
2 * Copyright (C) Microsoft. All rights reserved.
3 * Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
4 *
5 * =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
6 *
7 * Asynchronous I/O: stream buffer implementation details
8 *
9 * We're going to some lengths to avoid exporting C++ class member functions and implementation details across
10 * module boundaries, and the factoring requires that we keep the implementation details away from the main header
11 * files. The supporting functions, which are in this file, use C-like signatures to avoid as many issues as
12 * possible.
13 *
14 * For the latest on this and related APIs, please see: https://github.com/Microsoft/cpprestsdk
15 *
16 * =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
17 ****/
18 #include "stdafx.h"
19
20 #include "cpprest/details/fileio.h"
21 #include "cpprest/interopstream.h"
22 #include "robuffer.h"
23
24 using namespace ::Windows::Foundation;
25 using namespace ::Windows::Storage;
26 using namespace ::Windows::Storage::Streams;
27 using namespace ::Windows::Networking;
28 using namespace ::Windows::Networking::Sockets;
29
30 namespace Concurrency
31 {
32 namespace streams
33 {
34 namespace details
35 {
36 /// <summary>
37 /// The public parts of the file information record contain only what is implementation-
38 /// independent. The actual allocated record is larger and has details that the implementation
39 /// require in order to function.
40 /// </summary>
41 struct _file_info_impl : _file_info
42 {
43 _file_info_impl(Streams::IRandomAccessStream ^ stream, std::ios_base::openmode mode)
44 : m_stream(stream), m_writer(nullptr), _file_info(mode, 0)
45 {
46 m_pendingWrites = pplx::task_from_result();
47 }
48
49 _file_info_impl(Streams::IRandomAccessStream ^ stream, std::ios_base::openmode mode, size_t buffer_size)
50 : m_stream(stream), m_writer(nullptr), _file_info(mode, buffer_size)
51 {
52 m_pendingWrites = pplx::task_from_result();
53 }
54
55 Streams::IRandomAccessStream ^ m_stream;
56 Streams::IDataWriter ^ m_writer;
57 pplx::task<void> m_pendingWrites;
58 };
59
60 } // namespace details
61 } // namespace streams
62 } // namespace Concurrency
63
64 using namespace Concurrency::streams::details;
65
66 #pragma warning(push)
67 #pragma warning(disable : 4100)
68
69 /// <summary>
70 /// Translate from C++ STL file open modes to Win32 flags.
71 /// </summary>
72 /// <param name="mode">The C++ file open mode</param>
73 /// <param name="prot">The C++ file open protection</param>
74 /// <param name="dwDesiredAccess">A pointer to a DWORD that will hold the desired access flags</param>
75 /// <param name="dwCreationDisposition">A pointer to a DWORD that will hold the creation disposition</param>
76 /// <param name="dwShareMode">A pointer to a DWORD that will hold the share mode</param>
77 void _get_create_flags(std::ios_base::openmode mode,
78 int prot,
79 FileAccessMode& acc_mode,
80 CreationCollisionOption& options)
81 {
82 options = CreationCollisionOption::OpenIfExists;
83 acc_mode = FileAccessMode::ReadWrite;
84
85 if ((mode & std::ios_base::in) && !(mode & std::ios_base::out)) acc_mode = FileAccessMode::Read;
86 if (mode & std::ios_base::trunc) options = CreationCollisionOption::ReplaceExisting;
87 }
88
89 /// <summary>
90 /// Perform post-CreateFile processing.
91 /// </summary>
92 /// <param name="fh">The Win32 file handle</param>
93 /// <param name="callback">The callback interface pointer</param>
94 /// <param name="mode">The C++ file open mode</param>
95 /// <returns>The error code if there was an error in file creation.</returns>
96 void _finish_create(Streams::IRandomAccessStream ^ stream,
97 _In_ _filestream_callback* callback,
98 std::ios_base::openmode mode,
99 int prot)
100 {
101 _file_info_impl* info = nullptr;
102
103 info = new _file_info_impl(stream, mode, 512);
104
105 // Seek to end if it's in appending write mode
106 if ((mode & std::ios_base::out) && (mode & std::ios_base::app || mode & std::ios_base::ate))
107 {
108 _seekwrpos_fsb(info, static_cast<size_t>(stream->Size), 1);
109 }
110
111 callback->on_opened(info);
112 }
113
114 /// <summary>
115 /// Create a streambuf instance to represent a WinRT file.
116 /// </summary>
117 /// <param name="callback">A pointer to the callback interface to invoke when the file has been opened.</param>
118 /// <param name="file">The file object</param>
119 /// <param name="mode">A creation mode for the stream buffer</param>
120 /// <returns>True if the opening operation could be initiated, false otherwise.</returns>
121 /// <remarks>
122 /// True does not signal that the file will eventually be successfully opened, just that the process was started.
123 /// This is only available for WinRT.
124 /// </remarks>
125 bool __cdecl _open_fsb_stf_str(_In_ Concurrency::streams::details::_filestream_callback* callback,
126 ::Windows::Storage::StorageFile ^ file,
127 std::ios_base::openmode mode,
128 int prot)
129 {
130 _ASSERTE(callback != nullptr);
131 _ASSERTE(file != nullptr);
132
133 CreationCollisionOption options;
134 FileAccessMode acc_mode;
135
136 _get_create_flags(mode, prot, acc_mode, options);
137
138 pplx::create_task(file->OpenAsync(acc_mode)).then([=](pplx::task<Streams::IRandomAccessStream ^> sop) {
139 try
140 {
141 _finish_create(sop.get(), callback, mode, prot);
142 }
143 catch (Platform::Exception ^ exc)
144 {
145 callback->on_error(std::make_exception_ptr(utility::details::create_system_error(exc->HResult)));
146 }
147 });
148
149 return true;
150 }
151
152 bool __cdecl _sync_fsb_winrt(_In_ Concurrency::streams::details::_file_info* info,
153 _In_opt_ Concurrency::streams::details::_filestream_callback* callback)
154 {
155 _ASSERTE(info != nullptr);
156
157 _file_info_impl* fInfo = static_cast<_file_info_impl*>(info);
158
159 pplx::extensibility::scoped_recursive_lock_t lck(fInfo->m_lock);
160
161 if (fInfo->m_stream == nullptr || fInfo->m_writer == nullptr || !fInfo->m_stream->CanWrite) return false;
162
163 // take a snapshot of current writer, since writer can be replaced during flush
164 auto writer = fInfo->m_writer;
165 // Flush operation will not begin until all previous writes (StoreAsync) finished, thus it could avoid race.
166 fInfo->m_pendingWrites = fInfo->m_pendingWrites.then([=] { return writer->StoreAsync(); })
167 .then([=](unsigned int) {
168 fInfo->m_buffill = 0;
169 return writer->FlushAsync();
170 })
171 .then([=](pplx::task<bool> result) {
172 // Rethrow exception if no callback attached.
173 if (callback == nullptr)
174 result.wait();
175 else
176 {
177 try
178 {
179 result.wait();
180 callback->on_completed(0);
181 }
182 catch (Platform::Exception ^ exc)
183 {
184 callback->on_error(std::make_exception_ptr(
185 utility::details::create_system_error(exc->HResult)));
186 }
187 }
188 });
189 return true;
190 }
191
192 /// <summary>
193 /// Close a file stream buffer.
194 /// </summary>
195 /// <param name="info">The file info record of the file</param>
196 /// <param name="callback">A pointer to the callback interface to invoke when the file has been opened.</param>
197 /// <returns>True if the closing operation could be initiated, false otherwise.</returns>
198 /// <remarks>
199 /// True does not signal that the file will eventually be successfully closed, just that the process was started.
200 /// </remarks>
201 bool __cdecl _close_fsb_nolock(_In_ _file_info** info,
202 _In_ Concurrency::streams::details::_filestream_callback* callback)
203 {
204 _ASSERTE(callback != nullptr);
205 _ASSERTE(info != nullptr);
206 _ASSERTE(*info != nullptr);
207
208 _file_info_impl* fInfo = static_cast<_file_info_impl*>(*info);
209
210 *info = nullptr;
211
212 auto stream = fInfo->m_stream;
213
214 if (fInfo->m_stream->CanWrite)
215 {
216 _sync_fsb_winrt(fInfo, nullptr);
217 fInfo->m_pendingWrites.then([=](pplx::task<void> t) {
218 try
219 {
220 // The lock fInfo->m_lock must not be held at this point
221 delete fInfo;
222 t.wait();
223 callback->on_closed();
224 }
225 catch (Platform::Exception ^ exc)
226 {
227 callback->on_error(std::make_exception_ptr(utility::details::create_system_error(exc->HResult)));
228 }
229 });
230 }
231 else
232 {
233 // The lock fInfo->m_lock must not be held at this point
234 delete fInfo;
235 callback->on_closed();
236 }
237 return true;
238 }
239
240 bool __cdecl _close_fsb(_In_ _file_info** info, _In_ Concurrency::streams::details::_filestream_callback* callback)
241 {
242 return _close_fsb_nolock(info, callback);
243 }
244
245 /// <summary>
246 /// Initiate an asynchronous (overlapped) read from the file stream.
247 /// </summary>
248 /// <param name="info">The file info record of the file</param>
249 /// <param name="callback">A pointer to the callback interface to invoke when the write request is completed.</param>
250 /// <param name="ptr">A pointer to a buffer where the data should be placed</param>
251 /// <param name="count">The size (in bytes) of the buffer</param>
252 /// <param name="offset">The offset in the file to read from</param>
253 /// <returns>0 if the read request is still outstanding, -1 if the request failed, otherwise the size of the data read
254 /// into the buffer</returns>
255 size_t __cdecl _read_file_async(_In_ Concurrency::streams::details::_file_info_impl* fInfo,
256 _In_ Concurrency::streams::details::_filestream_callback* callback,
257 _Out_writes_(count) void* ptr,
258 _In_ size_t count,
259 size_t offset)
260 {
261 if (fInfo->m_stream == nullptr)
262 {
263 if (callback != nullptr)
264 {
265 // I don't know of a better error code, so this will have to do.
266 callback->on_error(std::make_exception_ptr(utility::details::create_system_error(ERROR_INVALID_ADDRESS)));
267 }
268 return 0;
269 }
270
271 auto reader = ref new Streams::DataReader(fInfo->m_stream->GetInputStreamAt(offset));
272
273 pplx::create_task(reader->LoadAsync(static_cast<unsigned int>(count))).then([=](pplx::task<unsigned int> result) {
274 try
275 {
276 auto read = result.get();
277
278 if (read > 0)
279 {
280 reader->ReadBytes(Platform::ArrayReference<unsigned char>(static_cast<unsigned char*>(ptr), read));
281 }
282
283 callback->on_completed(read);
284 }
285 catch (Platform::Exception ^ exc)
286 {
287 callback->on_error(std::make_exception_ptr(utility::details::create_system_error(exc->HResult)));
288 }
289 });
290
291 return 0;
292 }
293
294 template<typename Func>
295 class _filestream_callback_fill_buffer : public _filestream_callback
296 {
297 public:
298 _filestream_callback_fill_buffer(_In_ _file_info* info, const Func& func) : m_func(func), m_info(info) {}
299
300 virtual void on_completed(size_t result)
301 {
302 m_func(result);
303 delete this;
304 }
305
306 private:
307 _file_info* m_info;
308 Func m_func;
309 };
310
311 template<typename Func>
312 _filestream_callback_fill_buffer<Func>* create_callback(_In_ _file_info* info, const Func& func)
313 {
314 return new _filestream_callback_fill_buffer<Func>(info, func);
315 }
316
317 size_t _fill_buffer_fsb(_In_ _file_info_impl* fInfo,
318 _In_ _filestream_callback* callback,
319 size_t count,
320 size_t char_size)
321 {
322 msl::safeint3::SafeInt<size_t> safeCount = count;
323
324 if (fInfo->m_buffer == nullptr || safeCount > fInfo->m_bufsize)
325 {
326 if (fInfo->m_buffer != nullptr) delete fInfo->m_buffer;
327
328 fInfo->m_bufsize = safeCount.Max(fInfo->m_buffer_size);
329 fInfo->m_buffer = new char[fInfo->m_bufsize * char_size];
330 fInfo->m_bufoff = fInfo->m_rdpos;
331
332 auto cb = create_callback(fInfo, [=](size_t result) {
333 {
334 pplx::extensibility::scoped_recursive_lock_t lck(fInfo->m_lock);
335 fInfo->m_buffill = result / char_size;
336 }
337 callback->on_completed(result);
338 });
339
340 auto read = _read_file_async(
341 fInfo, cb, (uint8_t*)fInfo->m_buffer, fInfo->m_bufsize * char_size, fInfo->m_rdpos * char_size);
342
343 switch (read)
344 {
345 case 0:
346 // pending
347 return read;
348
349 case (-1):
350 // error
351 delete cb;
352 return read;
353
354 default:
355 // operation is complete. The pattern of returning synchronously
356 // has the expectation that we duplicate the callback code here...
357 // Do the expedient thing for now.
358 cb->on_completed(read);
359
360 // return pending
361 return 0;
362 };
363 }
364
365 // First, we need to understand how far into the buffer we have already read
366 // and how much remains.
367
368 size_t bufpos = fInfo->m_rdpos - fInfo->m_bufoff;
369 size_t bufrem = fInfo->m_buffill - bufpos;
370
371 // We have four different scenarios:
372 // 1. The read position is before the start of the buffer, in which case we will just reuse the buffer.
373 // 2. The read position is in the middle of the buffer, and we need to read some more.
374 // 3. The read position is beyond the end of the buffer. Do as in #1.
375 // 4. We have everything we need.
376
377 if ((fInfo->m_rdpos < fInfo->m_bufoff) || (fInfo->m_rdpos >= (fInfo->m_bufoff + fInfo->m_buffill)))
378 {
379 // Reuse the existing buffer.
380
381 fInfo->m_bufoff = fInfo->m_rdpos;
382
383 auto cb = create_callback(fInfo, [=](size_t result) {
384 {
385 pplx::extensibility::scoped_recursive_lock_t lck(fInfo->m_lock);
386 fInfo->m_buffill = result / char_size;
387 }
388 callback->on_completed(bufrem * char_size + result);
389 });
390
391 auto read = _read_file_async(
392 fInfo, cb, (uint8_t*)fInfo->m_buffer, fInfo->m_bufsize * char_size, fInfo->m_rdpos * char_size);
393
394 switch (read)
395 {
396 case 0:
397 // pending
398 return read;
399
400 case (-1):
401 // error
402 delete cb;
403 return read;
404
405 default:
406 // operation is complete. The pattern of returning synchronously
407 // has the expectation that we duplicate the callback code here...
408 // Do the expedient thing for now.
409 cb->on_completed(read);
410
411 // return pending
412 return 0;
413 };
414 }
415 else if (bufrem < count)
416 {
417 fInfo->m_bufsize = safeCount.Max(fInfo->m_buffer_size);
418
419 // Then, we allocate a new buffer.
420
421 char* newbuf = new char[fInfo->m_bufsize * char_size];
422
423 // Then, we copy the unread part to the new buffer and delete the old buffer
424
425 if (bufrem > 0) memcpy(newbuf, fInfo->m_buffer + bufpos * char_size, bufrem * char_size);
426
427 delete fInfo->m_buffer;
428 fInfo->m_buffer = newbuf;
429
430 // Then, we read the remainder of the count into the new buffer
431 fInfo->m_bufoff = fInfo->m_rdpos;
432
433 auto cb = create_callback(fInfo, [=](size_t result) {
434 {
435 pplx::extensibility::scoped_recursive_lock_t lck(fInfo->m_lock);
436 fInfo->m_buffill = result / char_size;
437 }
438 callback->on_completed(bufrem * char_size + result);
439 });
440
441 auto read = _read_file_async(fInfo,
442 cb,
443 (uint8_t*)fInfo->m_buffer + bufrem * char_size,
444 (fInfo->m_bufsize - bufrem) * char_size,
445 (fInfo->m_rdpos + bufrem) * char_size);
446
447 switch (read)
448 {
449 case 0:
450 // pending
451 return read;
452
453 case (-1):
454 // error
455 delete cb;
456 return read;
457
458 default:
459 // operation is complete. The pattern of returning synchronously
460 // has the expectation that we duplicate the callback code here...
461 // Do the expedient thing for now.
462 cb->on_completed(read);
463
464 // return pending
465 return 0;
466 };
467 }
468 else
469 {
470 // If we are here, it means that we didn't need to read, we already have enough data in the buffer
471 return count * char_size;
472 }
473 }
474
475 /// <summary>
476 /// Read data from a file stream into a buffer
477 /// </summary>
478 /// <param name="info">The file info record of the file</param>
479 /// <param name="callback">A pointer to the callback interface to invoke when the write request is completed.</param>
480 /// <param name="ptr">A pointer to a buffer where the data should be placed</param>
481 /// <param name="count">The size (in characters) of the buffer</param>
482 /// <returns>0 if the read request is still outstanding, -1 if the request failed, otherwise the size of the data read
483 /// into the buffer</returns>
484 size_t __cdecl _getn_fsb(_In_ Concurrency::streams::details::_file_info* info,
485 _In_ Concurrency::streams::details::_filestream_callback* callback,
486 _Out_writes_(count) void* ptr,
487 _In_ size_t count,
488 size_t char_size)
489 {
490 _ASSERTE(callback != nullptr);
491 _ASSERTE(info != nullptr);
492 _ASSERTE(count > 0);
493
494 _file_info_impl* fInfo = static_cast<_file_info_impl*>(info);
495
496 pplx::extensibility::scoped_recursive_lock_t lck(info->m_lock);
497
498 if (fInfo->m_buffer_size > 0)
499 {
500 auto cb = create_callback(fInfo, [=](size_t read) {
501 auto sz = count * char_size;
502 auto copy = (read < sz) ? read : sz;
503 auto bufoff = fInfo->m_rdpos - fInfo->m_bufoff;
504 memcpy(ptr, fInfo->m_buffer + bufoff * char_size, copy);
505 fInfo->m_atend = copy < sz;
506 callback->on_completed(copy);
507 });
508
509 size_t read = _fill_buffer_fsb(fInfo, cb, count, char_size);
510
511 if (read > 0)
512 {
513 auto sz = count * char_size;
514 auto copy = (read < sz) ? read : sz;
515 auto bufoff = fInfo->m_rdpos - fInfo->m_bufoff;
516 memcpy(ptr, fInfo->m_buffer + bufoff * char_size, copy);
517 fInfo->m_atend = copy < sz;
518 return copy;
519 }
520
521 return (size_t)read;
522 }
523 else
524 {
525 return _read_file_async(fInfo, callback, ptr, count * char_size, fInfo->m_rdpos * char_size);
526 }
527 }
528
529 /// <summary>
530 /// Write data from a buffer into the file stream.
531 /// </summary>
532 /// <param name="info">The file info record of the file</param>
533 /// <param name="callback">A pointer to the callback interface to invoke when the write request is completed.</param>
534 /// <param name="ptr">A pointer to a buffer where the data should be placed</param>
535 /// <param name="count">The size (in characters) of the buffer</param>
536 /// <returns>0 if the write request is still outstanding, -1 if the request failed, otherwise the size of the data read
537 /// into the buffer</returns>
538 size_t __cdecl _putn_fsb(_In_ Concurrency::streams::details::_file_info* info,
539 _In_ Concurrency::streams::details::_filestream_callback* callback,
540 const void* ptr,
541 size_t count,
542 size_t char_size)
543 {
544 _ASSERTE(callback != nullptr);
545 _ASSERTE(info != nullptr);
546 _ASSERTE(count > 0);
547
548 _file_info_impl* fInfo = static_cast<_file_info_impl*>(info);
549
550 pplx::extensibility::scoped_recursive_lock_t lck(fInfo->m_lock);
551
552 if (fInfo->m_stream == nullptr) return static_cast<size_t>(-1);
553
554 // To preserve the async write order, we have to move the write head before read.
555 if (fInfo->m_wrpos != static_cast<size_t>(-1)) fInfo->m_wrpos += count;
556
557 msl::safeint3::SafeInt<unsigned int> safeWriteSize = count;
558 safeWriteSize *= char_size;
559
560 // In most of the time, we preserve the writer so that it would have better performance.
561 // However, after user call seek, we will dispose old writer. By doing so, users could
562 // write to new writer in new position while the old writer is still flushing data into stream.
563 if (fInfo->m_writer == nullptr)
564 {
565 fInfo->m_writer = ref new Streams::DataWriter(fInfo->m_stream);
566 fInfo->m_buffill = 0;
567 }
568
569 // It keeps tracking the number of bytes written into m_writer buffer.
570 fInfo->m_buffill += count;
571
572 // ArrayReference here is for avoiding data copy.
573 fInfo->m_writer->WriteBytes(Platform::ArrayReference<unsigned char>(
574 const_cast<unsigned char*>(static_cast<const unsigned char*>(ptr)), safeWriteSize));
575
576 // Flush data from m_writer buffer into stream , if the buffer is full
577 if (fInfo->m_buffill >= fInfo->m_buffer_size)
578 {
579 fInfo->m_buffill = 0;
580 fInfo->m_pendingWrites = fInfo->m_pendingWrites.then([=] { return fInfo->m_writer->StoreAsync(); })
581 .then([=](pplx::task<unsigned int> result) {
582 try
583 {
584 result.wait();
585 callback->on_completed(safeWriteSize);
586 }
587 catch (Platform::Exception ^ exc)
588 {
589 callback->on_error(std::make_exception_ptr(
590 utility::details::create_system_error(exc->HResult)));
591 }
592 });
593 return 0;
594 }
595 else
596 return safeWriteSize;
597 }
598
599 /// <summary>
600 /// Flush all buffered data to the underlying file.
601 /// </summary>
602 /// <param name="info">The file info record of the file</param>
603 /// <param name="callback">A pointer to the callback interface to invoke when the write request is completed.</param>
604 /// <returns>True if the request was initiated</returns>
605 bool __cdecl _sync_fsb(_In_ Concurrency::streams::details::_file_info* info,
606 _In_ Concurrency::streams::details::_filestream_callback* callback)
607 {
608 return _sync_fsb_winrt(info, callback);
609 }
610
611 /// <summary>
612 /// Adjust the internal buffers and pointers when the application seeks to a new read location in the stream.
613 /// </summary>
614 /// <param name="info">The file info record of the file</param>
615 /// <param name="pos">The new position (offset from the start) in the file stream</param>
616 /// <returns>New file position or -1 if error</returns>
617 size_t __cdecl _seekrdpos_fsb(_In_ Concurrency::streams::details::_file_info* info, size_t pos, size_t char_size)
618 {
619 _ASSERTE(info != nullptr);
620
621 _file_info_impl* fInfo = static_cast<_file_info_impl*>(info);
622
623 pplx::extensibility::scoped_recursive_lock_t lck(info->m_lock);
624
625 if (fInfo->m_stream == nullptr) return static_cast<size_t>(-1);
626 ;
627
628 if (pos < fInfo->m_bufoff || pos > (fInfo->m_bufoff + fInfo->m_buffill))
629 {
630 delete fInfo->m_buffer;
631 fInfo->m_buffer = nullptr;
632 fInfo->m_bufoff = fInfo->m_buffill = fInfo->m_bufsize = 0;
633 }
634
635 fInfo->m_rdpos = pos;
636
637 return fInfo->m_rdpos;
638 }
639
640 /// <summary>
641 /// Adjust the internal buffers and pointers when the application seeks to a new read location in the stream.
642 /// </summary>
643 /// <param name="info">The file info record of the file</param>
644 /// <param name="offset">The new position (offset from the end of the stream) in the file stream</param>
645 /// <param name="char_size">The size of the character type used for this stream</param>
646 /// <returns>New file position or -1 if error</returns>
647 _ASYNCRTIMP size_t __cdecl _seekrdtoend_fsb(_In_ Concurrency::streams::details::_file_info* info,
648 int64_t offset,
649 size_t char_size)
650 {
651 _ASSERTE(info != nullptr);
652 _file_info_impl* fInfo = static_cast<_file_info_impl*>(info);
653
654 return _seekrdpos_fsb(info, static_cast<size_t>(fInfo->m_stream->Size / char_size + offset), char_size);
655 }
656
657 utility::size64_t __cdecl _get_size(_In_ concurrency::streams::details::_file_info* info, size_t char_size)
658 {
659 _ASSERTE(info != nullptr);
660
661 _file_info_impl* fInfo = static_cast<_file_info_impl*>(info);
662
663 pplx::extensibility::scoped_recursive_lock_t lck(info->m_lock);
664
665 if (fInfo->m_stream == nullptr) return 0;
666
667 return utility::size64_t(fInfo->m_stream->Size / char_size);
668 }
669
670 /// <summary>
671 /// Adjust the internal buffers and pointers when the application seeks to a new write location in the stream.
672 /// </summary>
673 /// <param name="info">The file info record of the file</param>
674 /// <param name="pos">The new position (offset from the start) in the file stream</param>
675 /// <returns>New file position or -1 if error</returns>
676 size_t __cdecl _seekwrpos_fsb(_In_ Concurrency::streams::details::_file_info* info, size_t pos, size_t char_size)
677 {
678 _ASSERTE(info != nullptr);
679
680 _file_info_impl* fInfo = static_cast<_file_info_impl*>(info);
681
682 pplx::extensibility::scoped_recursive_lock_t lck(info->m_lock);
683
684 if (fInfo->m_stream == nullptr) return static_cast<size_t>(-1);
685
686 fInfo->m_wrpos = pos;
687
688 // m_buffill keeps number of chars written into the m_writer buffer.
689 // We need to flush it into stream before seek the write head of the stream
690 if (fInfo->m_buffill > 0) _sync_fsb_winrt(fInfo, nullptr);
691
692 // Moving write head should follow the flush operation. is_done test is for perf optimization.
693 if (fInfo->m_pendingWrites.is_done())
694 fInfo->m_stream->Seek(static_cast<long long>(pos) * char_size);
695 else
696 {
697 auto lastWriter = fInfo->m_writer;
698 fInfo->m_writer = nullptr;
699
700 fInfo->m_pendingWrites = fInfo->m_pendingWrites.then([=] {
701 // Detach stream could avoid stream destruction after writer get destructed.
702 lastWriter->DetachStream();
703 fInfo->m_stream->Seek(static_cast<long long>(pos) * char_size);
704 });
705 }
706
707 return fInfo->m_wrpos;
708 }
709
710 namespace Concurrency
711 {
712 namespace streams
713 {
714 namespace details
715 {
716 /// <summary>
717 /// This class acts as a bridge between WinRT input streams and Casablanca asynchronous streams.
718 /// </summary>
719 ref class IRandomAccessStream_bridge sealed : public Windows::Storage::Streams::IRandomAccessStream
720 {
721 public:
722 virtual property bool CanRead
723 {
724 bool get() { return m_buffer.can_read(); }
725 }
726
727 virtual property bool CanWrite
728 {
729 bool get() { return m_buffer.can_write(); }
730 }
731
732 virtual property uint64_t Position
733 {
734 uint64_t get() { return m_position; }
735 }
736
737 virtual property uint64_t Size
738 {
739 uint64_t get()
740 {
741 if (!m_buffer.has_size()) return m_remembered_size;
742 return m_buffer.size();
743 }
744
745 void set(uint64_t sz)
746 {
747 if (!m_buffer.has_size() || !m_buffer.can_write())
748 m_remembered_size = sz;
749 else
750 m_buffer.seekoff(basic_streambuf<uint8_t>::pos_type(sz), std::ios_base::beg, std::ios_base::out);
751 }
752 }
753
754 virtual Windows::Storage::Streams::IRandomAccessStream ^
755 CloneStream() { return ref new IRandomAccessStream_bridge(m_buffer); }
756
757 virtual Windows::Storage::Streams::IInputStream
758 ^
759 GetInputStreamAt(uint64_t position) {
760 if (!m_buffer.can_read()) return nullptr;
761
762 concurrency::streams::streambuf<uint8_t>::pos_type pos = position;
763
764 if (m_buffer.can_seek() || pos == m_buffer.getpos(std::ios_base::in))
765 {
766 return ref new IRandomAccessStream_bridge(m_buffer, position);
767 }
768 return nullptr;
769 }
770
771 virtual Windows::Storage::Streams::IOutputStream
772 ^ GetOutputStreamAt(uint64_t position) {
773 if (!m_buffer.can_write()) return nullptr;
774
775 concurrency::streams::streambuf<uint8_t>::pos_type pos = position;
776
777 if (m_buffer.can_seek() || pos == m_buffer.getpos(std::ios_base::out))
778 {
779 return ref new IRandomAccessStream_bridge(m_buffer, position);
780 }
781 return nullptr;
782 };
783
784 virtual void Seek(uint64_t position)
785 {
786 if (!m_buffer.can_seek()) throw ref new Platform::InvalidArgumentException(L"underlying buffer cannot seek");
787
788 m_position = position;
789
790 m_buffer.seekpos(concurrency::streams::streambuf<uint8_t>::pos_type(m_position), std::ios_base::in);
791 m_buffer.seekpos(concurrency::streams::streambuf<uint8_t>::pos_type(m_position), std::ios_base::out);
792 }
793
794 virtual Windows::Foundation::IAsyncOperationWithProgress<unsigned int, unsigned int> ^
795 WriteAsync(Windows::Storage::Streams::IBuffer ^ buffer);
796 virtual Windows::Foundation::IAsyncOperationWithProgress<::Windows::Storage::Streams::IBuffer ^, unsigned int> ^
797 ReadAsync(::Windows::Storage::Streams::IBuffer ^ buffer,
798 unsigned int count,
799 Windows::Storage::Streams::InputStreamOptions options);
800 virtual Windows::Foundation::IAsyncOperation<bool> ^ FlushAsync();
801
802 virtual ~IRandomAccessStream_bridge() {}
803
804 internal :
805
806 IRandomAccessStream_bridge(const concurrency::streams::streambuf<uint8_t>& buffer)
807 : m_buffer(buffer), m_remembered_size(0), m_position(0)
808 {
809 }
810
811 IRandomAccessStream_bridge(const concurrency::streams::streambuf<uint8_t>& buffer,
812 concurrency::streams::streambuf<uint8_t>::pos_type position)
813 : m_buffer(buffer), m_remembered_size(0), m_position(position)
814 {
815 }
816
817 private:
818 uint64_t m_remembered_size;
819 concurrency::streams::streambuf<uint8_t>::pos_type m_position;
820 concurrency::streams::streambuf<uint8_t> m_buffer;
821 };
822
823 struct _alloc_protector
824 {
825 _alloc_protector(concurrency::streams::streambuf<uint8_t>& buffer) : m_buffer(buffer), m_size(0) {}
826
827 ~_alloc_protector() { m_buffer.commit(m_size); }
828
829 size_t m_size;
830
831 private:
832 _alloc_protector& operator=(const _alloc_protector&);
833
834 concurrency::streams::streambuf<uint8_t>& m_buffer;
835 };
836
837 struct _acquire_protector
838 {
839 _acquire_protector(concurrency::streams::streambuf<uint8_t>& buffer, uint8_t* ptr)
840 : m_buffer(buffer), m_ptr(ptr), m_size(0)
841 {
842 }
843
844 ~_acquire_protector() { m_buffer.release(m_ptr, m_size); }
845
846 size_t m_size;
847
848 private:
849 _acquire_protector& operator=(const _acquire_protector&);
850
851 uint8_t* m_ptr;
852 concurrency::streams::streambuf<uint8_t>& m_buffer;
853 };
854
855 // Rather than using ComPtr, which is somewhat complex, a simple RAII class
856 // to make sure that Release() is called is useful here.
857 struct _IUnknown_protector
858 {
859 _IUnknown_protector(IUnknown* unk_ptr) : m_unknown(unk_ptr) {}
860 ~_IUnknown_protector()
861 {
862 if (m_unknown != nullptr) m_unknown->Release();
863 }
864
865 private:
866 IUnknown* m_unknown;
867 };
868
869 Windows::Foundation::IAsyncOperationWithProgress<::Windows::Storage::Streams::IBuffer ^, unsigned int> ^
870 IRandomAccessStream_bridge::ReadAsync(::Windows::Storage::Streams::IBuffer ^ buffer,
871 unsigned int count,
872 Windows::Storage::Streams::InputStreamOptions options)
873 {
874 if (!m_buffer.can_read())
875 {
876 return pplx::create_async([buffer](pplx::progress_reporter<uint32> reporter) { return buffer; });
877 }
878
879 if (buffer->Capacity < count)
880 return pplx::create_async([buffer](pplx::progress_reporter<uint32> reporter) { return buffer; });
881
882 m_buffer.seekpos(concurrency::streams::streambuf<uint8_t>::pos_type(m_position), std::ios_base::in);
883
884 concurrency::streams::streambuf<uint8_t> streambuf = m_buffer;
885
886 return pplx::create_async([streambuf, buffer, options, count](pplx::progress_reporter<uint32> reporter) {
887 auto sbuf = streambuf;
888 auto local_buf = ref new ::Platform::Array<unsigned char, 1>(count);
889
890 uint8_t* ptr = nullptr;
891 size_t acquired_size = 0;
892
893 if (sbuf.acquire(ptr, acquired_size) && acquired_size >= count)
894 {
895 _acquire_protector prot(sbuf, ptr);
896
897 IUnknown* pUnk = reinterpret_cast<IUnknown*>(buffer);
898 ::Windows::Storage::Streams::IBufferByteAccess* pBufferByteAccess = nullptr;
899 HRESULT hr = pUnk->QueryInterface(IID_PPV_ARGS(&pBufferByteAccess));
900 __abi_ThrowIfFailed(hr);
901
902 _IUnknown_protector unkprot(pBufferByteAccess);
903
904 byte* buffer_data = nullptr;
905 hr = pBufferByteAccess->Buffer(&buffer_data);
906 __abi_ThrowIfFailed(hr);
907
908 memcpy(buffer_data, ptr, count);
909
910 prot.m_size = count;
911 buffer->Length = count;
912
913 return pplx::task_from_result(buffer);
914 }
915 else
916 {
917 if (acquired_size > 0)
918 {
919 sbuf.release(ptr, 0);
920 }
921
922 IUnknown* pUnk = reinterpret_cast<IUnknown*>(buffer);
923 ::Windows::Storage::Streams::IBufferByteAccess* pBufferByteAccess = nullptr;
924 HRESULT hr = pUnk->QueryInterface(IID_PPV_ARGS(&pBufferByteAccess));
925 __abi_ThrowIfFailed(hr);
926
927 _IUnknown_protector unkprot(pBufferByteAccess);
928
929 byte* buffer_data = nullptr;
930 hr = pBufferByteAccess->Buffer(&buffer_data);
931 __abi_ThrowIfFailed(hr);
932
933 pBufferByteAccess->AddRef();
934
935 return sbuf.getn(buffer_data, count).then([buffer, pBufferByteAccess, count](pplx::task<size_t> written) {
936 _IUnknown_protector unkprot(pBufferByteAccess);
937 buffer->Length = (unsigned int)written.get();
938 return pplx::task_from_result(buffer);
939 });
940 }
941 });
942 }
943
944 Windows::Foundation::IAsyncOperationWithProgress<unsigned int, unsigned int> ^
945 IRandomAccessStream_bridge::WriteAsync(Windows::Storage::Streams::IBuffer ^ buffer)
946 {
947 if (!m_buffer.can_write())
948 {
949 return pplx::create_async([](pplx::progress_reporter<uint32> reporter) { return 0U; });
950 }
951
952 m_buffer.seekpos(concurrency::streams::streambuf<uint8_t>::pos_type(m_position), std::ios_base::out);
953
954 concurrency::streams::streambuf<uint8_t> streambuf = m_buffer;
955
956 return pplx::create_async([buffer, streambuf](pplx::progress_reporter<uint32> reporter) {
957 auto size = buffer->Length;
958 auto sbuf = streambuf;
959 uint8_t* ptr = sbuf.alloc(size);
960
961 if (ptr != nullptr)
962 {
963 {
964 _alloc_protector prot(sbuf);
965
966 IUnknown* pUnk = reinterpret_cast<IUnknown*>(buffer);
967 ::Windows::Storage::Streams::IBufferByteAccess* pBufferByteAccess = nullptr;
968 HRESULT hr = pUnk->QueryInterface(IID_PPV_ARGS(&pBufferByteAccess));
969 __abi_ThrowIfFailed(hr);
970
971 _IUnknown_protector unkprot(pBufferByteAccess);
972
973 byte* buffer_data = nullptr;
974 hr = pBufferByteAccess->Buffer(&buffer_data);
975 __abi_ThrowIfFailed(hr);
976
977 memcpy(ptr, buffer_data, size);
978
979 prot.m_size = size;
980 }
981 return pplx::task_from_result((unsigned int)size);
982 }
983 else
984 {
985 IUnknown* pUnk = reinterpret_cast<IUnknown*>(buffer);
986 ::Windows::Storage::Streams::IBufferByteAccess* pBufferByteAccess = nullptr;
987 HRESULT hr = pUnk->QueryInterface(IID_PPV_ARGS(&pBufferByteAccess));
988 __abi_ThrowIfFailed(hr);
989
990 _IUnknown_protector unkprot(pBufferByteAccess);
991
992 byte* buffer_data = nullptr;
993 hr = pBufferByteAccess->Buffer(&buffer_data);
994 __abi_ThrowIfFailed(hr);
995
996 pBufferByteAccess->AddRef();
997
998 return sbuf.putn_nocopy(buffer_data, size).then([pBufferByteAccess](pplx::task<size_t> size) {
999 pBufferByteAccess->Release();
1000 return (unsigned int)size.get();
1001 });
1002 }
1003 });
1004 }
1005
1006 Windows::Foundation::IAsyncOperation<bool> ^ IRandomAccessStream_bridge::FlushAsync()
1007 {
1008 concurrency::streams::streambuf<uint8_t> streambuf = m_buffer;
1009 return pplx::create_async([streambuf]() {
1010 if (!streambuf.can_write())
1011 {
1012 return pplx::task_from_result(false);
1013 }
1014
1015 auto sbuf = streambuf;
1016 return sbuf.sync().then([] { return pplx::task_from_result(true); });
1017 });
1018 }
1019
1020 } // namespace details
1021 } // namespace streams
1022 } // namespace Concurrency
1023
1024 Windows::Storage::Streams::IInputStream ^
1025 Concurrency::streams::winrt_stream::create_input_stream(const concurrency::streams::streambuf<uint8_t>& buffer)
1026 {
1027 return ref new ::Concurrency::streams::details::IRandomAccessStream_bridge(buffer, 0);
1028 }
1029
1030 Windows::Storage::Streams::IOutputStream ^
1031 Concurrency::streams::winrt_stream::create_output_stream(const concurrency::streams::streambuf<uint8_t>& buffer)
1032 {
1033 return ref new Concurrency::streams::details::IRandomAccessStream_bridge(buffer, 0);
1034 }
1035
1036 Windows::Storage::Streams::IRandomAccessStream ^ Concurrency::streams::winrt_stream::create_random_access_stream(
1037 const concurrency::streams::streambuf<uint8_t>& buffer)
1038 {
1039 return ref new Concurrency::streams::details::IRandomAccessStream_bridge(buffer);
1040 }
1041
1042 #pragma warning(pop)