Battery Status API: add UMA logging for Linux.
[chromium-blink-merge.git] / mojo / common / test / test_utils_posix.cc
blob0072d0a597144602ed7d2213e5d4ad0a725799a4
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "mojo/common/test/test_utils.h"
7 #include <fcntl.h>
8 #include <unistd.h>
10 #include "base/base_paths.h"
11 #include "base/path_service.h"
12 #include "base/posix/eintr_wrapper.h"
14 namespace mojo {
15 namespace test {
17 bool BlockingWrite(const embedder::PlatformHandle& handle,
18 const void* buffer,
19 size_t bytes_to_write,
20 size_t* bytes_written) {
21 int original_flags = fcntl(handle.fd, F_GETFL);
22 if (original_flags == -1 ||
23 fcntl(handle.fd, F_SETFL, original_flags & (~O_NONBLOCK)) != 0) {
24 return false;
27 ssize_t result = HANDLE_EINTR(write(handle.fd, buffer, bytes_to_write));
29 fcntl(handle.fd, F_SETFL, original_flags);
31 if (result < 0)
32 return false;
34 *bytes_written = result;
35 return true;
38 bool BlockingRead(const embedder::PlatformHandle& handle,
39 void* buffer,
40 size_t buffer_size,
41 size_t* bytes_read) {
42 int original_flags = fcntl(handle.fd, F_GETFL);
43 if (original_flags == -1 ||
44 fcntl(handle.fd, F_SETFL, original_flags & (~O_NONBLOCK)) != 0) {
45 return false;
48 ssize_t result = HANDLE_EINTR(read(handle.fd, buffer, buffer_size));
50 fcntl(handle.fd, F_SETFL, original_flags);
52 if (result < 0)
53 return false;
55 *bytes_read = result;
56 return true;
59 bool NonBlockingRead(const embedder::PlatformHandle& handle,
60 void* buffer,
61 size_t buffer_size,
62 size_t* bytes_read) {
63 ssize_t result = HANDLE_EINTR(read(handle.fd, buffer, buffer_size));
65 if (result < 0) {
66 if (errno != EAGAIN && errno != EWOULDBLOCK)
67 return false;
69 *bytes_read = 0;
70 } else {
71 *bytes_read = result;
74 return true;
77 embedder::ScopedPlatformHandle PlatformHandleFromFILE(base::ScopedFILE fp) {
78 CHECK(fp);
79 int rv = dup(fileno(fp.get()));
80 PCHECK(rv != -1) << "dup";
81 return embedder::ScopedPlatformHandle(embedder::PlatformHandle(rv));
84 base::ScopedFILE FILEFromPlatformHandle(embedder::ScopedPlatformHandle h,
85 const char* mode) {
86 CHECK(h.is_valid());
87 base::ScopedFILE rv(fdopen(h.release().fd, mode));
88 PCHECK(rv) << "fdopen";
89 return rv.Pass();
92 base::FilePath GetFilePathForJSResource(const std::string& path) {
93 std::string binding_path = "gen/" + path + ".js";
94 base::FilePath exe_dir;
95 PathService::Get(base::DIR_EXE, &exe_dir);
96 return exe_dir.AppendASCII(binding_path);
99 } // namespace test
100 } // namespace mojo