• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2014 The Chromium Embedded Framework Authors. All rights
2 // reserved. Use of this source code is governed by a BSD-style license that
3 // can be found in the LICENSE file.
4 
5 #include "tests/cefclient/browser/bytes_write_handler.h"
6 
7 #include <cstdio>
8 #include <cstdlib>
9 
10 #include "include/wrapper/cef_helpers.h"
11 
12 namespace client {
13 
BytesWriteHandler(size_t grow)14 BytesWriteHandler::BytesWriteHandler(size_t grow)
15     : grow_(grow), datasize_(grow), offset_(0) {
16   DCHECK_GT(grow, 0U);
17   data_ = malloc(grow);
18   DCHECK(data_ != nullptr);
19 }
20 
~BytesWriteHandler()21 BytesWriteHandler::~BytesWriteHandler() {
22   if (data_)
23     free(data_);
24 }
25 
Write(const void * ptr,size_t size,size_t n)26 size_t BytesWriteHandler::Write(const void* ptr, size_t size, size_t n) {
27   base::AutoLock lock_scope(lock_);
28   size_t rv;
29   if (offset_ + static_cast<int64>(size * n) >= datasize_ &&
30       Grow(size * n) == 0) {
31     rv = 0;
32   } else {
33     memcpy(reinterpret_cast<char*>(data_) + offset_, ptr, size * n);
34     offset_ += size * n;
35     rv = n;
36   }
37 
38   return rv;
39 }
40 
Seek(int64 offset,int whence)41 int BytesWriteHandler::Seek(int64 offset, int whence) {
42   int rv = -1L;
43   base::AutoLock lock_scope(lock_);
44   switch (whence) {
45     case SEEK_CUR:
46       if (offset_ + offset > datasize_ || offset_ + offset < 0)
47         break;
48       offset_ += offset;
49       rv = 0;
50       break;
51     case SEEK_END: {
52       int64 offset_abs = std::abs(offset);
53       if (offset_abs > datasize_)
54         break;
55       offset_ = datasize_ - offset_abs;
56       rv = 0;
57       break;
58     }
59     case SEEK_SET:
60       if (offset > datasize_ || offset < 0)
61         break;
62       offset_ = offset;
63       rv = 0;
64       break;
65   }
66 
67   return rv;
68 }
69 
Tell()70 int64 BytesWriteHandler::Tell() {
71   base::AutoLock lock_scope(lock_);
72   return offset_;
73 }
74 
Flush()75 int BytesWriteHandler::Flush() {
76   return 0;
77 }
78 
Grow(size_t size)79 size_t BytesWriteHandler::Grow(size_t size) {
80   lock_.AssertAcquired();
81   size_t rv;
82   size_t s = (size > grow_ ? size : grow_);
83   void* tmp = realloc(data_, datasize_ + s);
84   DCHECK(tmp != nullptr);
85   if (tmp) {
86     data_ = tmp;
87     datasize_ += s;
88     rv = datasize_;
89   } else {
90     rv = 0;
91   }
92 
93   return rv;
94 }
95 
96 }  // namespace client
97