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/proxy/network_list_resource.h"
6
7#include <algorithm>
8
9#include "base/logging.h"
10#include "ppapi/c/pp_errors.h"
11#include "ppapi/shared_impl/array_writer.h"
12#include "ppapi/shared_impl/var.h"
13#include "ppapi/thunk/enter.h"
14
15namespace ppapi {
16namespace proxy {
17
18NetworkListResource::NetworkListResource(PP_Instance instance,
19                                         const SerializedNetworkList& list)
20    : Resource(OBJECT_IS_PROXY, instance),
21      list_(list) {
22}
23
24NetworkListResource::~NetworkListResource() {}
25
26thunk::PPB_NetworkList_API* NetworkListResource::AsPPB_NetworkList_API() {
27  return this;
28}
29
30uint32_t NetworkListResource::GetCount() {
31  return static_cast<uint32_t>(list_.size());
32}
33
34PP_Var NetworkListResource::GetName(uint32_t index) {
35  if (index >= list_.size())
36    return PP_MakeUndefined();
37  return StringVar::StringToPPVar(list_.at(index).name);
38}
39
40PP_NetworkList_Type NetworkListResource::GetType(uint32_t index) {
41  if (index >= list_.size())
42    return PP_NETWORKLIST_TYPE_UNKNOWN;
43  return list_.at(index).type;
44}
45
46PP_NetworkList_State NetworkListResource::GetState(uint32_t index) {
47  if (index >= list_.size())
48    return PP_NETWORKLIST_STATE_DOWN;
49  return list_.at(index).state;
50}
51
52int32_t NetworkListResource::GetIpAddresses(uint32_t index,
53                                            const PP_ArrayOutput& output) {
54  ArrayWriter writer(output);
55  if (index >= list_.size() || !writer.is_valid())
56    return PP_ERROR_BADARGUMENT;
57
58  thunk::EnterResourceCreationNoLock enter(pp_instance());
59  if (enter.failed())
60    return PP_ERROR_FAILED;
61
62  const std::vector<PP_NetAddress_Private>& addresses =
63      list_.at(index).addresses;
64  std::vector<PP_Resource> addr_resources;
65  for (size_t i = 0; i < addresses.size(); ++i) {
66    addr_resources.push_back(
67        enter.functions()->CreateNetAddressFromNetAddressPrivate(
68            pp_instance(), addresses[i]));
69  }
70  if (!writer.StoreResourceVector(addr_resources))
71    return PP_ERROR_FAILED;
72
73  return PP_OK;
74}
75
76PP_Var NetworkListResource::GetDisplayName(uint32_t index) {
77  if (index >= list_.size())
78    return PP_MakeUndefined();
79  return StringVar::StringToPPVar(list_.at(index).display_name);
80}
81
82uint32_t NetworkListResource::GetMTU(uint32_t index) {
83  if (index >= list_.size())
84    return 0;
85  return list_.at(index).mtu;
86}
87
88}  // namespace proxy
89}  // namespace thunk
90