/src/libreoffice/sal/osl/unx/readwrite_helper.cxx
Line | Count | Source |
1 | | /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ |
2 | | /* |
3 | | * This file is part of the LibreOffice project. |
4 | | * |
5 | | * This Source Code Form is subject to the terms of the Mozilla Public |
6 | | * License, v. 2.0. If a copy of the MPL was not distributed with this |
7 | | * file, You can obtain one at http://mozilla.org/MPL/2.0/. |
8 | | */ |
9 | | |
10 | | #include <sal/config.h> |
11 | | |
12 | | #include <algorithm> |
13 | | #include <cassert> |
14 | | #include <cstddef> |
15 | | #include <errno.h> |
16 | | #include <limits> |
17 | | #include <unistd.h> |
18 | | |
19 | | #include "readwrite_helper.hxx" |
20 | | |
21 | | namespace { |
22 | | |
23 | 0 | std::size_t cap_ssize_t(std::size_t value) { |
24 | 0 | return std::min(value, std::size_t(std::numeric_limits<ssize_t>::max())); |
25 | 0 | } |
26 | | |
27 | | } |
28 | | |
29 | | bool safeWrite(int fd, void* data, std::size_t dataSize) |
30 | 0 | { |
31 | 0 | auto nToWrite = dataSize; |
32 | 0 | unsigned char* dataToWrite = static_cast<unsigned char *>(data); |
33 | |
|
34 | 0 | while ( nToWrite ) { |
35 | 0 | auto nWritten = write(fd, dataToWrite, cap_ssize_t(nToWrite)); |
36 | 0 | if ( nWritten < 0 ) { |
37 | 0 | if ( errno == EINTR ) |
38 | 0 | continue; |
39 | | |
40 | 0 | return false; |
41 | |
|
42 | 0 | } |
43 | | |
44 | 0 | assert(nWritten > 0); |
45 | 0 | nToWrite -= nWritten; |
46 | 0 | dataToWrite += nWritten; |
47 | 0 | } |
48 | | |
49 | 0 | return true; |
50 | 0 | } |
51 | | |
52 | | bool safeRead( int fd, void* buffer, std::size_t count ) |
53 | 0 | { |
54 | 0 | auto nToRead = count; |
55 | 0 | unsigned char* bufferForReading = static_cast<unsigned char *>(buffer); |
56 | |
|
57 | 0 | while ( nToRead ) { |
58 | 0 | auto nRead = read(fd, bufferForReading, cap_ssize_t(nToRead)); |
59 | 0 | if ( nRead < 0 ) { |
60 | | // We were interrupted before reading, retry. |
61 | 0 | if (errno == EINTR) |
62 | 0 | continue; |
63 | | |
64 | 0 | return false; |
65 | 0 | } |
66 | | |
67 | | // If we reach the EOF, we consider this a partial transfer and thus |
68 | | // an error. |
69 | 0 | if ( nRead == 0 ) |
70 | 0 | return false; |
71 | | |
72 | 0 | nToRead -= nRead; |
73 | 0 | bufferForReading += nRead; |
74 | 0 | } |
75 | | |
76 | 0 | return true; |
77 | 0 | } |
78 | | |
79 | | /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ |