Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / mojo / common / test / test_utils_posix.cc
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.
4
5 #include "mojo/common/test/test_utils.h"
6
7 #include <fcntl.h>
8 #include <unistd.h>
9
10 #include "base/base_paths.h"
11 #include "base/path_service.h"
12 #include "base/posix/eintr_wrapper.h"
13 #include "mojo/embedder/platform_handle.h"
14
15 namespace mojo {
16 namespace test {
17
18 bool BlockingWrite(const embedder::PlatformHandle& handle,
19                    const void* buffer,
20                    size_t bytes_to_write,
21                    size_t* bytes_written) {
22   int original_flags = fcntl(handle.fd, F_GETFL);
23   if (original_flags == -1 ||
24       fcntl(handle.fd, F_SETFL, original_flags & (~O_NONBLOCK)) != 0) {
25     return false;
26   }
27
28   ssize_t result = HANDLE_EINTR(write(handle.fd, buffer, bytes_to_write));
29
30   fcntl(handle.fd, F_SETFL, original_flags);
31
32   if (result < 0)
33     return false;
34
35   *bytes_written = result;
36   return true;
37 }
38
39 bool BlockingRead(const embedder::PlatformHandle& handle,
40                   void* buffer,
41                   size_t buffer_size,
42                   size_t* bytes_read) {
43   int original_flags = fcntl(handle.fd, F_GETFL);
44   if (original_flags == -1 ||
45       fcntl(handle.fd, F_SETFL, original_flags & (~O_NONBLOCK)) != 0) {
46     return false;
47   }
48
49   ssize_t result = HANDLE_EINTR(read(handle.fd, buffer, buffer_size));
50
51   fcntl(handle.fd, F_SETFL, original_flags);
52
53   if (result < 0)
54     return false;
55
56   *bytes_read = result;
57   return true;
58 }
59
60 bool NonBlockingRead(const embedder::PlatformHandle& handle,
61                      void* buffer,
62                      size_t buffer_size,
63                      size_t* bytes_read) {
64   ssize_t result = HANDLE_EINTR(read(handle.fd, buffer, buffer_size));
65
66   if (result < 0) {
67     if (errno != EAGAIN && errno != EWOULDBLOCK)
68       return false;
69
70     *bytes_read = 0;
71   } else {
72     *bytes_read = result;
73   }
74
75   return true;
76 }
77
78 base::FilePath GetFilePathForJSResource(const std::string& path) {
79   std::string binding_path = "gen/" + path + ".js";
80   base::FilePath exe_dir;
81   PathService::Get(base::DIR_EXE, &exe_dir);
82   return exe_dir.AppendASCII(binding_path);
83 }
84
85 }  // namespace test
86 }  // namespace mojo