array_writer.cc revision 5821806d5e7f356e8fa4b058a389a808ea183019
1// Copyright (c) 2012 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 "ppapi/shared_impl/array_writer.h"
6
7#include <algorithm>
8
9#include "ppapi/shared_impl/ppapi_globals.h"
10#include "ppapi/shared_impl/resource.h"
11#include "ppapi/shared_impl/resource_tracker.h"
12
13namespace ppapi {
14
15ArrayWriter::ArrayWriter() {
16  Reset();
17}
18
19ArrayWriter::ArrayWriter(const PP_ArrayOutput& output)
20    : pp_array_output_(output) {
21}
22
23ArrayWriter::~ArrayWriter() {
24}
25
26void ArrayWriter::Reset() {
27  pp_array_output_.GetDataBuffer = NULL;
28  pp_array_output_.user_data = NULL;
29}
30
31bool ArrayWriter::StoreResourceVector(
32    const std::vector< scoped_refptr<Resource> >& input) {
33  // Always call the alloc function, even on 0 array size.
34  void* dest = pp_array_output_.GetDataBuffer(
35      pp_array_output_.user_data,
36      static_cast<uint32_t>(input.size()),
37      sizeof(PP_Resource));
38
39  // Regardless of success, we clear the output to prevent future calls on
40  // this same output object.
41  Reset();
42
43  if (input.empty())
44    return true;  // Allow plugin to return NULL on 0 elements.
45  if (!dest)
46    return false;
47
48  // Convert to PP_Resources.
49  PP_Resource* dest_resources = static_cast<PP_Resource*>(dest);
50  for (size_t i = 0; i < input.size(); i++)
51    dest_resources[i] = input[i]->GetReference();
52  return true;
53}
54
55bool ArrayWriter::StoreResourceVector(const std::vector<PP_Resource>& input) {
56  // Always call the alloc function, even on 0 array size.
57  void* dest = pp_array_output_.GetDataBuffer(
58      pp_array_output_.user_data,
59      static_cast<uint32_t>(input.size()),
60      sizeof(PP_Resource));
61
62  // Regardless of success, we clear the output to prevent future calls on
63  // this same output object.
64  Reset();
65
66  if (input.empty())
67    return true;  // Allow plugin to return NULL on 0 elements.
68  if (!dest) {
69    // Free the resources.
70    for (size_t i = 0; i < input.size(); i++)
71      PpapiGlobals::Get()->GetResourceTracker()->ReleaseResource(input[i]);
72    return false;
73  }
74
75  std::copy(input.begin(), input.end(), static_cast<PP_Resource*>(dest));
76  return true;
77}
78
79}  // namespace ppapi
80