| 416 | |
| 417 | |
| 418 | DWORD TextStream::Write(LPCTSTR aBuf, DWORD aBufLen) |
| 419 | // Returns the number of bytes aBuf took after performing applicable EOL and |
| 420 | // code page translations. Since data is buffered, this is generally not the |
| 421 | // amount actually written to file. Returns 0 on apparent critical failure, |
| 422 | // even if *some* data was written into the buffer and/or to file. |
| 423 | { |
| 424 | if (!PrepareToWrite()) |
| 425 | return 0; |
| 426 | |
| 427 | if (aBufLen == 0) |
| 428 | { |
| 429 | aBufLen = (DWORD)_tcslen(aBuf); |
| 430 | if (aBufLen == 0) // Below may rely on this having been checked. |
| 431 | return 0; |
| 432 | } |
| 433 | |
| 434 | DWORD bytes_flushed = 0; // Number of buffered bytes flushed to file; used to calculate our return value. |
| 435 | |
| 436 | LPCTSTR src; |
| 437 | LPCTSTR src_end; |
| 438 | int src_size; |
| 439 | |
| 440 | union { |
| 441 | LPBYTE dst; |
| 442 | LPSTR dstA; |
| 443 | LPWSTR dstW; |
| 444 | }; |
| 445 | dst = mBuffer + mLength; |
| 446 | |
| 447 | // Allow enough space in the buffer for any one of the following: |
| 448 | // a 4-byte UTF-8 sequence |
| 449 | // a UTF-16 surrogate pair |
| 450 | // a carriage-return/newline pair |
| 451 | LPBYTE dst_end = mBuffer + TEXT_IO_BLOCK - 4; |
| 452 | |
| 453 | for (src = aBuf, src_end = aBuf + aBufLen; ; ) |
| 454 | { |
| 455 | // The following section speeds up writing of ASCII characters by copying as many as |
| 456 | // possible in each iteration of the outer loop, avoiding certain checks that would |
| 457 | // otherwise be made once for each char. This relies on the fact that ASCII chars |
| 458 | // have the same binary value (but not necessarily width) in every supported encoding. |
| 459 | // EOL logic is also handled here, for performance. An alternative approach which is |
| 460 | // tidier and performs almost as well is to add (*src != '\n') to each loop's condition |
| 461 | // and handle it after the loop terminates. |
| 462 | if (mCodePage != CP_UTF16) |
| 463 | { |
| 464 | for ( ; src < src_end && !(*src & ~0x7F) && dst < dst_end; ++src) |
| 465 | { |
| 466 | if (*src == '\n' && (mFlags & EOL_CRLF) && ((src == aBuf) ? mLastWriteChar : src[-1]) != '\r') |
| 467 | *dstA++ = '\r'; |
| 468 | *dstA++ = (CHAR)*src; |
| 469 | } |
| 470 | } |
| 471 | else |
| 472 | { |
| 473 | #ifdef UNICODE |
| 474 | for ( ; src < src_end && dst < dst_end; ++src) |
| 475 | #else |
no test coverage detected