blob: b8104b68c9a71a1e63c2fe09a5b93c5e5f2f61a5 [file] [log] [blame]
Andrew Top0d1858f2019-05-15 22:01:47 -07001// Copyright 2016 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 "net/log/net_log_source.h"
6
7#include <memory>
8#include <utility>
9
10#include "base/bind.h"
11#include "base/callback.h"
12#include "base/logging.h"
13#include "base/values.h"
14#include "net/log/net_log_capture_mode.h"
15
16namespace net {
17
18namespace {
19
20std::unique_ptr<base::Value> SourceEventParametersCallback(
21 const NetLogSource source,
22 NetLogCaptureMode /* capture_mode */) {
23 if (!source.IsValid())
24 return std::unique_ptr<base::Value>();
25 std::unique_ptr<base::DictionaryValue> event_params(
26 new base::DictionaryValue());
27 source.AddToEventParameters(event_params.get());
28 return std::move(event_params);
29}
30
31} // namespace
32
33// LoadTimingInfo requires this be 0.
34const uint32_t NetLogSource::kInvalidId = 0;
35
36NetLogSource::NetLogSource() : type(NetLogSourceType::NONE), id(kInvalidId) {}
37
38NetLogSource::NetLogSource(NetLogSourceType type, uint32_t id)
39 : type(type), id(id) {}
40
41bool NetLogSource::IsValid() const {
42 return id != kInvalidId;
43}
44
45void NetLogSource::AddToEventParameters(
46 base::DictionaryValue* event_params) const {
47 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
48 dict->SetInteger("type", static_cast<int>(type));
49 dict->SetInteger("id", static_cast<int>(id));
50 event_params->Set("source_dependency", std::move(dict));
51}
52
53NetLogParametersCallback NetLogSource::ToEventParametersCallback() const {
54 return base::Bind(&SourceEventParametersCallback, *this);
55}
56
57// static
58bool NetLogSource::FromEventParameters(base::Value* event_params,
59 NetLogSource* source) {
60 base::DictionaryValue* dict = NULL;
61 base::DictionaryValue* source_dict = NULL;
62 int source_id = -1;
63 int source_type = static_cast<int>(NetLogSourceType::COUNT);
64 if (!event_params || !event_params->GetAsDictionary(&dict) ||
65 !dict->GetDictionary("source_dependency", &source_dict) ||
66 !source_dict->GetInteger("id", &source_id) ||
67 !source_dict->GetInteger("type", &source_type)) {
68 *source = NetLogSource();
69 return false;
70 }
71
72 DCHECK_GE(source_id, 0);
73 DCHECK_LT(source_type, static_cast<int>(NetLogSourceType::COUNT));
74 *source = NetLogSource(static_cast<NetLogSourceType>(source_type), source_id);
75 return true;
76}
77
78} // namespace net