diff options
author | Luis Hector Chavez <lhchavez@google.com> | 2016-05-31 23:41:41 +0000 |
---|---|---|
committer | android-build-merger <android-build-merger@google.com> | 2016-05-31 23:41:41 +0000 |
commit | d77dfa0b5a854a80a586b89f13f602ee5a523d06 (patch) | |
tree | dd9041de1b74c6133fb3a07fcaa321de989b9668 | |
parent | f91e999fb2dc8a70365471277e846e7b8e7b3284 (diff) | |
parent | abfe7a063bbaebdca8703d27137c8c9aed826dac (diff) | |
download | libweave-d77dfa0b5a854a80a586b89f13f602ee5a523d06.tar.gz |
Revert "Merge remote-tracking branch \'weave/master\' into \'weave/aosp-master\'"
am: abfe7a063b
* commit 'abfe7a063bbaebdca8703d27137c8c9aed826dac':
Revert "Merge remote-tracking branch 'weave/master' into 'weave/aosp-master'"
Change-Id: Id85d181a0a73598c6c4a3f397bd8085dd2c398e5
38 files changed, 1090 insertions, 553 deletions
diff --git a/examples/daemon/oven/oven.cc b/examples/daemon/oven/oven.cc new file mode 100644 index 0000000..f92c838 --- /dev/null +++ b/examples/daemon/oven/oven.cc @@ -0,0 +1,290 @@ +// Copyright 2015 The Weave Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "examples/daemon/common/daemon.h" + +#include <weave/device.h> +#include <weave/provider/task_runner.h> + +#include <base/bind.h> +#include <base/memory/weak_ptr.h> + +namespace { +// Time for sensor temperature to match setting temperature +const double kWarmUpTime = 60.0; +// Oven max temp +const double kMaxTemp = 300.0; +// Oven min temp +const double kMinTemp = 20.0; + +const char kTraits[] = R"({ + "temperatureSetting": { + "commands": { + "setConfig": { + "minimalRole": "user", + "parameters": { + "units": { + "type": "string" + }, + "tempSetting": { + "type": "number" + } + }, + "errors": ["tempOutOfRange", "unsupportedUnits"] + } + }, + "state": { + "supportedUnits": { + "type": "array", + "items": { + "type": "string", + "enum": [ "celsius", "fahrenheit", "kelvin" ] + }, + "minItems": 1, + "uniqueItems": true, + "isRequired": true + }, + "units": { + "type": "string", + "enum": [ "celsius", "fahrenheit", "kelvin" ], + "isRequired": true + }, + "tempSetting": { + "type": "number", + "isRequired": true + }, + "maxTempSetting": { + "type": "number", + "isRequired": true + }, + "minTempSetting": { + "type": "number", + "isRequired": true + } + } + }, + "temperatureSensor": { + "commands": { + "setConfig": { + "minimalRole": "user", + "parameters": { + "units": { + "type": "string" + } + }, + "errors": ["unsupportedUnits"] + } + }, + "state": { + "supportedUnits": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "celsius", + "fahrenheit", + "kelvin" + ] + }, + "minItems": 1, + "uniqueItems": true, + "isRequired": true + }, + "units": { + "type": "string", + "enum": [ "celsius", "fahrenheit", "kelvin" ], + "isRequired": true + }, + "value": { + "type": "number", + "isRequired": true + } + } + }, + "brightness": { + "commands": { + "setConfig": { + "minimalRole": "user", + "parameters": { + "brightness": { + "type": "integer", + "minimum": 0, + "maximum": 100 + } + } + } + }, + "state": { + "brightness": { + "type": "integer", + "isRequired": true, + "minimum": 0, + "maximum": 100 + } + } + } +})"; + +const char kComponent[] = "oven"; +} // anonymous namespace + +// OvenHandler is a virtual oven example +// It implements the following commands from traits: +// - temperatureSetting: sets the temperature for the oven +// - brightness: sets the brightness of the oven light +// It exposes the following states from traits: +// - temperatureSetting: temperature setting for the oven +// - temperatureSensor: current oven temperature +// - brightness: current oven brightness +class OvenHandler { + public: + OvenHandler(weave::provider::TaskRunner* task_runner) + : task_runner_{task_runner} {} + + void Register(weave::Device* device) { + device_ = device; + + device->AddTraitDefinitionsFromJson(kTraits); + CHECK(device->AddComponent( + kComponent, {"temperatureSetting", "temperatureSensor", "brightness"}, + nullptr)); + + UpdateOvenState(); + + device->AddCommandHandler(kComponent, "temperatureSetting.setConfig", + base::Bind(&OvenHandler::OnSetTempCommand, + weak_ptr_factory_.GetWeakPtr())); + + device->AddCommandHandler(kComponent, "brightness.setConfig", + base::Bind(&OvenHandler::OnSetBrightnessCommand, + weak_ptr_factory_.GetWeakPtr())); + } + + private: + void OnSetTempCommand(const std::weak_ptr<weave::Command>& command) { + auto cmd = command.lock(); + if (!cmd) + return; + LOG(INFO) << "received command: " << cmd->GetName(); + + const auto& params = cmd->GetParameters(); + std::string units; + double temp; + + if (params.GetString("units", &units) && + params.GetDouble("tempSetting", &temp)) { + units_ = units; + target_temperature_ = temp; + + UpdateOvenState(); + + cmd->Complete({}, nullptr); + LOG(INFO) << cmd->GetName() << " updated oven, matching temp"; + + if (target_temperature_ != current_temperature_ && !is_match_ticking_) { + double tickIncrement = + ((target_temperature_ - current_temperature_) / kWarmUpTime); + DoTick(tickIncrement); + } + return; + } + + weave::ErrorPtr error; + weave::Error::AddTo(&error, FROM_HERE, "invalid_parameter_value", + "Invalid parameters"); + cmd->Abort(error.get(), nullptr); + } + + void OnSetBrightnessCommand(const std::weak_ptr<weave::Command>& command) { + auto cmd = command.lock(); + if (!cmd) + return; + LOG(INFO) << "received command: " << cmd->GetName(); + + const auto& params = cmd->GetParameters(); + + int brightness; + if (params.GetInteger("brightness", &brightness)) { + brightness_ = brightness; + + UpdateOvenState(); + + cmd->Complete({}, nullptr); + return; + } + + weave::ErrorPtr error; + weave::Error::AddTo(&error, FROM_HERE, "invalid_parameter_value", + "Invalid parameters"); + cmd->Abort(error.get(), nullptr); + } + + void UpdateOvenState() { + base::DictionaryValue state; + base::ListValue supportedUnits; + supportedUnits.AppendStrings({"celsius"}); + + state.SetString("temperatureSensor.units", units_); + state.SetDouble("temperatureSensor.value", current_temperature_); + state.Set("temperatureSensor.supportedUnits", + supportedUnits.CreateDeepCopy()); + + state.SetString("temperatureSetting.units", units_); + state.SetDouble("temperatureSetting.tempSetting", target_temperature_); + state.Set("temperatureSetting.supportedUnits", + supportedUnits.CreateDeepCopy()); + state.SetDouble("temperatureSetting.maxTempSetting", kMaxTemp); + state.SetDouble("temperatureSetting.minTempSetting", kMinTemp); + + state.SetInteger("brightness.brightness", brightness_); + + device_->SetStateProperties(kComponent, state, nullptr); + } + + void DoTick(double tickIncrement) { + LOG(INFO) << "Oven matching temp tick"; + + if (std::fabs(target_temperature_ - current_temperature_) >= + tickIncrement) { + is_match_ticking_ = true; + current_temperature_ += tickIncrement; + UpdateOvenState(); + task_runner_->PostDelayedTask( + FROM_HERE, base::Bind(&OvenHandler::DoTick, + weak_ptr_factory_.GetWeakPtr(), tickIncrement), + base::TimeDelta::FromSeconds(1)); + return; + } + + is_match_ticking_ = false; + current_temperature_ = target_temperature_; + UpdateOvenState(); + + LOG(INFO) << "Oven temp matched"; + } + + weave::Device* device_{nullptr}; + weave::provider::TaskRunner* task_runner_{nullptr}; + + std::string units_ = "celsius"; + double target_temperature_ = 0.0; + double current_temperature_ = 0.0; + int brightness_ = 0; + bool is_match_ticking_ = false; + + base::WeakPtrFactory<OvenHandler> weak_ptr_factory_{this}; +}; + +int main(int argc, char** argv) { + Daemon::Options opts; + if (!opts.Parse(argc, argv)) { + Daemon::Options::ShowUsage(argv[0]); + return 1; + } + Daemon daemon{opts}; + OvenHandler handler{daemon.GetTaskRunner()}; + handler.Register(daemon.GetDevice()); + daemon.Run(); + return 0; +} diff --git a/examples/daemon/speaker/speaker.cc b/examples/daemon/speaker/speaker.cc new file mode 100644 index 0000000..56da840 --- /dev/null +++ b/examples/daemon/speaker/speaker.cc @@ -0,0 +1,178 @@ +// Copyright 2015 The Weave Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "examples/daemon/common/daemon.h" + +#include <weave/device.h> + +#include <base/bind.h> +#include <base/memory/weak_ptr.h> + +namespace { + +const char kTraits[] = R"({ + "onOff": { + "commands": { + "setConfig": { + "minimalRole": "user", + "parameters": { + "state": { + "type": "string", + "enum": [ "on", "off" ] + } + } + } + }, + "state": { + "state": { + "type": "string", + "enum": [ "on", "off" ], + "isRequired": true + } + } + }, + "volume": { + "commands": { + "setConfig": { + "minimalRole": "user", + "parameters": { + "volume": { + "type": "integer", + "minimum": 0, + "maximum": 100 + }, + "isMuted": { "type": "boolean" } + } + } + }, + "state": { + "isMuted": { + "type": "boolean", + "isRequired": true + }, + "volume": { + "type": "integer", + "minimum": 0, + "maximum": 100, + "isRequired": true + } + } + } +})"; + +const char kComponent[] = "speaker"; + +} // anonymous namespace + +// SpeakerHandler is a command handler example that shows +// how to handle commands for a Weave speaker. +class SpeakerHandler { + public: + SpeakerHandler() = default; + void Register(weave::Device* device) { + device_ = device; + + device->AddTraitDefinitionsFromJson(kTraits); + CHECK(device->AddComponent(kComponent, {"onOff", "volume"}, nullptr)); + UpdateSpeakerState(); + + device->AddCommandHandler(kComponent, "onOff.setConfig", + base::Bind(&SpeakerHandler::OnOnOffSetConfig, + weak_ptr_factory_.GetWeakPtr())); + device->AddCommandHandler(kComponent, "volume.setConfig", + base::Bind(&SpeakerHandler::OnVolumeSetConfig, + weak_ptr_factory_.GetWeakPtr())); + } + + private: + void OnVolumeSetConfig(const std::weak_ptr<weave::Command>& command) { + auto cmd = command.lock(); + if (!cmd) + return; + LOG(INFO) << "received command: " << cmd->GetName(); + + const auto& params = cmd->GetParameters(); + // Handle volume parameter + int32_t volume_value = 0; + if (params.GetInteger("volume", &volume_value)) { + // Display this command in terminal. + LOG(INFO) << cmd->GetName() << " volume: " << volume_value; + + if (volume_value_ != volume_value) { + volume_value_ = volume_value; + UpdateSpeakerState(); + } + cmd->Complete({}, nullptr); + return; + } + + // Handle isMuted parameter + bool isMuted_status = false; + if (params.GetBoolean("isMuted", &isMuted_status)) { + // Display this command in terminal. + LOG(INFO) << cmd->GetName() << " is " + << (isMuted_status ? "muted" : "not muted"); + + if (isMuted_status_ != isMuted_status) { + isMuted_status_ = isMuted_status; + + LOG(INFO) << "Speaker is now: " + << (isMuted_status ? "muted" : "not muted"); + UpdateSpeakerState(); + } + } + + cmd->Complete({}, nullptr); + } + + void OnOnOffSetConfig(const std::weak_ptr<weave::Command>& command) { + auto cmd = command.lock(); + if (!cmd) + return; + LOG(INFO) << "received command: " << cmd->GetName(); + const auto& params = cmd->GetParameters(); + std::string requested_state; + if (params.GetString("state", &requested_state)) { + LOG(INFO) << cmd->GetName() << " state: " << requested_state; + + bool new_speaker_status = requested_state == "on"; + if (new_speaker_status != speaker_status_) { + speaker_status_ = new_speaker_status; + + LOG(INFO) << "Speaker is now: " << (speaker_status_ ? "ON" : "OFF"); + UpdateSpeakerState(); + } + } + cmd->Complete({}, nullptr); + } + + void UpdateSpeakerState() { + base::DictionaryValue state; + state.SetString("onOff.state", speaker_status_ ? "on" : "off"); + state.SetBoolean("volume.isMuted", isMuted_status_); + state.SetInteger("volume.volume", volume_value_); + device_->SetStateProperties(kComponent, state, nullptr); + } + + weave::Device* device_{nullptr}; + + // Simulate the state of the speaker. + bool speaker_status_; + bool isMuted_status_; + int32_t volume_value_; + base::WeakPtrFactory<SpeakerHandler> weak_ptr_factory_{this}; +}; + +int main(int argc, char** argv) { + Daemon::Options opts; + if (!opts.Parse(argc, argv)) { + Daemon::Options::ShowUsage(argv[0]); + return 1; + } + Daemon daemon{opts}; + SpeakerHandler speaker; + speaker.Register(daemon.GetDevice()); + daemon.Run(); + return 0; +} diff --git a/examples/examples.mk b/examples/examples.mk index cb64e2b..555322c 100644 --- a/examples/examples.mk +++ b/examples/examples.mk @@ -21,7 +21,9 @@ EXAMPLES_DAEMON_SRC_FILES := \ examples/daemon/ledflasher/ledflasher.cc \ examples/daemon/light/light.cc \ examples/daemon/lock/lock.cc \ - examples/daemon/sample/sample.cc + examples/daemon/oven/oven.cc \ + examples/daemon/sample/sample.cc \ + examples/daemon/speaker/speaker.cc examples_daemon_obj_files := $(EXAMPLES_DAEMON_SRC_FILES:%.cc=out/$(BUILD_MODE)/%.o) @@ -60,10 +62,16 @@ out/$(BUILD_MODE)/weave_daemon_light : out/$(BUILD_MODE)/examples/daemon/light/l out/$(BUILD_MODE)/weave_daemon_lock : out/$(BUILD_MODE)/examples/daemon/lock/lock.o $(example_daemon_deps) $(CXX) -o $@ $^ $(CFLAGS) $(example_daemon_common_flags) +out/$(BUILD_MODE)/weave_daemon_oven : out/$(BUILD_MODE)/examples/daemon/oven/oven.o $(example_daemon_deps) + $(CXX) -o $@ $^ $(CFLAGS) $(example_daemon_common_flags) + out/$(BUILD_MODE)/weave_daemon_sample : out/$(BUILD_MODE)/examples/daemon/sample/sample.o $(example_daemon_deps) $(CXX) -o $@ $^ $(CFLAGS) $(example_daemon_common_flags) -all-examples : out/$(BUILD_MODE)/weave_daemon_ledflasher out/$(BUILD_MODE)/weave_daemon_light out/$(BUILD_MODE)/weave_daemon_lock out/$(BUILD_MODE)/weave_daemon_sample +out/$(BUILD_MODE)/weave_daemon_speaker : out/$(BUILD_MODE)/examples/daemon/speaker/speaker.o $(example_daemon_deps) + $(CXX) -o $@ $^ $(CFLAGS) $(example_daemon_common_flags) + +all-examples : out/$(BUILD_MODE)/weave_daemon_ledflasher out/$(BUILD_MODE)/weave_daemon_light out/$(BUILD_MODE)/weave_daemon_lock out/$(BUILD_MODE)/weave_daemon_oven out/$(BUILD_MODE)/weave_daemon_sample out/$(BUILD_MODE)/weave_daemon_speaker .PHONY : all-examples diff --git a/examples/provider/avahi_client.cc b/examples/provider/avahi_client.cc index 36109c4..ddd4630 100644 --- a/examples/provider/avahi_client.cc +++ b/examples/provider/avahi_client.cc @@ -5,7 +5,6 @@ #include "examples/provider/avahi_client.h" #include <cstdlib> -#include <memory> #include <vector> #include <avahi-common/error.h> diff --git a/examples/provider/avahi_client.h b/examples/provider/avahi_client.h index f9ba01c..7d9b932 100644 --- a/examples/provider/avahi_client.h +++ b/examples/provider/avahi_client.h @@ -6,7 +6,6 @@ #define LIBWEAVE_EXAMPLES_PROVIDER_AVAHI_CLIENT_H_ #include <map> -#include <memory> #include <string> #include <avahi-client/client.h> diff --git a/examples/provider/event_network.h b/examples/provider/event_network.h index 6a5617f..3aeac24 100644 --- a/examples/provider/event_network.h +++ b/examples/provider/event_network.h @@ -5,8 +5,6 @@ #ifndef LIBWEAVE_EXAMPLES_UBUNTU_EVENT_NETWORK_H_ #define LIBWEAVE_EXAMPLES_UBUNTU_EVENT_NETWORK_H_ -#include <vector> - #include <weave/provider/network.h> #include <base/memory/weak_ptr.h> diff --git a/examples/provider/event_task_runner.h b/examples/provider/event_task_runner.h index a788950..97f9db9 100644 --- a/examples/provider/event_task_runner.h +++ b/examples/provider/event_task_runner.h @@ -6,7 +6,6 @@ #define LIBWEAVE_EXAMPLES_PROVIDER_EVENT_TASK_RUNNER_H_ #include <queue> -#include <map> #include <utility> #include <vector> diff --git a/include/weave/provider/test/fake_task_runner.h b/include/weave/provider/test/fake_task_runner.h index 9a06a8e..9476d02 100644 --- a/include/weave/provider/test/fake_task_runner.h +++ b/include/weave/provider/test/fake_task_runner.h @@ -9,7 +9,6 @@ #include <algorithm> #include <queue> -#include <memory> #include <utility> #include <vector> diff --git a/include/weave/settings.h b/include/weave/settings.h index 2ebc4f2..2dceedb 100644 --- a/include/weave/settings.h +++ b/include/weave/settings.h @@ -13,7 +13,7 @@ namespace weave { // Scopes in order of increasing privileges. -enum class AuthScope : int32_t { +enum class AuthScope { kNone, kViewer, kUser, diff --git a/src/access_revocation_manager_impl.cc b/src/access_revocation_manager_impl.cc index 1c051de..93bdf3f 100644 --- a/src/access_revocation_manager_impl.cc +++ b/src/access_revocation_manager_impl.cc @@ -4,11 +4,8 @@ #include "src/access_revocation_manager_impl.h" -#include <memory> - #include <base/json/json_reader.h> #include <base/json/json_writer.h> -#include <base/memory/ptr_util.h> #include <base/values.h> #include "src/commands/schema_constants.h" @@ -73,8 +70,7 @@ void AccessRevocationManagerImpl::Save(const DoneCallback& callback) { base::ListValue list; for (const auto& e : entries_) { - std::unique_ptr<base::DictionaryValue> entry = - base::MakeUnique<base::DictionaryValue>(); + scoped_ptr<base::DictionaryValue> entry{new base::DictionaryValue}; entry->SetString(kUser, Base64Encode(e.user_id)); entry->SetString(kApp, Base64Encode(e.app_id)); entry->SetInteger(kRevocation, ToJ2000Time(e.revocation)); diff --git a/src/bind_lambda.h b/src/bind_lambda.h index 164e3e4..e6f367c 100644 --- a/src/bind_lambda.h +++ b/src/bind_lambda.h @@ -31,7 +31,7 @@ class LambdaAdapter<Lambda, R (Lambda::*)(Args... args)> { public: typedef R(RunType)(Args...); LambdaAdapter(Lambda lambda) : lambda_(lambda) {} - R Run(Args... args) { return lambda_(std::forward<Args>(args)...); } + R Run(Args... args) { return lambda_(CallbackForward(args)...); } private: Lambda lambda_; @@ -43,7 +43,7 @@ class LambdaAdapter<Lambda, R (Lambda::*)(Args... args) const> { public: typedef R(RunType)(Args...); LambdaAdapter(Lambda lambda) : lambda_(lambda) {} - R Run(Args... args) { return lambda_(std::forward<Args>(args)...); } + R Run(Args... args) { return lambda_(CallbackForward(args)...); } private: Lambda lambda_; diff --git a/src/privet/privet_handler.cc b/src/privet/privet_handler.cc index ada9f44..42a1c23 100644 --- a/src/privet/privet_handler.cc +++ b/src/privet/privet_handler.cc @@ -711,8 +711,7 @@ void PrivetHandler::HandleAuth(const base::DictionaryValue& input, return ReturnError(*error, callback); } - CHECK_LE(static_cast<int32_t>(access_token_scope), - static_cast<int32_t>(desired_scope)); + CHECK_LE(access_token_scope, desired_scope); if (access_token_scope < acceptable_scope) { Error::AddToPrintf(&error, FROM_HERE, errors::kAccessDenied, diff --git a/src/privet/privet_handler.h b/src/privet/privet_handler.h index eab1aa3..e64151b 100644 --- a/src/privet/privet_handler.h +++ b/src/privet/privet_handler.h @@ -12,7 +12,6 @@ #include <base/macros.h> #include <base/memory/weak_ptr.h> #include <base/time/default_clock.h> -#include <weave/settings.h> #include "src/privet/cloud_delegate.h" diff --git a/src/privet/privet_types.h b/src/privet/privet_types.h index 2a290d4..44be96f 100644 --- a/src/privet/privet_types.h +++ b/src/privet/privet_types.h @@ -6,7 +6,6 @@ #define LIBWEAVE_SRC_PRIVET_PRIVET_TYPES_H_ #include <string> -#include <vector> #include <base/logging.h> #include <weave/error.h> diff --git a/src/streams.h b/src/streams.h index cefcf94..990f47c 100644 --- a/src/streams.h +++ b/src/streams.h @@ -5,8 +5,6 @@ #ifndef LIBWEAVE_SRC_STREAMS_H_ #define LIBWEAVE_SRC_STREAMS_H_ -#include <vector> - #include <base/memory/weak_ptr.h> #include <weave/stream.h> diff --git a/tests_schema/daemon/testdevice/standard_traits.h b/tests_schema/daemon/testdevice/standard_traits.h index 27586f8..c63c5fe 100644 --- a/tests_schema/daemon/testdevice/standard_traits.h +++ b/tests_schema/daemon/testdevice/standard_traits.h @@ -196,35 +196,6 @@ const char kTraits[] = R"({ } } } - }, - "volume": { - "commands": { - "setConfig": { - "minimalRole": "user", - "parameters": { - "volume": { - "type": "integer", - "minimum": 0, - "maximum": 100 - }, - "isMuted": { - "type": "boolean" - } - } - } - }, - "state": { - "volume": { - "isRequired": true, - "type": "integer", - "minimum": 0, - "maximum": 100 - }, - "isMuted": { - "isRequired": true, - "type": "boolean" - } - } } })"; @@ -232,7 +203,6 @@ const char kDefaultState[] = R"({ "lock":{"isLockingSupported": true}, "onOff":{"state": "on"}, "brightness":{"brightness": 0.0}, - "volume":{"isMuted": true}, "colorTemp":{"colorTemp": 0}, "colorXy": { "colorSetting": {"colorX": 0.0, "colorY": 0.0}, diff --git a/tests_schema/daemon/testdevice/testdevice.cc b/tests_schema/daemon/testdevice/testdevice.cc index 7a29eac..a69ff46 100644 --- a/tests_schema/daemon/testdevice/testdevice.cc +++ b/tests_schema/daemon/testdevice/testdevice.cc @@ -45,8 +45,7 @@ class TestDeviceHandler { CHECK(device->AddComponent( standard_traits::kComponent, - {"lock", "onOff", "brightness", "volume", "colorTemp", "colorXy"}, - nullptr)); + {"lock", "onOff", "brightness", "colorTemp", "colorXy"}, nullptr)); CHECK(device->AddComponent(custom_traits::ledflasher, {"_ledflasher"}, nullptr)); @@ -80,9 +79,6 @@ class TestDeviceHandler { standard_traits::kComponent, "brightness.setConfig", base::Bind(&TestDeviceHandler::OnBrightnessSetConfig, weak_ptr_factory_.GetWeakPtr())); - device->AddCommandHandler(standard_traits::kComponent, "volume.setConfig", - base::Bind(&TestDeviceHandler::OnVolumeSetConfig, - weak_ptr_factory_.GetWeakPtr())); device->AddCommandHandler( standard_traits::kComponent, "colorTemp.setConfig", base::Bind(&TestDeviceHandler::OnColorTempSetConfig, @@ -152,50 +148,6 @@ class TestDeviceHandler { AbortCommand(cmd); } - void OnVolumeSetConfig(const std::weak_ptr<weave::Command>& command) { - auto cmd = command.lock(); - if (!cmd) - return; - LOG(INFO) << "received command: " << cmd->GetName(); - const auto& params = cmd->GetParameters(); - // Handle volume parameter - bool updateState = false; - int32_t volume_value = 0; - if (params.GetInteger("volume", &volume_value)) { - LOG(INFO) << cmd->GetName() << " volume: " << volume_value; - - if (volume_value < 0 || volume_value > 100) { - // Invalid volume range value is specified. - AbortCommand(cmd); - return; - } - - if (volume_value_ != volume_value) { - volume_value_ = volume_value; - updateState = true; - } - } - - // Handle isMuted parameter - bool isMuted_status = false; - if (params.GetBoolean("isMuted", &isMuted_status)) { - LOG(INFO) << cmd->GetName() << " is " - << (isMuted_status ? "muted" : "not muted"); - - if (isMuted_status_ != isMuted_status) { - isMuted_status_ = isMuted_status; - LOG(INFO) << "Speaker is now: " - << (isMuted_status ? "muted" : "not muted"); - updateState = true; - } - } - - if (updateState) { - UpdateTestDeviceState(); - } - cmd->Complete({}, nullptr); - } - void OnOnOffSetConfig(const std::weak_ptr<weave::Command>& command) { auto cmd = command.lock(); if (!cmd) @@ -207,16 +159,18 @@ class TestDeviceHandler { LOG(INFO) << cmd->GetName() << " state: " << requested_state; std::string temp_state = requested_state; - if (temp_state != "on" && temp_state != "off") { + std::transform(temp_state.begin(), temp_state.end(), temp_state.begin(), + ::toupper); + if (temp_state != "ON" && temp_state != "OFF") { // Invalid OnOff state is specified. AbortCommand(cmd); return; } - bool new_device_status = requested_state == "on"; - if (new_device_status != device_status_) { - device_status_ = new_device_status; - LOG(INFO) << "Device is now: " << (device_status_ ? "ON" : "OFF"); + bool new_light_status = requested_state == "on"; + if (new_light_status != light_status_) { + light_status_ = new_light_status; + LOG(INFO) << "Light is now: " << (light_status_ ? "ON" : "OFF"); UpdateTestDeviceState(); } cmd->Complete({}, nullptr); @@ -365,11 +319,8 @@ class TestDeviceHandler { device_->SetStateProperty(standard_traits::kComponent, "lock.lockedState", base::StringValue{updated_state}, nullptr); base::DictionaryValue state; - state.SetString("onOff.state", device_status_ ? "on" : "off"); + state.SetString("onOff.state", light_status_ ? "on" : "off"); state.SetDouble("brightness.brightness", brightness_state_); - // state.SetString("onOff.state", speaker_status_ ? "on" : "off"); - state.SetBoolean("volume.isMuted", isMuted_status_); - state.SetInteger("volume.volume", volume_value_); state.SetInteger("colorTemp.minColorTemp", color_temp_min_value_); state.SetInteger("colorTemp.maxColorTemp", color_temp_max_value_); state.SetInteger("colorTemp.colorTemp", color_temp_); @@ -393,10 +344,8 @@ class TestDeviceHandler { // Simulate the state of the testdevice. weave::lockstate::LockState lock_state_{weave::lockstate::LockState::kLocked}; - bool device_status_{false}; + bool light_status_{false}; double brightness_state_{0.0}; - bool isMuted_status_{false}; - int32_t volume_value_{0}; int32_t color_temp_{0}; int32_t color_temp_min_value_{0}; int32_t color_temp_max_value_{1}; diff --git a/third_party/chromium/base/bind_unittest.cc b/third_party/chromium/base/bind_unittest.cc index 4c4f3e6..76d158b 100644 --- a/third_party/chromium/base/bind_unittest.cc +++ b/third_party/chromium/base/bind_unittest.cc @@ -13,8 +13,8 @@ #include "base/callback.h" #include "base/macros.h" -#include "base/memory/ptr_util.h" #include "base/memory/ref_counted.h" +#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "build/build_config.h" @@ -823,7 +823,7 @@ struct CustomDeleter { }; using MoveOnlyTypesToTest = - ::testing::Types<std::unique_ptr<DeleteCounter>, + ::testing::Types<scoped_ptr<DeleteCounter>, std::unique_ptr<DeleteCounter>, std::unique_ptr<DeleteCounter, CustomDeleter>>; TYPED_TEST_CASE(BindMoveOnlyTypeTest, MoveOnlyTypesToTest); @@ -880,23 +880,23 @@ TYPED_TEST(BindMoveOnlyTypeTest, UnboundForwarding) { EXPECT_EQ(1, deletes); } -void VerifyVector(const std::vector<std::unique_ptr<int>>& v) { +void VerifyVector(const std::vector<scoped_ptr<int>>& v) { ASSERT_EQ(1u, v.size()); EXPECT_EQ(12345, *v[0]); } -std::vector<std::unique_ptr<int>> AcceptAndReturnMoveOnlyVector( - std::vector<std::unique_ptr<int>> v) { +std::vector<scoped_ptr<int>> AcceptAndReturnMoveOnlyVector( + std::vector<scoped_ptr<int>> v) { VerifyVector(v); return v; } // Test that a vector containing move-only types can be used with Callback. TEST_F(BindTest, BindMoveOnlyVector) { - using MoveOnlyVector = std::vector<std::unique_ptr<int>>; + using MoveOnlyVector = std::vector<scoped_ptr<int>>; MoveOnlyVector v; - v.push_back(base::MakeUnique<int>(12345)); + v.push_back(make_scoped_ptr(new int(12345))); // Early binding should work: base::Callback<MoveOnlyVector()> bound_cb = diff --git a/third_party/chromium/base/callback_internal.h b/third_party/chromium/base/callback_internal.h index d700794..3682bf9 100644 --- a/third_party/chromium/base/callback_internal.h +++ b/third_party/chromium/base/callback_internal.h @@ -8,12 +8,17 @@ #ifndef BASE_CALLBACK_INTERNAL_H_ #define BASE_CALLBACK_INTERNAL_H_ -#include <atomic> +#include <stddef.h> +#include <map> +#include <memory> +#include <type_traits> +#include <vector> #include "base/base_export.h" #include "base/callback_forward.h" #include "base/macros.h" #include "base/memory/ref_counted.h" +#include "base/memory/scoped_ptr.h" namespace base { namespace internal { @@ -112,6 +117,129 @@ class BASE_EXPORT CallbackBase<CopyMode::Copyable> extern template class CallbackBase<CopyMode::MoveOnly>; extern template class CallbackBase<CopyMode::Copyable>; +// A helper template to determine if given type is non-const move-only-type, +// i.e. if a value of the given type should be passed via std::move() in a +// destructive way. Types are considered to be move-only if they have a +// sentinel MoveOnlyTypeForCPP03 member: a class typically gets this from using +// the DISALLOW_COPY_AND_ASSIGN_WITH_MOVE_FOR_BIND macro. +// It would be easy to generalize this trait to all move-only types... but this +// confuses template deduction in VS2013 with certain types such as +// std::unique_ptr. +// TODO(dcheng): Revisit this when Windows switches to VS2015 by default. + +template <typename T> struct IsMoveOnlyType { + // Types YesType and NoType are guaranteed such that sizeof(YesType) < + // sizeof(NoType). + using YesType = char; + struct NoType { YesType dummy[2]; }; + + template <typename U> + static YesType Test(const typename U::MoveOnlyTypeForCPP03*); + + template <typename U> + static NoType Test(...); + + static const bool value = sizeof((Test<T>(0))) == sizeof(YesType) && + !std::is_const<T>::value; +}; + +// Specialization of IsMoveOnlyType so that std::unique_ptr is still considered +// move-only, even without the sentinel member. +template <typename T, typename D> +struct IsMoveOnlyType<std::unique_ptr<T, D>> : std::true_type {}; + +// Specialization of std::vector, so that it's considered move-only if the +// element type is move-only. Allocator is explicitly ignored when determining +// move-only status of the std::vector. +template <typename T, typename Allocator> +struct IsMoveOnlyType<std::vector<T, Allocator>> : IsMoveOnlyType<T> {}; + +template <typename> +struct CallbackParamTraitsForMoveOnlyType; + +template <typename> +struct CallbackParamTraitsForNonMoveOnlyType; + +// TODO(tzik): Use a default parameter once MSVS supports variadic templates +// with default values. +// http://connect.microsoft.com/VisualStudio/feedbackdetail/view/957801/compilation-error-with-variadic-templates +// +// This is a typetraits object that's used to take an argument type, and +// extract a suitable type for forwarding arguments. +template <typename T> +struct CallbackParamTraits + : std::conditional<IsMoveOnlyType<T>::value, + CallbackParamTraitsForMoveOnlyType<T>, + CallbackParamTraitsForNonMoveOnlyType<T>>::type { +}; + +template <typename T> +struct CallbackParamTraitsForNonMoveOnlyType { + using ForwardType = const T&; +}; + +// Note that for array types, we implicitly add a const in the conversion. This +// means that it is not possible to bind array arguments to functions that take +// a non-const pointer. Trying to specialize the template based on a "const +// T[n]" does not seem to match correctly, so we are stuck with this +// restriction. +template <typename T, size_t n> +struct CallbackParamTraitsForNonMoveOnlyType<T[n]> { + using ForwardType = const T*; +}; + +// See comment for CallbackParamTraits<T[n]>. +template <typename T> +struct CallbackParamTraitsForNonMoveOnlyType<T[]> { + using ForwardType = const T*; +}; + +// Parameter traits for movable-but-not-copyable scopers. +// +// Callback<>/Bind() understands movable-but-not-copyable semantics where +// the type cannot be copied but can still have its state destructively +// transferred (aka. moved) to another instance of the same type by calling a +// helper function. When used with Bind(), this signifies transferal of the +// object's state to the target function. +// +// For these types, the ForwardType must not be a const reference, or a +// reference. A const reference is inappropriate, and would break const +// correctness, because we are implementing a destructive move. A non-const +// reference cannot be used with temporaries which means the result of a +// function or a cast would not be usable with Callback<> or Bind(). +template <typename T> +struct CallbackParamTraitsForMoveOnlyType { + using ForwardType = T; +}; + +// CallbackForward() is a very limited simulation of C++11's std::forward() +// used by the Callback/Bind system for a set of movable-but-not-copyable +// types. It is needed because forwarding a movable-but-not-copyable +// argument to another function requires us to invoke the proper move +// operator to create a rvalue version of the type. The supported types are +// whitelisted below as overloads of the CallbackForward() function. The +// default template compiles out to be a no-op. +// +// In C++11, std::forward would replace all uses of this function. However, it +// is impossible to implement a general std::forward without C++11 due to a lack +// of rvalue references. +// +// In addition to Callback/Bind, this is used by PostTaskAndReplyWithResult to +// simulate std::forward() and forward the result of one Callback as a +// parameter to another callback. This is to support Callbacks that return +// the movable-but-not-copyable types whitelisted above. +template <typename T> +typename std::enable_if<!IsMoveOnlyType<T>::value, T>::type& CallbackForward( + T& t) { + return t; +} + +template <typename T> +typename std::enable_if<IsMoveOnlyType<T>::value, T>::type CallbackForward( + T& t) { + return std::move(t); +} + } // namespace internal } // namespace base diff --git a/third_party/chromium/base/callback_list.h b/third_party/chromium/base/callback_list.h index 7ab79dd..7d6a478 100644 --- a/third_party/chromium/base/callback_list.h +++ b/third_party/chromium/base/callback_list.h @@ -6,12 +6,13 @@ #define BASE_CALLBACK_LIST_H_ #include <list> -#include <memory> #include "base/callback.h" +#include "base/callback_internal.h" #include "base/compiler_specific.h" #include "base/logging.h" #include "base/macros.h" +#include "base/memory/scoped_ptr.h" // OVERVIEW: // @@ -28,7 +29,7 @@ // // typedef base::Callback<void(const Foo&)> OnFooCallback; // -// std::unique_ptr<base::CallbackList<void(const Foo&)>::Subscription> +// scoped_ptr<base::CallbackList<void(const Foo&)>::Subscription> // RegisterCallback(const OnFooCallback& cb) { // return callback_list_.Add(cb); // } @@ -61,7 +62,7 @@ // // Do something. // } // -// std::unique_ptr<base::CallbackList<void(const Foo&)>::Subscription> +// scoped_ptr<base::CallbackList<void(const Foo&)>::Subscription> // foo_subscription_; // // DISALLOW_COPY_AND_ASSIGN(MyWidgetListener); @@ -102,9 +103,9 @@ class CallbackListBase { // Add a callback to the list. The callback will remain registered until the // returned Subscription is destroyed, which must occur before the // CallbackList is destroyed. - std::unique_ptr<Subscription> Add(const CallbackType& cb) WARN_UNUSED_RESULT { + scoped_ptr<Subscription> Add(const CallbackType& cb) WARN_UNUSED_RESULT { DCHECK(!cb.is_null()); - return std::unique_ptr<Subscription>( + return scoped_ptr<Subscription>( new Subscription(this, callbacks_.insert(callbacks_.end(), cb))); } @@ -210,8 +211,8 @@ class CallbackList<void(Args...)> CallbackList() {} - template <typename... RunArgs> - void Notify(RunArgs&&... args) { + void Notify( + typename internal::CallbackParamTraits<Args>::ForwardType... args) { typename internal::CallbackListBase<CallbackType>::Iterator it = this->GetIterator(); CallbackType* cb; diff --git a/third_party/chromium/base/callback_list_unittest.cc b/third_party/chromium/base/callback_list_unittest.cc index bd6634d..937910e 100644 --- a/third_party/chromium/base/callback_list_unittest.cc +++ b/third_party/chromium/base/callback_list_unittest.cc @@ -5,12 +5,12 @@ #include "base/callback_list.h" #include <gtest/gtest.h> -#include <memory> #include <utility> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/macros.h" +#include "base/memory/scoped_ptr.h" namespace base { namespace { @@ -38,7 +38,7 @@ class Remover { removal_subscription_.reset(); } void SetSubscriptionToRemove( - std::unique_ptr<CallbackList<void(void)>::Subscription> sub) { + scoped_ptr<CallbackList<void(void)>::Subscription> sub) { removal_subscription_ = std::move(sub); } @@ -46,7 +46,7 @@ class Remover { private: int total_; - std::unique_ptr<CallbackList<void(void)>::Subscription> removal_subscription_; + scoped_ptr<CallbackList<void(void)>::Subscription> removal_subscription_; DISALLOW_COPY_AND_ASSIGN(Remover); }; @@ -74,7 +74,7 @@ class Adder { bool added_; int total_; CallbackList<void(void)>* cb_reg_; - std::unique_ptr<CallbackList<void(void)>::Subscription> subscription_; + scoped_ptr<CallbackList<void(void)>::Subscription> subscription_; DISALLOW_COPY_AND_ASSIGN(Adder); }; @@ -118,43 +118,42 @@ TEST(CallbackListTest, ArityTest) { Summer s; CallbackList<void(int)> c1; - std::unique_ptr<CallbackList<void(int)>::Subscription> subscription1 = + scoped_ptr<CallbackList<void(int)>::Subscription> subscription1 = c1.Add(Bind(&Summer::AddOneParam, Unretained(&s))); c1.Notify(1); EXPECT_EQ(1, s.value()); CallbackList<void(int, int)> c2; - std::unique_ptr<CallbackList<void(int, int)>::Subscription> subscription2 = + scoped_ptr<CallbackList<void(int, int)>::Subscription> subscription2 = c2.Add(Bind(&Summer::AddTwoParam, Unretained(&s))); c2.Notify(1, 2); EXPECT_EQ(3, s.value()); CallbackList<void(int, int, int)> c3; - std::unique_ptr<CallbackList<void(int, int, int)>::Subscription> + scoped_ptr<CallbackList<void(int, int, int)>::Subscription> subscription3 = c3.Add(Bind(&Summer::AddThreeParam, Unretained(&s))); c3.Notify(1, 2, 3); EXPECT_EQ(6, s.value()); CallbackList<void(int, int, int, int)> c4; - std::unique_ptr<CallbackList<void(int, int, int, int)>::Subscription> + scoped_ptr<CallbackList<void(int, int, int, int)>::Subscription> subscription4 = c4.Add(Bind(&Summer::AddFourParam, Unretained(&s))); c4.Notify(1, 2, 3, 4); EXPECT_EQ(10, s.value()); CallbackList<void(int, int, int, int, int)> c5; - std::unique_ptr<CallbackList<void(int, int, int, int, int)>::Subscription> + scoped_ptr<CallbackList<void(int, int, int, int, int)>::Subscription> subscription5 = c5.Add(Bind(&Summer::AddFiveParam, Unretained(&s))); c5.Notify(1, 2, 3, 4, 5); EXPECT_EQ(15, s.value()); CallbackList<void(int, int, int, int, int, int)> c6; - std::unique_ptr< - CallbackList<void(int, int, int, int, int, int)>::Subscription> + scoped_ptr<CallbackList<void(int, int, int, int, int, int)>::Subscription> subscription6 = c6.Add(Bind(&Summer::AddSixParam, Unretained(&s))); c6.Notify(1, 2, 3, 4, 5, 6); @@ -167,9 +166,9 @@ TEST(CallbackListTest, BasicTest) { CallbackList<void(void)> cb_reg; Listener a, b, c; - std::unique_ptr<CallbackList<void(void)>::Subscription> a_subscription = + scoped_ptr<CallbackList<void(void)>::Subscription> a_subscription = cb_reg.Add(Bind(&Listener::IncrementTotal, Unretained(&a))); - std::unique_ptr<CallbackList<void(void)>::Subscription> b_subscription = + scoped_ptr<CallbackList<void(void)>::Subscription> b_subscription = cb_reg.Add(Bind(&Listener::IncrementTotal, Unretained(&b))); EXPECT_TRUE(a_subscription.get()); @@ -182,7 +181,7 @@ TEST(CallbackListTest, BasicTest) { b_subscription.reset(); - std::unique_ptr<CallbackList<void(void)>::Subscription> c_subscription = + scoped_ptr<CallbackList<void(void)>::Subscription> c_subscription = cb_reg.Add(Bind(&Listener::IncrementTotal, Unretained(&c))); cb_reg.Notify(); @@ -202,9 +201,9 @@ TEST(CallbackListTest, BasicTestWithParams) { CallbackList<void(int)> cb_reg; Listener a(1), b(-1), c(1); - std::unique_ptr<CallbackList<void(int)>::Subscription> a_subscription = + scoped_ptr<CallbackList<void(int)>::Subscription> a_subscription = cb_reg.Add(Bind(&Listener::IncrementByMultipleOfScaler, Unretained(&a))); - std::unique_ptr<CallbackList<void(int)>::Subscription> b_subscription = + scoped_ptr<CallbackList<void(int)>::Subscription> b_subscription = cb_reg.Add(Bind(&Listener::IncrementByMultipleOfScaler, Unretained(&b))); EXPECT_TRUE(a_subscription.get()); @@ -217,7 +216,7 @@ TEST(CallbackListTest, BasicTestWithParams) { b_subscription.reset(); - std::unique_ptr<CallbackList<void(int)>::Subscription> c_subscription = + scoped_ptr<CallbackList<void(int)>::Subscription> c_subscription = cb_reg.Add(Bind(&Listener::IncrementByMultipleOfScaler, Unretained(&c))); cb_reg.Notify(10); @@ -238,15 +237,15 @@ TEST(CallbackListTest, RemoveCallbacksDuringIteration) { Listener a, b; Remover remover_1, remover_2; - std::unique_ptr<CallbackList<void(void)>::Subscription> remover_1_sub = - cb_reg.Add( - Bind(&Remover::IncrementTotalAndRemove, Unretained(&remover_1))); - std::unique_ptr<CallbackList<void(void)>::Subscription> remover_2_sub = - cb_reg.Add( - Bind(&Remover::IncrementTotalAndRemove, Unretained(&remover_2))); - std::unique_ptr<CallbackList<void(void)>::Subscription> a_subscription = + scoped_ptr<CallbackList<void(void)>::Subscription> remover_1_sub = + cb_reg.Add(Bind(&Remover::IncrementTotalAndRemove, + Unretained(&remover_1))); + scoped_ptr<CallbackList<void(void)>::Subscription> remover_2_sub = + cb_reg.Add(Bind(&Remover::IncrementTotalAndRemove, + Unretained(&remover_2))); + scoped_ptr<CallbackList<void(void)>::Subscription> a_subscription = cb_reg.Add(Bind(&Listener::IncrementTotal, Unretained(&a))); - std::unique_ptr<CallbackList<void(void)>::Subscription> b_subscription = + scoped_ptr<CallbackList<void(void)>::Subscription> b_subscription = cb_reg.Add(Bind(&Listener::IncrementTotal, Unretained(&b))); // |remover_1| will remove itself. @@ -279,9 +278,9 @@ TEST(CallbackListTest, AddCallbacksDuringIteration) { CallbackList<void(void)> cb_reg; Adder a(&cb_reg); Listener b; - std::unique_ptr<CallbackList<void(void)>::Subscription> a_subscription = + scoped_ptr<CallbackList<void(void)>::Subscription> a_subscription = cb_reg.Add(Bind(&Adder::AddCallback, Unretained(&a))); - std::unique_ptr<CallbackList<void(void)>::Subscription> b_subscription = + scoped_ptr<CallbackList<void(void)>::Subscription> b_subscription = cb_reg.Add(Bind(&Listener::IncrementTotal, Unretained(&b))); cb_reg.Notify(); @@ -309,7 +308,7 @@ TEST(CallbackList, RemovalCallback) { cb_reg.set_removal_callback( Bind(&Counter::Increment, Unretained(&remove_count))); - std::unique_ptr<CallbackList<void(void)>::Subscription> subscription = + scoped_ptr<CallbackList<void(void)>::Subscription> subscription = cb_reg.Add(Bind(&DoNothing)); // Removing a subscription outside of iteration signals the callback. @@ -319,12 +318,12 @@ TEST(CallbackList, RemovalCallback) { // Configure two subscriptions to remove themselves. Remover remover_1, remover_2; - std::unique_ptr<CallbackList<void(void)>::Subscription> remover_1_sub = - cb_reg.Add( - Bind(&Remover::IncrementTotalAndRemove, Unretained(&remover_1))); - std::unique_ptr<CallbackList<void(void)>::Subscription> remover_2_sub = - cb_reg.Add( - Bind(&Remover::IncrementTotalAndRemove, Unretained(&remover_2))); + scoped_ptr<CallbackList<void(void)>::Subscription> remover_1_sub = + cb_reg.Add(Bind(&Remover::IncrementTotalAndRemove, + Unretained(&remover_1))); + scoped_ptr<CallbackList<void(void)>::Subscription> remover_2_sub = + cb_reg.Add(Bind(&Remover::IncrementTotalAndRemove, + Unretained(&remover_2))); remover_1.SetSubscriptionToRemove(std::move(remover_1_sub)); remover_2.SetSubscriptionToRemove(std::move(remover_2_sub)); diff --git a/third_party/chromium/base/callback_unittest.cc b/third_party/chromium/base/callback_unittest.cc index 0d35a9d..bf9d76f 100644 --- a/third_party/chromium/base/callback_unittest.cc +++ b/third_party/chromium/base/callback_unittest.cc @@ -5,11 +5,11 @@ #include "base/callback.h" #include <gtest/gtest.h> -#include <memory> #include "base/bind.h" #include "base/callback_internal.h" #include "base/memory/ref_counted.h" +#include "base/memory/scoped_ptr.h" namespace base { diff --git a/third_party/chromium/base/json/json_parser.cc b/third_party/chromium/base/json/json_parser.cc index 708965a..304a7bd 100644 --- a/third_party/chromium/base/json/json_parser.cc +++ b/third_party/chromium/base/json/json_parser.cc @@ -5,11 +5,10 @@ #include "base/json/json_parser.h" #include <cmath> -#include <utility> #include "base/logging.h" #include "base/macros.h" -#include "base/memory/ptr_util.h" +#include "base/memory/scoped_ptr.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_piece.h" #include "base/strings/string_util.h" @@ -27,19 +26,16 @@ const int kStackMaxDepth = 100; const int32_t kExtendedASCIIStart = 0x80; -// DictionaryHiddenRootValue and ListHiddenRootValue are used in conjunction -// with JSONStringValue as an optimization for reducing the number of string -// copies. When this optimization is active, the parser uses a hidden root to -// keep the original JSON input string live and creates JSONStringValue children -// holding StringPiece references to the input string, avoiding about 2/3rds of -// string memory copies. The real root value is Swap()ed into the new instance. +// This and the class below are used to own the JSON input string for when +// string tokens are stored as StringPiece instead of std::string. This +// optimization avoids about 2/3rds of string memory copies. The constructor +// takes ownership of the input string. The real root value is Swap()ed into +// the new instance. class DictionaryHiddenRootValue : public DictionaryValue { public: - DictionaryHiddenRootValue(std::unique_ptr<std::string> json, - std::unique_ptr<Value> root) - : json_(std::move(json)) { + DictionaryHiddenRootValue(std::string* json, Value* root) : json_(json) { DCHECK(root->IsType(Value::TYPE_DICTIONARY)); - DictionaryValue::Swap(static_cast<DictionaryValue*>(root.get())); + DictionaryValue::Swap(static_cast<DictionaryValue*>(root)); } void Swap(DictionaryValue* other) override { @@ -47,7 +43,7 @@ class DictionaryHiddenRootValue : public DictionaryValue { // First deep copy to convert JSONStringValue to std::string and swap that // copy with |other|, which contains the new contents of |this|. - std::unique_ptr<DictionaryValue> copy(CreateDeepCopy()); + scoped_ptr<DictionaryValue> copy(DeepCopy()); copy->Swap(other); // Then erase the contents of the current dictionary and swap in the @@ -61,7 +57,7 @@ class DictionaryHiddenRootValue : public DictionaryValue { // the method below. bool RemoveWithoutPathExpansion(const std::string& key, - std::unique_ptr<Value>* out) override { + scoped_ptr<Value>* out) override { // If the caller won't take ownership of the removed value, just call up. if (!out) return DictionaryValue::RemoveWithoutPathExpansion(key, out); @@ -70,28 +66,26 @@ class DictionaryHiddenRootValue : public DictionaryValue { // Otherwise, remove the value while its still "owned" by this and copy it // to convert any JSONStringValues to std::string. - std::unique_ptr<Value> out_owned; + scoped_ptr<Value> out_owned; if (!DictionaryValue::RemoveWithoutPathExpansion(key, &out_owned)) return false; - *out = out_owned->CreateDeepCopy(); + out->reset(out_owned->DeepCopy()); return true; } private: - std::unique_ptr<std::string> json_; + scoped_ptr<std::string> json_; DISALLOW_COPY_AND_ASSIGN(DictionaryHiddenRootValue); }; class ListHiddenRootValue : public ListValue { public: - ListHiddenRootValue(std::unique_ptr<std::string> json, - std::unique_ptr<Value> root) - : json_(std::move(json)) { + ListHiddenRootValue(std::string* json, Value* root) : json_(json) { DCHECK(root->IsType(Value::TYPE_LIST)); - ListValue::Swap(static_cast<ListValue*>(root.get())); + ListValue::Swap(static_cast<ListValue*>(root)); } void Swap(ListValue* other) override { @@ -99,7 +93,7 @@ class ListHiddenRootValue : public ListValue { // First deep copy to convert JSONStringValue to std::string and swap that // copy with |other|, which contains the new contents of |this|. - std::unique_ptr<ListValue> copy(CreateDeepCopy()); + scoped_ptr<ListValue> copy(DeepCopy()); copy->Swap(other); // Then erase the contents of the current list and swap in the new contents, @@ -109,7 +103,7 @@ class ListHiddenRootValue : public ListValue { ListValue::Swap(copy.get()); } - bool Remove(size_t index, std::unique_ptr<Value>* out) override { + bool Remove(size_t index, scoped_ptr<Value>* out) override { // If the caller won't take ownership of the removed value, just call up. if (!out) return ListValue::Remove(index, out); @@ -118,17 +112,17 @@ class ListHiddenRootValue : public ListValue { // Otherwise, remove the value while its still "owned" by this and copy it // to convert any JSONStringValues to std::string. - std::unique_ptr<Value> out_owned; + scoped_ptr<Value> out_owned; if (!ListValue::Remove(index, &out_owned)) return false; - *out = out_owned->CreateDeepCopy(); + out->reset(out_owned->DeepCopy()); return true; } private: - std::unique_ptr<std::string> json_; + scoped_ptr<std::string> json_; DISALLOW_COPY_AND_ASSIGN(ListHiddenRootValue); }; @@ -138,8 +132,10 @@ class ListHiddenRootValue : public ListValue { // otherwise the referenced string will not be guaranteed to outlive it. class JSONStringValue : public Value { public: - explicit JSONStringValue(StringPiece piece) - : Value(TYPE_STRING), string_piece_(piece) {} + explicit JSONStringValue(const StringPiece& piece) + : Value(TYPE_STRING), + string_piece_(piece) { + } // Overridden from Value: bool GetAsString(std::string* out_value) const override { @@ -202,13 +198,13 @@ JSONParser::JSONParser(int options) JSONParser::~JSONParser() { } -std::unique_ptr<Value> JSONParser::Parse(StringPiece input) { - std::unique_ptr<std::string> input_copy; +Value* JSONParser::Parse(const StringPiece& input) { + scoped_ptr<std::string> input_copy; // If the children of a JSON root can be detached, then hidden roots cannot // be used, so do not bother copying the input because StringPiece will not // be used anywhere. if (!(options_ & JSON_DETACHABLE_CHILDREN)) { - input_copy = WrapUnique(new std::string(input.as_string())); + input_copy.reset(new std::string(input.as_string())); start_pos_ = input_copy->data(); } else { start_pos_ = input.data(); @@ -234,15 +230,15 @@ std::unique_ptr<Value> JSONParser::Parse(StringPiece input) { } // Parse the first and any nested tokens. - std::unique_ptr<Value> root(ParseNextToken()); - if (!root) - return nullptr; + scoped_ptr<Value> root(ParseNextToken()); + if (!root.get()) + return NULL; // Make sure the input stream is at an end. if (GetNextToken() != T_END_OF_INPUT) { if (!CanConsume(1) || (NextChar() && GetNextToken() != T_END_OF_INPUT)) { ReportError(JSONReader::JSON_UNEXPECTED_DATA_AFTER_ROOT, 1); - return nullptr; + return NULL; } } @@ -250,21 +246,19 @@ std::unique_ptr<Value> JSONParser::Parse(StringPiece input) { // hidden root. if (!(options_ & JSON_DETACHABLE_CHILDREN)) { if (root->IsType(Value::TYPE_DICTIONARY)) { - return WrapUnique(new DictionaryHiddenRootValue(std::move(input_copy), - std::move(root))); + return new DictionaryHiddenRootValue(input_copy.release(), root.get()); } else if (root->IsType(Value::TYPE_LIST)) { - return WrapUnique( - new ListHiddenRootValue(std::move(input_copy), std::move(root))); + return new ListHiddenRootValue(input_copy.release(), root.get()); } else if (root->IsType(Value::TYPE_STRING)) { // A string type could be a JSONStringValue, but because there's no // corresponding HiddenRootValue, the memory will be lost. Deep copy to // preserve it. - return root->CreateDeepCopy(); + return root->DeepCopy(); } } // All other values can be returned directly. - return root; + return root.release(); } JSONReader::JsonParseError JSONParser::error_code() const { @@ -310,7 +304,7 @@ JSONParser::StringBuilder::~StringBuilder() { void JSONParser::StringBuilder::Append(const char& c) { DCHECK_GE(c, 0); - DCHECK_LT(static_cast<unsigned char>(c), 128); + DCHECK_LT(c, 128); if (string_) string_->push_back(c); @@ -500,7 +494,7 @@ Value* JSONParser::ConsumeDictionary() { return NULL; } - std::unique_ptr<DictionaryValue> dict(new DictionaryValue); + scoped_ptr<DictionaryValue> dict(new DictionaryValue); NextChar(); Token token = GetNextToken(); @@ -564,7 +558,7 @@ Value* JSONParser::ConsumeList() { return NULL; } - std::unique_ptr<ListValue> list(new ListValue); + scoped_ptr<ListValue> list(new ListValue); NextChar(); Token token = GetNextToken(); diff --git a/third_party/chromium/base/json/json_parser.h b/third_party/chromium/base/json/json_parser.h index 5bdec58..fc04594 100644 --- a/third_party/chromium/base/json/json_parser.h +++ b/third_party/chromium/base/json/json_parser.h @@ -8,7 +8,6 @@ #include <stddef.h> #include <stdint.h> -#include <memory> #include <string> #include "base/base_export.h" @@ -51,7 +50,7 @@ class BASE_EXPORT JSONParser { // Parses the input string according to the set options and returns the // result as a Value owned by the caller. - std::unique_ptr<Value> Parse(StringPiece input); + Value* Parse(const StringPiece& input); // Returns the error code. JSONReader::JsonParseError error_code() const; @@ -134,7 +133,7 @@ class BASE_EXPORT JSONParser { size_t length_; // The copied string representation. NULL until Convert() is called. - // Strong. std::unique_ptr<T> has too much of an overhead here. + // Strong. scoped_ptr<T> has too much of an overhead here. std::string* string_; }; diff --git a/third_party/chromium/base/json/json_parser_unittest.cc b/third_party/chromium/base/json/json_parser_unittest.cc index a6c360d..956e277 100644 --- a/third_party/chromium/base/json/json_parser_unittest.cc +++ b/third_party/chromium/base/json/json_parser_unittest.cc @@ -6,11 +6,10 @@ #include <stddef.h> -#include <memory> - #include <gtest/gtest.h> #include "base/json/json_reader.h" +#include "base/memory/scoped_ptr.h" #include "base/values.h" namespace base { @@ -36,7 +35,7 @@ class JSONParserTest : public testing::Test { TEST_F(JSONParserTest, NextChar) { std::string input("Hello world"); - std::unique_ptr<JSONParser> parser(NewTestParser(input)); + scoped_ptr<JSONParser> parser(NewTestParser(input)); EXPECT_EQ('H', *parser->pos_); for (size_t i = 1; i < input.length(); ++i) { @@ -47,8 +46,8 @@ TEST_F(JSONParserTest, NextChar) { TEST_F(JSONParserTest, ConsumeString) { std::string input("\"test\",|"); - std::unique_ptr<JSONParser> parser(NewTestParser(input)); - std::unique_ptr<Value> value(parser->ConsumeString()); + scoped_ptr<JSONParser> parser(NewTestParser(input)); + scoped_ptr<Value> value(parser->ConsumeString()); EXPECT_EQ('"', *parser->pos_); TestLastThree(parser.get()); @@ -61,8 +60,8 @@ TEST_F(JSONParserTest, ConsumeString) { TEST_F(JSONParserTest, ConsumeList) { std::string input("[true, false],|"); - std::unique_ptr<JSONParser> parser(NewTestParser(input)); - std::unique_ptr<Value> value(parser->ConsumeList()); + scoped_ptr<JSONParser> parser(NewTestParser(input)); + scoped_ptr<Value> value(parser->ConsumeList()); EXPECT_EQ(']', *parser->pos_); TestLastThree(parser.get()); @@ -75,8 +74,8 @@ TEST_F(JSONParserTest, ConsumeList) { TEST_F(JSONParserTest, ConsumeDictionary) { std::string input("{\"abc\":\"def\"},|"); - std::unique_ptr<JSONParser> parser(NewTestParser(input)); - std::unique_ptr<Value> value(parser->ConsumeDictionary()); + scoped_ptr<JSONParser> parser(NewTestParser(input)); + scoped_ptr<Value> value(parser->ConsumeDictionary()); EXPECT_EQ('}', *parser->pos_); TestLastThree(parser.get()); @@ -92,8 +91,8 @@ TEST_F(JSONParserTest, ConsumeDictionary) { TEST_F(JSONParserTest, ConsumeLiterals) { // Literal |true|. std::string input("true,|"); - std::unique_ptr<JSONParser> parser(NewTestParser(input)); - std::unique_ptr<Value> value(parser->ConsumeLiteral()); + scoped_ptr<JSONParser> parser(NewTestParser(input)); + scoped_ptr<Value> value(parser->ConsumeLiteral()); EXPECT_EQ('e', *parser->pos_); TestLastThree(parser.get()); @@ -130,8 +129,8 @@ TEST_F(JSONParserTest, ConsumeLiterals) { TEST_F(JSONParserTest, ConsumeNumbers) { // Integer. std::string input("1234,|"); - std::unique_ptr<JSONParser> parser(NewTestParser(input)); - std::unique_ptr<Value> value(parser->ConsumeNumber()); + scoped_ptr<JSONParser> parser(NewTestParser(input)); + scoped_ptr<Value> value(parser->ConsumeNumber()); EXPECT_EQ('4', *parser->pos_); TestLastThree(parser.get()); @@ -207,7 +206,7 @@ TEST_F(JSONParserTest, ErrorMessages) { // Error strings should not be modified in case of success. std::string error_message; int error_code = 0; - std::unique_ptr<Value> root = JSONReader::ReadAndReturnError( + scoped_ptr<Value> root = JSONReader::ReadAndReturnError( "[42]", JSON_PARSE_RFC, &error_code, &error_message); EXPECT_TRUE(error_message.empty()); EXPECT_EQ(0, error_code); @@ -311,7 +310,7 @@ TEST_F(JSONParserTest, Decode4ByteUtf8Char) { "[\"😇\",[],[],[],{\"google:suggesttype\":[]}]"; std::string error_message; int error_code = 0; - std::unique_ptr<Value> root = JSONReader::ReadAndReturnError( + scoped_ptr<Value> root = JSONReader::ReadAndReturnError( kUtf8Data, JSON_PARSE_RFC, &error_code, &error_message); EXPECT_TRUE(root.get()) << error_message; } diff --git a/third_party/chromium/base/json/json_reader.cc b/third_party/chromium/base/json/json_reader.cc index 4ff7496..3ab5f75 100644 --- a/third_party/chromium/base/json/json_reader.cc +++ b/third_party/chromium/base/json/json_reader.cc @@ -43,28 +43,27 @@ JSONReader::~JSONReader() { } // static -std::unique_ptr<Value> JSONReader::Read(StringPiece json) { +scoped_ptr<Value> JSONReader::Read(const StringPiece& json) { internal::JSONParser parser(JSON_PARSE_RFC); - return parser.Parse(json); + return make_scoped_ptr(parser.Parse(json)); } // static -std::unique_ptr<Value> JSONReader::Read(StringPiece json, int options) { +scoped_ptr<Value> JSONReader::Read(const StringPiece& json, int options) { internal::JSONParser parser(options); - return parser.Parse(json); + return make_scoped_ptr(parser.Parse(json)); } // static -std::unique_ptr<Value> JSONReader::ReadAndReturnError( - const StringPiece& json, - int options, - int* error_code_out, - std::string* error_msg_out, - int* error_line_out, - int* error_column_out) { +scoped_ptr<Value> JSONReader::ReadAndReturnError(const StringPiece& json, + int options, + int* error_code_out, + std::string* error_msg_out, + int* error_line_out, + int* error_column_out) { internal::JSONParser parser(options); - std::unique_ptr<Value> root(parser.Parse(json)); + scoped_ptr<Value> root(parser.Parse(json)); if (!root) { if (error_code_out) *error_code_out = parser.error_code(); @@ -106,8 +105,8 @@ std::string JSONReader::ErrorCodeToString(JsonParseError error_code) { } } -std::unique_ptr<Value> JSONReader::ReadToValue(StringPiece json) { - return parser_->Parse(json); +scoped_ptr<Value> JSONReader::ReadToValue(const std::string& json) { + return make_scoped_ptr(parser_->Parse(json)); } JSONReader::JsonParseError JSONReader::error_code() const { diff --git a/third_party/chromium/base/json/json_reader.h b/third_party/chromium/base/json/json_reader.h index f647724..c6bcb52 100644 --- a/third_party/chromium/base/json/json_reader.h +++ b/third_party/chromium/base/json/json_reader.h @@ -28,10 +28,10 @@ #ifndef BASE_JSON_JSON_READER_H_ #define BASE_JSON_JSON_READER_H_ -#include <memory> #include <string> #include "base/base_export.h" +#include "base/memory/scoped_ptr.h" #include "base/strings/string_piece.h" namespace base { @@ -93,31 +93,30 @@ class BASE_EXPORT JSONReader { // Reads and parses |json|, returning a Value. The caller owns the returned // instance. If |json| is not a properly formed JSON string, returns NULL. - static std::unique_ptr<Value> Read(StringPiece json); + static scoped_ptr<Value> Read(const StringPiece& json); // Reads and parses |json|, returning a Value owned by the caller. The // parser respects the given |options|. If the input is not properly formed, // returns NULL. - static std::unique_ptr<Value> Read(StringPiece json, int options); + static scoped_ptr<Value> Read(const StringPiece& json, int options); // Reads and parses |json| like Read(). |error_code_out| and |error_msg_out| // are optional. If specified and NULL is returned, they will be populated // an error code and a formatted error message (including error location if // appropriate). Otherwise, they will be unmodified. - static std::unique_ptr<Value> ReadAndReturnError( - const StringPiece& json, - int options, // JSONParserOptions - int* error_code_out, - std::string* error_msg_out, - int* error_line_out = nullptr, - int* error_column_out = nullptr); + static scoped_ptr<Value> ReadAndReturnError(const StringPiece& json, + int options, // JSONParserOptions + int* error_code_out, + std::string* error_msg_out, + int* error_line_out = nullptr, + int* error_column_out = nullptr); // Converts a JSON parse error code into a human readable message. // Returns an empty string if error_code is JSON_NO_ERROR. static std::string ErrorCodeToString(JsonParseError error_code); // Parses an input string into a Value that is owned by the caller. - std::unique_ptr<Value> ReadToValue(StringPiece json); + scoped_ptr<Value> ReadToValue(const std::string& json); // Returns the error code if the last call to ReadToValue() failed. // Returns JSON_NO_ERROR otherwise. @@ -128,7 +127,7 @@ class BASE_EXPORT JSONReader { std::string GetErrorMessage() const; private: - std::unique_ptr<internal::JSONParser> parser_; + scoped_ptr<internal::JSONParser> parser_; }; } // namespace base diff --git a/third_party/chromium/base/json/json_reader_unittest.cc b/third_party/chromium/base/json/json_reader_unittest.cc index b1ad46e..2bfd10e 100644 --- a/third_party/chromium/base/json/json_reader_unittest.cc +++ b/third_party/chromium/base/json/json_reader_unittest.cc @@ -7,10 +7,10 @@ #include <stddef.h> #include <gtest/gtest.h> -#include <memory> #include "base/logging.h" #include "base/macros.h" +#include "base/memory/scoped_ptr.h" #include "base/strings/string_piece.h" #include "base/strings/utf_string_conversion_utils.h" #include "base/values.h" @@ -20,7 +20,7 @@ namespace base { TEST(JSONReaderTest, Reading) { // some whitespace checking - std::unique_ptr<Value> root = JSONReader().ReadToValue(" null "); + scoped_ptr<Value> root = JSONReader().ReadToValue(" null "); ASSERT_TRUE(root.get()); EXPECT_TRUE(root->IsType(Value::TYPE_NULL)); @@ -249,7 +249,7 @@ TEST(JSONReaderTest, Reading) { EXPECT_EQ(3U, list->GetSize()); // Test with trailing comma. Should be parsed the same as above. - std::unique_ptr<Value> root2 = + scoped_ptr<Value> root2 = JSONReader::Read("[true, false, null, ]", JSON_ALLOW_TRAILING_COMMAS); EXPECT_TRUE(root->Equals(root2.get())); @@ -543,15 +543,15 @@ TEST(JSONReaderTest, Reading) { // Tests that the root of a JSON object can be deleted safely while its // children outlive it. TEST(JSONReaderTest, StringOptimizations) { - std::unique_ptr<Value> dict_literal_0; - std::unique_ptr<Value> dict_literal_1; - std::unique_ptr<Value> dict_string_0; - std::unique_ptr<Value> dict_string_1; - std::unique_ptr<Value> list_value_0; - std::unique_ptr<Value> list_value_1; + scoped_ptr<Value> dict_literal_0; + scoped_ptr<Value> dict_literal_1; + scoped_ptr<Value> dict_string_0; + scoped_ptr<Value> dict_string_1; + scoped_ptr<Value> list_value_0; + scoped_ptr<Value> list_value_1; { - std::unique_ptr<Value> root = JSONReader::Read( + scoped_ptr<Value> root = JSONReader::Read( "{" " \"test\": {" " \"foo\": true," diff --git a/third_party/chromium/base/json/json_writer_unittest.cc b/third_party/chromium/base/json/json_writer_unittest.cc index 7aaa78b..ca99f4d 100644 --- a/third_party/chromium/base/json/json_writer_unittest.cc +++ b/third_party/chromium/base/json/json_writer_unittest.cc @@ -6,7 +6,6 @@ #include <gtest/gtest.h> -#include "base/memory/ptr_util.h" #include "base/values.h" #include "build/build_config.h" @@ -58,11 +57,11 @@ TEST(JSONWriterTest, NestedTypes) { // Writer unittests like empty list/dict nesting, // list list nesting, etc. DictionaryValue root_dict; - std::unique_ptr<ListValue> list(new ListValue()); - std::unique_ptr<DictionaryValue> inner_dict(new DictionaryValue()); + scoped_ptr<ListValue> list(new ListValue()); + scoped_ptr<DictionaryValue> inner_dict(new DictionaryValue()); inner_dict->SetInteger("inner int", 10); list->Append(std::move(inner_dict)); - list->Append(WrapUnique(new ListValue())); + list->Append(make_scoped_ptr(new ListValue())); list->AppendBoolean(true); root_dict.Set("list", std::move(list)); @@ -94,7 +93,7 @@ TEST(JSONWriterTest, KeysWithPeriods) { DictionaryValue period_dict; period_dict.SetIntegerWithoutPathExpansion("a.b", 3); period_dict.SetIntegerWithoutPathExpansion("c", 2); - std::unique_ptr<DictionaryValue> period_dict2(new DictionaryValue()); + scoped_ptr<DictionaryValue> period_dict2(new DictionaryValue()); period_dict2->SetIntegerWithoutPathExpansion("g.h.i.j", 1); period_dict.SetWithoutPathExpansion("d.e.f", std::move(period_dict2)); EXPECT_TRUE(JSONWriter::Write(period_dict, &output_js)); @@ -112,7 +111,7 @@ TEST(JSONWriterTest, BinaryValues) { // Binary values should return errors unless suppressed via the // OPTIONS_OMIT_BINARY_VALUES flag. - std::unique_ptr<Value> root(BinaryValue::CreateWithCopiedBuffer("asdf", 4)); + scoped_ptr<Value> root(BinaryValue::CreateWithCopiedBuffer("asdf", 4)); EXPECT_FALSE(JSONWriter::Write(*root, &output_js)); EXPECT_TRUE(JSONWriter::WriteWithOptions( *root, JSONWriter::OPTIONS_OMIT_BINARY_VALUES, &output_js)); @@ -120,9 +119,9 @@ TEST(JSONWriterTest, BinaryValues) { ListValue binary_list; binary_list.Append(BinaryValue::CreateWithCopiedBuffer("asdf", 4)); - binary_list.Append(WrapUnique(new FundamentalValue(5))); + binary_list.Append(make_scoped_ptr(new FundamentalValue(5))); binary_list.Append(BinaryValue::CreateWithCopiedBuffer("asdf", 4)); - binary_list.Append(WrapUnique(new FundamentalValue(2))); + binary_list.Append(make_scoped_ptr(new FundamentalValue(2))); binary_list.Append(BinaryValue::CreateWithCopiedBuffer("asdf", 4)); EXPECT_FALSE(JSONWriter::Write(binary_list, &output_js)); EXPECT_TRUE(JSONWriter::WriteWithOptions( @@ -131,13 +130,13 @@ TEST(JSONWriterTest, BinaryValues) { DictionaryValue binary_dict; binary_dict.Set( - "a", WrapUnique(BinaryValue::CreateWithCopiedBuffer("asdf", 4))); + "a", make_scoped_ptr(BinaryValue::CreateWithCopiedBuffer("asdf", 4))); binary_dict.SetInteger("b", 5); binary_dict.Set( - "c", WrapUnique(BinaryValue::CreateWithCopiedBuffer("asdf", 4))); + "c", make_scoped_ptr(BinaryValue::CreateWithCopiedBuffer("asdf", 4))); binary_dict.SetInteger("d", 2); binary_dict.Set( - "e", WrapUnique(BinaryValue::CreateWithCopiedBuffer("asdf", 4))); + "e", make_scoped_ptr(BinaryValue::CreateWithCopiedBuffer("asdf", 4))); EXPECT_FALSE(JSONWriter::Write(binary_dict, &output_js)); EXPECT_TRUE(JSONWriter::WriteWithOptions( binary_dict, JSONWriter::OPTIONS_OMIT_BINARY_VALUES, &output_js)); diff --git a/third_party/chromium/base/memory/ptr_util.h b/third_party/chromium/base/memory/ptr_util.h deleted file mode 100644 index 8747ac9..0000000 --- a/third_party/chromium/base/memory/ptr_util.h +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_MEMORY_PTR_UTIL_H_ -#define BASE_MEMORY_PTR_UTIL_H_ - -#include <memory> -#include <utility> - -namespace base { - -// Helper to transfer ownership of a raw pointer to a std::unique_ptr<T>. -// Note that std::unique_ptr<T> has very different semantics from -// std::unique_ptr<T[]>: do not use this helper for array allocations. -template <typename T> -std::unique_ptr<T> WrapUnique(T* ptr) { - return std::unique_ptr<T>(ptr); -} - -namespace internal { - -template <typename T> -struct MakeUniqueResult { - using Scalar = std::unique_ptr<T>; -}; - -template <typename T> -struct MakeUniqueResult<T[]> { - using Array = std::unique_ptr<T[]>; -}; - -template <typename T, size_t N> -struct MakeUniqueResult<T[N]> { - using Invalid = void; -}; - -} // namespace internal - -// Helper to construct an object wrapped in a std::unique_ptr. This is an -// implementation of C++14's std::make_unique that can be used in Chrome. -// -// MakeUnique<T>(args) should be preferred over WrapUnique(new T(args)): bare -// calls to `new` should be treated with scrutiny. -// -// Usage: -// // ptr is a std::unique_ptr<std::string> -// auto ptr = MakeUnique<std::string>("hello world!"); -// -// // arr is a std::unique_ptr<int[]> -// auto arr = MakeUnique<int[]>(5); - -// Overload for non-array types. Arguments are forwarded to T's constructor. -template <typename T, typename... Args> -typename internal::MakeUniqueResult<T>::Scalar MakeUnique(Args&&... args) { - return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); -} - -// Overload for array types of unknown bound, e.g. T[]. The array is allocated -// with `new T[n]()` and value-initialized: note that this is distinct from -// `new T[n]`, which default-initializes. -template <typename T> -typename internal::MakeUniqueResult<T>::Array MakeUnique(size_t size) { - return std::unique_ptr<T>(new typename std::remove_extent<T>::type[size]()); -} - -// Overload to reject array types of known bound, e.g. T[n]. -template <typename T, typename... Args> -typename internal::MakeUniqueResult<T>::Invalid MakeUnique(Args&&... args) = - delete; - -} // namespace base - -#endif // BASE_MEMORY_PTR_UTIL_H_ diff --git a/third_party/chromium/base/memory/scoped_ptr.h b/third_party/chromium/base/memory/scoped_ptr.h new file mode 100644 index 0000000..2d2c0ec --- /dev/null +++ b/third_party/chromium/base/memory/scoped_ptr.h @@ -0,0 +1,135 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// Scopers help you manage ownership of a pointer, helping you easily manage a +// pointer within a scope, and automatically destroying the pointer at the end +// of a scope. There are two main classes you will use, which correspond to the +// operators new/delete and new[]/delete[]. +// +// Example usage (scoped_ptr<T>): +// { +// scoped_ptr<Foo> foo(new Foo("wee")); +// } // foo goes out of scope, releasing the pointer with it. +// +// { +// scoped_ptr<Foo> foo; // No pointer managed. +// foo.reset(new Foo("wee")); // Now a pointer is managed. +// foo.reset(new Foo("wee2")); // Foo("wee") was destroyed. +// foo.reset(new Foo("wee3")); // Foo("wee2") was destroyed. +// foo->Method(); // Foo::Method() called. +// foo.get()->Method(); // Foo::Method() called. +// SomeFunc(foo.release()); // SomeFunc takes ownership, foo no longer +// // manages a pointer. +// foo.reset(new Foo("wee4")); // foo manages a pointer again. +// foo.reset(); // Foo("wee4") destroyed, foo no longer +// // manages a pointer. +// } // foo wasn't managing a pointer, so nothing was destroyed. +// +// Example usage (scoped_ptr<T[]>): +// { +// scoped_ptr<Foo[]> foo(new Foo[100]); +// foo.get()->Method(); // Foo::Method on the 0th element. +// foo[10].Method(); // Foo::Method on the 10th element. +// } +// +// Scopers are testable as booleans: +// { +// scoped_ptr<Foo> foo; +// if (!foo) +// foo.reset(new Foo()); +// if (foo) +// LOG(INFO) << "This code is reached." +// } +// +// These scopers also implement part of the functionality of C++11 unique_ptr +// in that they are "movable but not copyable." You can use the scopers in +// the parameter and return types of functions to signify ownership transfer +// in to and out of a function. When calling a function that has a scoper +// as the argument type, it must be called with an rvalue of a scoper, which +// can be created by using std::move(), or the result of another function that +// generates a temporary; passing by copy will NOT work. Here is an example +// using scoped_ptr: +// +// void TakesOwnership(scoped_ptr<Foo> arg) { +// // Do something with arg. +// } +// scoped_ptr<Foo> CreateFoo() { +// // No need for calling std::move() for returning a move-only value, or +// // when you already have an rvalue as we do here. +// return scoped_ptr<Foo>(new Foo("new")); +// } +// scoped_ptr<Foo> PassThru(scoped_ptr<Foo> arg) { +// return arg; +// } +// +// { +// scoped_ptr<Foo> ptr(new Foo("yay")); // ptr manages Foo("yay"). +// TakesOwnership(std::move(ptr)); // ptr no longer owns Foo("yay"). +// scoped_ptr<Foo> ptr2 = CreateFoo(); // ptr2 owns the return Foo. +// scoped_ptr<Foo> ptr3 = // ptr3 now owns what was in ptr2. +// PassThru(std::move(ptr2)); // ptr2 is correspondingly nullptr. +// } +// +// Notice that if you do not call std::move() when returning from PassThru(), or +// when invoking TakesOwnership(), the code will not compile because scopers +// are not copyable; they only implement move semantics which require calling +// the std::move() function to signify a destructive transfer of state. +// CreateFoo() is different though because we are constructing a temporary on +// the return line and thus can avoid needing to call std::move(). +// +// The conversion move-constructor properly handles upcast in initialization, +// i.e. you can use a scoped_ptr<Child> to initialize a scoped_ptr<Parent>: +// +// scoped_ptr<Foo> foo(new Foo()); +// scoped_ptr<FooParent> parent(std::move(foo)); + +#ifndef BASE_MEMORY_SCOPED_PTR_H_ +#define BASE_MEMORY_SCOPED_PTR_H_ + +// This is an implementation designed to match the anticipated future TR2 +// implementation of the scoped_ptr class. + +// TODO(dcheng): Clean up these headers, but there are likely lots of existing +// IWYU violations. +#include <stddef.h> +#include <stdlib.h> + +#include <iosfwd> +#include <memory> +#include <type_traits> +#include <utility> + +#include "base/compiler_specific.h" +#include "base/logging.h" +#include "base/macros.h" +#include "base/move.h" +#include "build/build_config.h" + +namespace base { + +// Function object which invokes 'free' on its parameter, which must be +// a pointer. Can be used to store malloc-allocated pointers in scoped_ptr: +// +// scoped_ptr<int, base::FreeDeleter> foo_ptr( +// static_cast<int*>(malloc(sizeof(int)))); +struct FreeDeleter { + inline void operator()(void* ptr) const { + free(ptr); + } +}; + +} // namespace base + +template <typename T, typename D = std::default_delete<T>> +using scoped_ptr = std::unique_ptr<T, D>; + +// A function to convert T* into scoped_ptr<T> +// Doing e.g. make_scoped_ptr(new FooBarBaz<type>(arg)) is a shorter notation +// for scoped_ptr<FooBarBaz<type> >(new FooBarBaz<type>(arg)) +template <typename T> +scoped_ptr<T> make_scoped_ptr(T* ptr) { + return scoped_ptr<T>(ptr); +} + +#endif // BASE_MEMORY_SCOPED_PTR_H_ diff --git a/third_party/chromium/base/memory/weak_ptr.h b/third_party/chromium/base/memory/weak_ptr.h index 2efb024..601c379 100644 --- a/third_party/chromium/base/memory/weak_ptr.h +++ b/third_party/chromium/base/memory/weak_ptr.h @@ -3,7 +3,7 @@ // found in the LICENSE file. // Weak pointers are pointers to an object that do not affect its lifetime, -// and which may be invalidated (i.e. reset to nullptr) by the object, or its +// and which may be invalidated (i.e. reset to NULL) by the object, or its // owner, at any time, most commonly when the object is about to be deleted. // Weak pointers are useful when an object needs to be accessed safely by one @@ -70,7 +70,6 @@ #ifndef BASE_MEMORY_WEAK_PTR_H_ #define BASE_MEMORY_WEAK_PTR_H_ -#include <cstddef> #include <type_traits> #include "base/base_export.h" @@ -198,9 +197,8 @@ template <typename T> class WeakPtrFactory; template <typename T> class WeakPtr : public internal::WeakPtrBase { public: - WeakPtr() : ptr_(nullptr) {} - - WeakPtr(std::nullptr_t) : ptr_(nullptr) {} + WeakPtr() : ptr_(NULL) { + } // Allow conversion from U to T provided U "is a" T. Note that this // is separate from the (implicit) copy constructor. @@ -208,20 +206,20 @@ class WeakPtr : public internal::WeakPtrBase { WeakPtr(const WeakPtr<U>& other) : WeakPtrBase(other), ptr_(other.ptr_) { } - T* get() const { return ref_.is_valid() ? ptr_ : nullptr; } + T* get() const { return ref_.is_valid() ? ptr_ : NULL; } T& operator*() const { - DCHECK(get() != nullptr); + DCHECK(get() != NULL); return *get(); } T* operator->() const { - DCHECK(get() != nullptr); + DCHECK(get() != NULL); return get(); } void reset() { ref_ = internal::WeakReference(); - ptr_ = nullptr; + ptr_ = NULL; } // Implement "Safe Bool Idiom" @@ -246,7 +244,7 @@ class WeakPtr : public internal::WeakPtrBase { typedef T* WeakPtr::*Testable; public: - operator Testable() const { return get() ? &WeakPtr::ptr_ : nullptr; } + operator Testable() const { return get() ? &WeakPtr::ptr_ : NULL; } private: // Explicitly declare comparison operators as required by the "Safe Bool @@ -265,7 +263,7 @@ class WeakPtr : public internal::WeakPtrBase { } // This pointer is only valid when ref_.is_valid() is true. Otherwise, its - // value is undefined (as opposed to nullptr). + // value is undefined (as opposed to NULL). T* ptr_; }; @@ -280,7 +278,9 @@ class WeakPtrFactory { explicit WeakPtrFactory(T* ptr) : ptr_(ptr) { } - ~WeakPtrFactory() { ptr_ = nullptr; } + ~WeakPtrFactory() { + ptr_ = NULL; + } WeakPtr<T> GetWeakPtr() { DCHECK(ptr_); diff --git a/third_party/chromium/base/memory/weak_ptr_unittest.cc b/third_party/chromium/base/memory/weak_ptr_unittest.cc index 982becd..fdbb280 100644 --- a/third_party/chromium/base/memory/weak_ptr_unittest.cc +++ b/third_party/chromium/base/memory/weak_ptr_unittest.cc @@ -4,21 +4,17 @@ #include "base/memory/weak_ptr.h" -#include <memory> #include <string> #include <gtest/gtest.h> #include "base/bind.h" #include "base/location.h" +#include "base/memory/scoped_ptr.h" namespace base { namespace { -WeakPtr<int> PassThru(WeakPtr<int> ptr) { - return ptr; -} - struct Base { std::string member; }; @@ -56,13 +52,13 @@ TEST(WeakPtrFactoryTest, Comparison) { TEST(WeakPtrFactoryTest, OutOfScope) { WeakPtr<int> ptr; - EXPECT_EQ(nullptr, ptr.get()); + EXPECT_EQ(NULL, ptr.get()); { int data; WeakPtrFactory<int> factory(&data); ptr = factory.GetWeakPtr(); } - EXPECT_EQ(nullptr, ptr.get()); + EXPECT_EQ(NULL, ptr.get()); } TEST(WeakPtrFactoryTest, Multiple) { @@ -75,8 +71,8 @@ TEST(WeakPtrFactoryTest, Multiple) { EXPECT_EQ(&data, a.get()); EXPECT_EQ(&data, b.get()); } - EXPECT_EQ(nullptr, a.get()); - EXPECT_EQ(nullptr, b.get()); + EXPECT_EQ(NULL, a.get()); + EXPECT_EQ(NULL, b.get()); } TEST(WeakPtrFactoryTest, MultipleStaged) { @@ -88,9 +84,9 @@ TEST(WeakPtrFactoryTest, MultipleStaged) { { WeakPtr<int> b = factory.GetWeakPtr(); } - EXPECT_NE(nullptr, a.get()); + EXPECT_TRUE(NULL != a.get()); } - EXPECT_EQ(nullptr, a.get()); + EXPECT_EQ(NULL, a.get()); } TEST(WeakPtrFactoryTest, Dereference) { @@ -111,11 +107,6 @@ TEST(WeakPtrFactoryTest, UpCast) { EXPECT_EQ(ptr.get(), &data); } -TEST(WeakPtrTest, ConstructFromNullptr) { - WeakPtr<int> ptr = PassThru(nullptr); - EXPECT_EQ(nullptr, ptr.get()); -} - TEST(WeakPtrTest, SupportsWeakPtr) { Target target; WeakPtr<Target> ptr = target.AsWeakPtr(); @@ -166,7 +157,7 @@ TEST(WeakPtrTest, InvalidateWeakPtrs) { EXPECT_EQ(&data, ptr.get()); EXPECT_TRUE(factory.HasWeakPtrs()); factory.InvalidateWeakPtrs(); - EXPECT_EQ(nullptr, ptr.get()); + EXPECT_EQ(NULL, ptr.get()); EXPECT_FALSE(factory.HasWeakPtrs()); // Test that the factory can create new weak pointers after a @@ -176,7 +167,7 @@ TEST(WeakPtrTest, InvalidateWeakPtrs) { EXPECT_EQ(&data, ptr2.get()); EXPECT_TRUE(factory.HasWeakPtrs()); factory.InvalidateWeakPtrs(); - EXPECT_EQ(nullptr, ptr2.get()); + EXPECT_EQ(NULL, ptr2.get()); EXPECT_FALSE(factory.HasWeakPtrs()); } diff --git a/third_party/chromium/base/rand_util_unittest.cc b/third_party/chromium/base/rand_util_unittest.cc index da4023f..fc0233d 100644 --- a/third_party/chromium/base/rand_util_unittest.cc +++ b/third_party/chromium/base/rand_util_unittest.cc @@ -9,11 +9,11 @@ #include <algorithm> #include <limits> -#include <memory> #include <gtest/gtest.h> #include "base/logging.h" +#include "base/memory/scoped_ptr.h" #include "base/time/time.h" namespace { diff --git a/third_party/chromium/base/values.cc b/third_party/chromium/base/values.cc index 4af9919..29f0301 100644 --- a/third_party/chromium/base/values.cc +++ b/third_party/chromium/base/values.cc @@ -13,7 +13,6 @@ #include "base/json/json_writer.h" #include "base/logging.h" -#include "base/memory/ptr_util.h" #include "base/move.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversion_utils.h" @@ -22,15 +21,15 @@ namespace base { namespace { -std::unique_ptr<Value> CopyWithoutEmptyChildren(const Value& node); +scoped_ptr<Value> CopyWithoutEmptyChildren(const Value& node); // Make a deep copy of |node|, but don't include empty lists or dictionaries // in the copy. It's possible for this function to return NULL and it // expects |node| to always be non-NULL. -std::unique_ptr<ListValue> CopyListWithoutEmptyChildren(const ListValue& list) { - std::unique_ptr<ListValue> copy; +scoped_ptr<ListValue> CopyListWithoutEmptyChildren(const ListValue& list) { + scoped_ptr<ListValue> copy; for (ListValue::const_iterator it = list.begin(); it != list.end(); ++it) { - std::unique_ptr<Value> child_copy = CopyWithoutEmptyChildren(**it); + scoped_ptr<Value> child_copy = CopyWithoutEmptyChildren(**it); if (child_copy) { if (!copy) copy.reset(new ListValue); @@ -40,11 +39,11 @@ std::unique_ptr<ListValue> CopyListWithoutEmptyChildren(const ListValue& list) { return copy; } -std::unique_ptr<DictionaryValue> CopyDictionaryWithoutEmptyChildren( +scoped_ptr<DictionaryValue> CopyDictionaryWithoutEmptyChildren( const DictionaryValue& dict) { - std::unique_ptr<DictionaryValue> copy; + scoped_ptr<DictionaryValue> copy; for (DictionaryValue::Iterator it(dict); !it.IsAtEnd(); it.Advance()) { - std::unique_ptr<Value> child_copy = CopyWithoutEmptyChildren(it.value()); + scoped_ptr<Value> child_copy = CopyWithoutEmptyChildren(it.value()); if (child_copy) { if (!copy) copy.reset(new DictionaryValue); @@ -54,7 +53,7 @@ std::unique_ptr<DictionaryValue> CopyDictionaryWithoutEmptyChildren( return copy; } -std::unique_ptr<Value> CopyWithoutEmptyChildren(const Value& node) { +scoped_ptr<Value> CopyWithoutEmptyChildren(const Value& node) { switch (node.GetType()) { case Value::TYPE_LIST: return CopyListWithoutEmptyChildren(static_cast<const ListValue&>(node)); @@ -90,47 +89,47 @@ Value::~Value() { } // static -std::unique_ptr<Value> Value::CreateNullValue() { - return WrapUnique(new Value(TYPE_NULL)); +scoped_ptr<Value> Value::CreateNullValue() { + return make_scoped_ptr(new Value(TYPE_NULL)); } -bool Value::GetAsBinary(const BinaryValue**) const { +bool Value::GetAsBinary(const BinaryValue** /* out_value */) const { return false; } -bool Value::GetAsBoolean(bool*) const { +bool Value::GetAsBoolean(bool* /* out_value */) const { return false; } -bool Value::GetAsInteger(int*) const { +bool Value::GetAsInteger(int* /* out_value */) const { return false; } -bool Value::GetAsDouble(double*) const { +bool Value::GetAsDouble(double* /* out_value */) const { return false; } -bool Value::GetAsString(std::string*) const { +bool Value::GetAsString(std::string* /* out_value */) const { return false; } -bool Value::GetAsString(const StringValue**) const { +bool Value::GetAsString(const StringValue** out_value) const { return false; } -bool Value::GetAsList(ListValue**) { +bool Value::GetAsList(ListValue** /* out_value */) { return false; } -bool Value::GetAsList(const ListValue**) const { +bool Value::GetAsList(const ListValue** /* out_value */) const { return false; } -bool Value::GetAsDictionary(DictionaryValue**) { +bool Value::GetAsDictionary(DictionaryValue** /* out_value */) { return false; } -bool Value::GetAsDictionary(const DictionaryValue**) const { +bool Value::GetAsDictionary(const DictionaryValue** /* out_value */) const { return false; } @@ -141,8 +140,8 @@ Value* Value::DeepCopy() const { return CreateNullValue().release(); } -std::unique_ptr<Value> Value::CreateDeepCopy() const { - return WrapUnique(DeepCopy()); +scoped_ptr<Value> Value::CreateDeepCopy() const { + return make_scoped_ptr(DeepCopy()); } bool Value::Equals(const Value* other) const { @@ -299,7 +298,7 @@ BinaryValue::BinaryValue() size_(0) { } -BinaryValue::BinaryValue(std::unique_ptr<char[]> buffer, size_t size) +BinaryValue::BinaryValue(scoped_ptr<char[]> buffer, size_t size) : Value(TYPE_BINARY), buffer_(std::move(buffer)), size_(size) {} BinaryValue::~BinaryValue() { @@ -310,7 +309,7 @@ BinaryValue* BinaryValue::CreateWithCopiedBuffer(const char* buffer, size_t size) { char* buffer_copy = new char[size]; memcpy(buffer_copy, buffer, size); - std::unique_ptr<char[]> scoped_buffer_copy(buffer_copy); + scoped_ptr<char[]> scoped_buffer_copy(buffer_copy); return new BinaryValue(std::move(scoped_buffer_copy), size); } @@ -336,12 +335,11 @@ bool BinaryValue::Equals(const Value* other) const { ///////////////////// DictionaryValue //////////////////// // static -std::unique_ptr<DictionaryValue> DictionaryValue::From( - std::unique_ptr<Value> value) { +scoped_ptr<DictionaryValue> DictionaryValue::From(scoped_ptr<Value> value) { DictionaryValue* out; if (value && value->GetAsDictionary(&out)) { ignore_result(value.release()); - return WrapUnique(out); + return make_scoped_ptr(out); } return nullptr; } @@ -383,8 +381,7 @@ void DictionaryValue::Clear() { dictionary_.clear(); } -void DictionaryValue::Set(const std::string& path, - std::unique_ptr<Value> in_value) { +void DictionaryValue::Set(const std::string& path, scoped_ptr<Value> in_value) { DCHECK(IsStringUTF8(path)); DCHECK(in_value); @@ -410,7 +407,7 @@ void DictionaryValue::Set(const std::string& path, } void DictionaryValue::Set(const std::string& path, Value* in_value) { - Set(path, WrapUnique(in_value)); + Set(path, make_scoped_ptr(in_value)); } void DictionaryValue::SetBoolean(const std::string& path, bool in_value) { @@ -431,7 +428,7 @@ void DictionaryValue::SetString(const std::string& path, } void DictionaryValue::SetWithoutPathExpansion(const std::string& key, - std::unique_ptr<Value> in_value) { + scoped_ptr<Value> in_value) { Value* bare_ptr = in_value.release(); // If there's an existing value here, we need to delete it, because // we own all our children. @@ -446,7 +443,7 @@ void DictionaryValue::SetWithoutPathExpansion(const std::string& key, void DictionaryValue::SetWithoutPathExpansion(const std::string& key, Value* in_value) { - SetWithoutPathExpansion(key, WrapUnique(in_value)); + SetWithoutPathExpansion(key, make_scoped_ptr(in_value)); } void DictionaryValue::SetBooleanWithoutPathExpansion( @@ -712,7 +709,7 @@ bool DictionaryValue::GetListWithoutPathExpansion(const std::string& key, } bool DictionaryValue::Remove(const std::string& path, - std::unique_ptr<Value>* out_value) { + scoped_ptr<Value>* out_value) { DCHECK(IsStringUTF8(path)); std::string current_path(path); DictionaryValue* current_dictionary = this; @@ -728,9 +725,8 @@ bool DictionaryValue::Remove(const std::string& path, out_value); } -bool DictionaryValue::RemoveWithoutPathExpansion( - const std::string& key, - std::unique_ptr<Value>* out_value) { +bool DictionaryValue::RemoveWithoutPathExpansion(const std::string& key, + scoped_ptr<Value>* out_value) { DCHECK(IsStringUTF8(key)); ValueMap::iterator entry_iterator = dictionary_.find(key); if (entry_iterator == dictionary_.end()) @@ -746,7 +742,7 @@ bool DictionaryValue::RemoveWithoutPathExpansion( } bool DictionaryValue::RemovePath(const std::string& path, - std::unique_ptr<Value>* out_value) { + scoped_ptr<Value>* out_value) { bool result = false; size_t delimiter_position = path.find('.'); @@ -765,10 +761,9 @@ bool DictionaryValue::RemovePath(const std::string& path, return result; } -std::unique_ptr<DictionaryValue> DictionaryValue::DeepCopyWithoutEmptyChildren() +scoped_ptr<DictionaryValue> DictionaryValue::DeepCopyWithoutEmptyChildren() const { - std::unique_ptr<DictionaryValue> copy = - CopyDictionaryWithoutEmptyChildren(*this); + scoped_ptr<DictionaryValue> copy = CopyDictionaryWithoutEmptyChildren(*this); if (!copy) copy.reset(new DictionaryValue); return copy; @@ -815,8 +810,8 @@ DictionaryValue* DictionaryValue::DeepCopy() const { return result; } -std::unique_ptr<DictionaryValue> DictionaryValue::CreateDeepCopy() const { - return WrapUnique(DeepCopy()); +scoped_ptr<DictionaryValue> DictionaryValue::CreateDeepCopy() const { + return make_scoped_ptr(DeepCopy()); } bool DictionaryValue::Equals(const Value* other) const { @@ -844,11 +839,11 @@ bool DictionaryValue::Equals(const Value* other) const { ///////////////////// ListValue //////////////////// // static -std::unique_ptr<ListValue> ListValue::From(std::unique_ptr<Value> value) { +scoped_ptr<ListValue> ListValue::From(scoped_ptr<Value> value) { ListValue* out; if (value && value->GetAsList(&out)) { ignore_result(value.release()); - return WrapUnique(out); + return make_scoped_ptr(out); } return nullptr; } @@ -883,7 +878,7 @@ bool ListValue::Set(size_t index, Value* in_value) { return true; } -bool ListValue::Set(size_t index, std::unique_ptr<Value> in_value) { +bool ListValue::Set(size_t index, scoped_ptr<Value> in_value) { return Set(index, in_value.release()); } @@ -990,7 +985,7 @@ bool ListValue::GetList(size_t index, ListValue** out_value) { const_cast<const ListValue**>(out_value)); } -bool ListValue::Remove(size_t index, std::unique_ptr<Value>* out_value) { +bool ListValue::Remove(size_t index, scoped_ptr<Value>* out_value) { if (index >= list_.size()) return false; @@ -1019,7 +1014,7 @@ bool ListValue::Remove(const Value& value, size_t* index) { } ListValue::iterator ListValue::Erase(iterator iter, - std::unique_ptr<Value>* out_value) { + scoped_ptr<Value>* out_value) { if (out_value) out_value->reset(*iter); else @@ -1028,7 +1023,7 @@ ListValue::iterator ListValue::Erase(iterator iter, return list_.erase(iter); } -void ListValue::Append(std::unique_ptr<Value> in_value) { +void ListValue::Append(scoped_ptr<Value> in_value) { Append(in_value.release()); } @@ -1110,8 +1105,8 @@ ListValue* ListValue::DeepCopy() const { return result; } -std::unique_ptr<ListValue> ListValue::CreateDeepCopy() const { - return WrapUnique(DeepCopy()); +scoped_ptr<ListValue> ListValue::CreateDeepCopy() const { + return make_scoped_ptr(DeepCopy()); } bool ListValue::Equals(const Value* other) const { diff --git a/third_party/chromium/base/values.h b/third_party/chromium/base/values.h index fca5239..36e24cc 100644 --- a/third_party/chromium/base/values.h +++ b/third_party/chromium/base/values.h @@ -22,7 +22,6 @@ #include <iosfwd> #include <map> -#include <memory> #include <string> #include <utility> #include <vector> @@ -30,6 +29,7 @@ #include "base/base_export.h" #include "base/compiler_specific.h" #include "base/macros.h" +#include "base/memory/scoped_ptr.h" #include "base/strings/string_piece.h" namespace base { @@ -65,7 +65,7 @@ class BASE_EXPORT Value { virtual ~Value(); - static std::unique_ptr<Value> CreateNullValue(); + static scoped_ptr<Value> CreateNullValue(); // Returns the type of the value stored by the current Value object. // Each type will be implemented by only one subclass of Value, so it's @@ -100,7 +100,7 @@ class BASE_EXPORT Value { // this works because C++ supports covariant return types. virtual Value* DeepCopy() const; // Preferred version of DeepCopy. TODO(estade): remove the above. - std::unique_ptr<Value> CreateDeepCopy() const; + scoped_ptr<Value> CreateDeepCopy() const; // Compares if two Value objects have equal contents. virtual bool Equals(const Value* other) const; @@ -172,7 +172,7 @@ class BASE_EXPORT BinaryValue : public Value { // Creates a BinaryValue, taking ownership of the bytes pointed to by // |buffer|. - BinaryValue(std::unique_ptr<char[]> buffer, size_t size); + BinaryValue(scoped_ptr<char[]> buffer, size_t size); ~BinaryValue() override; @@ -193,7 +193,7 @@ class BASE_EXPORT BinaryValue : public Value { bool Equals(const Value* other) const override; private: - std::unique_ptr<char[]> buffer_; + scoped_ptr<char[]> buffer_; size_t size_; DISALLOW_COPY_AND_ASSIGN(BinaryValue); @@ -205,7 +205,7 @@ class BASE_EXPORT BinaryValue : public Value { class BASE_EXPORT DictionaryValue : public Value { public: // Returns |value| if it is a dictionary, nullptr otherwise. - static std::unique_ptr<DictionaryValue> From(std::unique_ptr<Value> value); + static scoped_ptr<DictionaryValue> From(scoped_ptr<Value> value); DictionaryValue(); ~DictionaryValue() override; @@ -233,7 +233,7 @@ class BASE_EXPORT DictionaryValue : public Value { // If the key at any step of the way doesn't exist, or exists but isn't // a DictionaryValue, a new DictionaryValue will be created and attached // to the path in that location. |in_value| must be non-null. - void Set(const std::string& path, std::unique_ptr<Value> in_value); + void Set(const std::string& path, scoped_ptr<Value> in_value); // Deprecated version of the above. TODO(estade): remove. void Set(const std::string& path, Value* in_value); @@ -247,7 +247,7 @@ class BASE_EXPORT DictionaryValue : public Value { // Like Set(), but without special treatment of '.'. This allows e.g. URLs to // be used as paths. void SetWithoutPathExpansion(const std::string& key, - std::unique_ptr<Value> in_value); + scoped_ptr<Value> in_value); // Deprecated version of the above. TODO(estade): remove. void SetWithoutPathExpansion(const std::string& key, Value* in_value); @@ -317,22 +317,21 @@ class BASE_EXPORT DictionaryValue : public Value { // |out_value|. If |out_value| is NULL, the removed value will be deleted. // This method returns true if |path| is a valid path; otherwise it will // return false and the DictionaryValue object will be unchanged. - virtual bool Remove(const std::string& path, - std::unique_ptr<Value>* out_value); + virtual bool Remove(const std::string& path, scoped_ptr<Value>* out_value); // Like Remove(), but without special treatment of '.'. This allows e.g. URLs // to be used as paths. virtual bool RemoveWithoutPathExpansion(const std::string& key, - std::unique_ptr<Value>* out_value); + scoped_ptr<Value>* out_value); // Removes a path, clearing out all dictionaries on |path| that remain empty // after removing the value at |path|. virtual bool RemovePath(const std::string& path, - std::unique_ptr<Value>* out_value); + scoped_ptr<Value>* out_value); // Makes a copy of |this| but doesn't include empty dictionaries and lists in // the copy. This never returns NULL, even if |this| itself is empty. - std::unique_ptr<DictionaryValue> DeepCopyWithoutEmptyChildren() const; + scoped_ptr<DictionaryValue> DeepCopyWithoutEmptyChildren() const; // Merge |dictionary| into this dictionary. This is done recursively, i.e. any // sub-dictionaries will be merged as well. In case of key collisions, the @@ -366,7 +365,7 @@ class BASE_EXPORT DictionaryValue : public Value { // Overridden from Value: DictionaryValue* DeepCopy() const override; // Preferred version of DeepCopy. TODO(estade): remove the above. - std::unique_ptr<DictionaryValue> CreateDeepCopy() const; + scoped_ptr<DictionaryValue> CreateDeepCopy() const; bool Equals(const Value* other) const override; private: @@ -382,7 +381,7 @@ class BASE_EXPORT ListValue : public Value { typedef ValueVector::const_iterator const_iterator; // Returns |value| if it is a list, nullptr otherwise. - static std::unique_ptr<ListValue> From(std::unique_ptr<Value> value); + static scoped_ptr<ListValue> From(scoped_ptr<Value> value); ListValue(); ~ListValue() override; @@ -403,7 +402,7 @@ class BASE_EXPORT ListValue : public Value { // the value is a null pointer. bool Set(size_t index, Value* in_value); // Preferred version of the above. TODO(estade): remove the above. - bool Set(size_t index, std::unique_ptr<Value> in_value); + bool Set(size_t index, scoped_ptr<Value> in_value); // Gets the Value at the given index. Modifies |out_value| (and returns true) // only if the index falls within the current list range. @@ -434,7 +433,7 @@ class BASE_EXPORT ListValue : public Value { // passed out via |out_value|. If |out_value| is NULL, the removed value will // be deleted. This method returns true if |index| is valid; otherwise // it will return false and the ListValue object will be unchanged. - virtual bool Remove(size_t index, std::unique_ptr<Value>* out_value); + virtual bool Remove(size_t index, scoped_ptr<Value>* out_value); // Removes the first instance of |value| found in the list, if any, and // deletes it. |index| is the location where |value| was found. Returns false @@ -445,10 +444,10 @@ class BASE_EXPORT ListValue : public Value { // deleted, otherwise ownership of the value is passed back to the caller. // Returns an iterator pointing to the location of the element that // followed the erased element. - iterator Erase(iterator iter, std::unique_ptr<Value>* out_value); + iterator Erase(iterator iter, scoped_ptr<Value>* out_value); // Appends a Value to the end of the list. - void Append(std::unique_ptr<Value> in_value); + void Append(scoped_ptr<Value> in_value); // Deprecated version of the above. TODO(estade): remove. void Append(Value* in_value); @@ -490,7 +489,7 @@ class BASE_EXPORT ListValue : public Value { bool Equals(const Value* other) const override; // Preferred version of DeepCopy. TODO(estade): remove DeepCopy. - std::unique_ptr<ListValue> CreateDeepCopy() const; + scoped_ptr<ListValue> CreateDeepCopy() const; private: ValueVector list_; diff --git a/third_party/chromium/base/values_unittest.cc b/third_party/chromium/base/values_unittest.cc index 5e49446..b5e47dd 100644 --- a/third_party/chromium/base/values_unittest.cc +++ b/third_party/chromium/base/values_unittest.cc @@ -2,18 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "base/values.h" - #include <stddef.h> #include <limits> -#include <memory> #include <utility> #include <gtest/gtest.h> -#include "base/memory/ptr_util.h" +#include "base/memory/scoped_ptr.h" #include "base/strings/utf_string_conversion_utils.h" +#include "base/values.h" namespace base { @@ -38,11 +36,11 @@ TEST(ValuesTest, Basic) { ASSERT_FALSE( settings.GetList("global.toolbar.bookmarks", &toolbar_bookmarks)); - std::unique_ptr<ListValue> new_toolbar_bookmarks(new ListValue); + scoped_ptr<ListValue> new_toolbar_bookmarks(new ListValue); settings.Set("global.toolbar.bookmarks", std::move(new_toolbar_bookmarks)); ASSERT_TRUE(settings.GetList("global.toolbar.bookmarks", &toolbar_bookmarks)); - std::unique_ptr<DictionaryValue> new_bookmark(new DictionaryValue); + scoped_ptr<DictionaryValue> new_bookmark(new DictionaryValue); new_bookmark->SetString("name", "Froogle"); new_bookmark->SetString("url", "http://froogle.com"); toolbar_bookmarks->Append(std::move(new_bookmark)); @@ -61,11 +59,11 @@ TEST(ValuesTest, Basic) { } TEST(ValuesTest, List) { - std::unique_ptr<ListValue> mixed_list(new ListValue()); - mixed_list->Set(0, WrapUnique(new FundamentalValue(true))); - mixed_list->Set(1, WrapUnique(new FundamentalValue(42))); - mixed_list->Set(2, WrapUnique(new FundamentalValue(88.8))); - mixed_list->Set(3, WrapUnique(new StringValue("foo"))); + scoped_ptr<ListValue> mixed_list(new ListValue()); + mixed_list->Set(0, make_scoped_ptr(new FundamentalValue(true))); + mixed_list->Set(1, make_scoped_ptr(new FundamentalValue(42))); + mixed_list->Set(2, make_scoped_ptr(new FundamentalValue(88.8))); + mixed_list->Set(3, make_scoped_ptr(new StringValue("foo"))); ASSERT_EQ(4u, mixed_list->GetSize()); Value *value = NULL; @@ -111,13 +109,13 @@ TEST(ValuesTest, List) { TEST(ValuesTest, BinaryValue) { // Default constructor creates a BinaryValue with a null buffer and size 0. - std::unique_ptr<BinaryValue> binary(new BinaryValue()); + scoped_ptr<BinaryValue> binary(new BinaryValue()); ASSERT_TRUE(binary.get()); ASSERT_EQ(NULL, binary->GetBuffer()); ASSERT_EQ(0U, binary->GetSize()); // Test the common case of a non-empty buffer - std::unique_ptr<char[]> buffer(new char[15]); + scoped_ptr<char[]> buffer(new char[15]); char* original_buffer = buffer.get(); binary.reset(new BinaryValue(std::move(buffer), 15)); ASSERT_TRUE(binary.get()); @@ -143,7 +141,7 @@ TEST(ValuesTest, BinaryValue) { TEST(ValuesTest, StringValue) { // Test overloaded StringValue constructor. - std::unique_ptr<Value> narrow_value(new StringValue("narrow")); + scoped_ptr<Value> narrow_value(new StringValue("narrow")); ASSERT_TRUE(narrow_value.get()); ASSERT_TRUE(narrow_value->IsType(Value::TYPE_STRING)); @@ -186,14 +184,14 @@ TEST(ValuesTest, ListDeletion) { { ListValue list; - list.Append(WrapUnique(new DeletionTestValue(&deletion_flag))); + list.Append(make_scoped_ptr(new DeletionTestValue(&deletion_flag))); EXPECT_FALSE(deletion_flag); } EXPECT_TRUE(deletion_flag); { ListValue list; - list.Append(WrapUnique(new DeletionTestValue(&deletion_flag))); + list.Append(make_scoped_ptr(new DeletionTestValue(&deletion_flag))); EXPECT_FALSE(deletion_flag); list.Clear(); EXPECT_TRUE(deletion_flag); @@ -201,7 +199,7 @@ TEST(ValuesTest, ListDeletion) { { ListValue list; - list.Append(WrapUnique(new DeletionTestValue(&deletion_flag))); + list.Append(make_scoped_ptr(new DeletionTestValue(&deletion_flag))); EXPECT_FALSE(deletion_flag); EXPECT_TRUE(list.Set(0, Value::CreateNullValue())); EXPECT_TRUE(deletion_flag); @@ -210,11 +208,11 @@ TEST(ValuesTest, ListDeletion) { TEST(ValuesTest, ListRemoval) { bool deletion_flag = true; - std::unique_ptr<Value> removed_item; + scoped_ptr<Value> removed_item; { ListValue list; - list.Append(WrapUnique(new DeletionTestValue(&deletion_flag))); + list.Append(make_scoped_ptr(new DeletionTestValue(&deletion_flag))); EXPECT_FALSE(deletion_flag); EXPECT_EQ(1U, list.GetSize()); EXPECT_FALSE(list.Remove(std::numeric_limits<size_t>::max(), @@ -230,7 +228,7 @@ TEST(ValuesTest, ListRemoval) { { ListValue list; - list.Append(WrapUnique(new DeletionTestValue(&deletion_flag))); + list.Append(make_scoped_ptr(new DeletionTestValue(&deletion_flag))); EXPECT_FALSE(deletion_flag); EXPECT_TRUE(list.Remove(0, NULL)); EXPECT_TRUE(deletion_flag); @@ -239,8 +237,7 @@ TEST(ValuesTest, ListRemoval) { { ListValue list; - std::unique_ptr<DeletionTestValue> value( - new DeletionTestValue(&deletion_flag)); + scoped_ptr<DeletionTestValue> value(new DeletionTestValue(&deletion_flag)); DeletionTestValue* original_value = value.get(); list.Append(std::move(value)); EXPECT_FALSE(deletion_flag); @@ -258,14 +255,14 @@ TEST(ValuesTest, DictionaryDeletion) { { DictionaryValue dict; - dict.Set(key, WrapUnique(new DeletionTestValue(&deletion_flag))); + dict.Set(key, make_scoped_ptr(new DeletionTestValue(&deletion_flag))); EXPECT_FALSE(deletion_flag); } EXPECT_TRUE(deletion_flag); { DictionaryValue dict; - dict.Set(key, WrapUnique(new DeletionTestValue(&deletion_flag))); + dict.Set(key, make_scoped_ptr(new DeletionTestValue(&deletion_flag))); EXPECT_FALSE(deletion_flag); dict.Clear(); EXPECT_TRUE(deletion_flag); @@ -273,7 +270,7 @@ TEST(ValuesTest, DictionaryDeletion) { { DictionaryValue dict; - dict.Set(key, WrapUnique(new DeletionTestValue(&deletion_flag))); + dict.Set(key, make_scoped_ptr(new DeletionTestValue(&deletion_flag))); EXPECT_FALSE(deletion_flag); dict.Set(key, Value::CreateNullValue()); EXPECT_TRUE(deletion_flag); @@ -283,11 +280,11 @@ TEST(ValuesTest, DictionaryDeletion) { TEST(ValuesTest, DictionaryRemoval) { std::string key = "test"; bool deletion_flag = true; - std::unique_ptr<Value> removed_item; + scoped_ptr<Value> removed_item; { DictionaryValue dict; - dict.Set(key, WrapUnique(new DeletionTestValue(&deletion_flag))); + dict.Set(key, make_scoped_ptr(new DeletionTestValue(&deletion_flag))); EXPECT_FALSE(deletion_flag); EXPECT_TRUE(dict.HasKey(key)); EXPECT_FALSE(dict.Remove("absent key", &removed_item)); @@ -301,7 +298,7 @@ TEST(ValuesTest, DictionaryRemoval) { { DictionaryValue dict; - dict.Set(key, WrapUnique(new DeletionTestValue(&deletion_flag))); + dict.Set(key, make_scoped_ptr(new DeletionTestValue(&deletion_flag))); EXPECT_FALSE(deletion_flag); EXPECT_TRUE(dict.HasKey(key)); EXPECT_TRUE(dict.Remove(key, NULL)); @@ -361,7 +358,7 @@ TEST(ValuesTest, DictionaryRemovePath) { dict.SetInteger("a.long.way.down", 1); dict.SetBoolean("a.long.key.path", true); - std::unique_ptr<Value> removed_item; + scoped_ptr<Value> removed_item; EXPECT_TRUE(dict.RemovePath("a.long.way.down", &removed_item)); ASSERT_TRUE(removed_item); EXPECT_TRUE(removed_item->IsType(base::Value::TYPE_INTEGER)); @@ -383,48 +380,45 @@ TEST(ValuesTest, DictionaryRemovePath) { TEST(ValuesTest, DeepCopy) { DictionaryValue original_dict; - std::unique_ptr<Value> scoped_null = Value::CreateNullValue(); + scoped_ptr<Value> scoped_null = Value::CreateNullValue(); Value* original_null = scoped_null.get(); original_dict.Set("null", std::move(scoped_null)); - std::unique_ptr<FundamentalValue> scoped_bool(new FundamentalValue(true)); + scoped_ptr<FundamentalValue> scoped_bool(new FundamentalValue(true)); FundamentalValue* original_bool = scoped_bool.get(); original_dict.Set("bool", std::move(scoped_bool)); - std::unique_ptr<FundamentalValue> scoped_int(new FundamentalValue(42)); + scoped_ptr<FundamentalValue> scoped_int(new FundamentalValue(42)); FundamentalValue* original_int = scoped_int.get(); original_dict.Set("int", std::move(scoped_int)); - std::unique_ptr<FundamentalValue> scoped_double(new FundamentalValue(3.14)); + scoped_ptr<FundamentalValue> scoped_double(new FundamentalValue(3.14)); FundamentalValue* original_double = scoped_double.get(); original_dict.Set("double", std::move(scoped_double)); - std::unique_ptr<StringValue> scoped_string(new StringValue("hello")); + scoped_ptr<StringValue> scoped_string(new StringValue("hello")); StringValue* original_string = scoped_string.get(); original_dict.Set("string", std::move(scoped_string)); - std::unique_ptr<char[]> original_buffer(new char[42]); + scoped_ptr<char[]> original_buffer(new char[42]); memset(original_buffer.get(), '!', 42); - std::unique_ptr<BinaryValue> scoped_binary( + scoped_ptr<BinaryValue> scoped_binary( new BinaryValue(std::move(original_buffer), 42)); BinaryValue* original_binary = scoped_binary.get(); original_dict.Set("binary", std::move(scoped_binary)); - std::unique_ptr<ListValue> scoped_list(new ListValue()); + scoped_ptr<ListValue> scoped_list(new ListValue()); Value* original_list = scoped_list.get(); - std::unique_ptr<FundamentalValue> scoped_list_element_0( - new FundamentalValue(0)); + scoped_ptr<FundamentalValue> scoped_list_element_0(new FundamentalValue(0)); Value* original_list_element_0 = scoped_list_element_0.get(); scoped_list->Append(std::move(scoped_list_element_0)); - std::unique_ptr<FundamentalValue> scoped_list_element_1( - new FundamentalValue(1)); + scoped_ptr<FundamentalValue> scoped_list_element_1(new FundamentalValue(1)); Value* original_list_element_1 = scoped_list_element_1.get(); scoped_list->Append(std::move(scoped_list_element_1)); original_dict.Set("list", std::move(scoped_list)); - std::unique_ptr<DictionaryValue> scoped_nested_dictionary( - new DictionaryValue()); + scoped_ptr<DictionaryValue> scoped_nested_dictionary(new DictionaryValue()); Value* original_nested_dictionary = scoped_nested_dictionary.get(); scoped_nested_dictionary->SetString("key", "value"); original_dict.Set("dictionary", std::move(scoped_nested_dictionary)); - std::unique_ptr<DictionaryValue> copy_dict = original_dict.CreateDeepCopy(); + scoped_ptr<DictionaryValue> copy_dict = original_dict.CreateDeepCopy(); ASSERT_TRUE(copy_dict.get()); ASSERT_NE(copy_dict.get(), &original_dict); @@ -519,8 +513,8 @@ TEST(ValuesTest, DeepCopy) { } TEST(ValuesTest, Equals) { - std::unique_ptr<Value> null1(Value::CreateNullValue()); - std::unique_ptr<Value> null2(Value::CreateNullValue()); + scoped_ptr<Value> null1(Value::CreateNullValue()); + scoped_ptr<Value> null2(Value::CreateNullValue()); EXPECT_NE(null1.get(), null2.get()); EXPECT_TRUE(null1->Equals(null2.get())); @@ -534,21 +528,21 @@ TEST(ValuesTest, Equals) { dv.SetString("d1", "string"); dv.Set("e", Value::CreateNullValue()); - std::unique_ptr<DictionaryValue> copy = dv.CreateDeepCopy(); + scoped_ptr<DictionaryValue> copy = dv.CreateDeepCopy(); EXPECT_TRUE(dv.Equals(copy.get())); - std::unique_ptr<ListValue> list(new ListValue); + scoped_ptr<ListValue> list(new ListValue); ListValue* original_list = list.get(); list->Append(Value::CreateNullValue()); - list->Append(WrapUnique(new DictionaryValue)); - std::unique_ptr<Value> list_copy(list->CreateDeepCopy()); + list->Append(make_scoped_ptr(new DictionaryValue)); + scoped_ptr<Value> list_copy(list->CreateDeepCopy()); dv.Set("f", std::move(list)); EXPECT_FALSE(dv.Equals(copy.get())); copy->Set("f", std::move(list_copy)); EXPECT_TRUE(dv.Equals(copy.get())); - original_list->Append(WrapUnique(new FundamentalValue(true))); + original_list->Append(make_scoped_ptr(new FundamentalValue(true))); EXPECT_FALSE(dv.Equals(copy.get())); // Check if Equals detects differences in only the keys. @@ -560,14 +554,14 @@ TEST(ValuesTest, Equals) { } TEST(ValuesTest, StaticEquals) { - std::unique_ptr<Value> null1(Value::CreateNullValue()); - std::unique_ptr<Value> null2(Value::CreateNullValue()); + scoped_ptr<Value> null1(Value::CreateNullValue()); + scoped_ptr<Value> null2(Value::CreateNullValue()); EXPECT_TRUE(Value::Equals(null1.get(), null2.get())); EXPECT_TRUE(Value::Equals(NULL, NULL)); - std::unique_ptr<Value> i42(new FundamentalValue(42)); - std::unique_ptr<Value> j42(new FundamentalValue(42)); - std::unique_ptr<Value> i17(new FundamentalValue(17)); + scoped_ptr<Value> i42(new FundamentalValue(42)); + scoped_ptr<Value> j42(new FundamentalValue(42)); + scoped_ptr<Value> i17(new FundamentalValue(17)); EXPECT_TRUE(Value::Equals(i42.get(), i42.get())); EXPECT_TRUE(Value::Equals(j42.get(), i42.get())); EXPECT_TRUE(Value::Equals(i42.get(), j42.get())); @@ -584,47 +578,45 @@ TEST(ValuesTest, StaticEquals) { TEST(ValuesTest, DeepCopyCovariantReturnTypes) { DictionaryValue original_dict; - std::unique_ptr<Value> scoped_null(Value::CreateNullValue()); + scoped_ptr<Value> scoped_null(Value::CreateNullValue()); Value* original_null = scoped_null.get(); original_dict.Set("null", std::move(scoped_null)); - std::unique_ptr<FundamentalValue> scoped_bool(new FundamentalValue(true)); + scoped_ptr<FundamentalValue> scoped_bool(new FundamentalValue(true)); Value* original_bool = scoped_bool.get(); original_dict.Set("bool", std::move(scoped_bool)); - std::unique_ptr<FundamentalValue> scoped_int(new FundamentalValue(42)); + scoped_ptr<FundamentalValue> scoped_int(new FundamentalValue(42)); Value* original_int = scoped_int.get(); original_dict.Set("int", std::move(scoped_int)); - std::unique_ptr<FundamentalValue> scoped_double(new FundamentalValue(3.14)); + scoped_ptr<FundamentalValue> scoped_double(new FundamentalValue(3.14)); Value* original_double = scoped_double.get(); original_dict.Set("double", std::move(scoped_double)); - std::unique_ptr<StringValue> scoped_string(new StringValue("hello")); + scoped_ptr<StringValue> scoped_string(new StringValue("hello")); Value* original_string = scoped_string.get(); original_dict.Set("string", std::move(scoped_string)); - std::unique_ptr<char[]> original_buffer(new char[42]); + scoped_ptr<char[]> original_buffer(new char[42]); memset(original_buffer.get(), '!', 42); - std::unique_ptr<BinaryValue> scoped_binary( + scoped_ptr<BinaryValue> scoped_binary( new BinaryValue(std::move(original_buffer), 42)); Value* original_binary = scoped_binary.get(); original_dict.Set("binary", std::move(scoped_binary)); - std::unique_ptr<ListValue> scoped_list(new ListValue()); + scoped_ptr<ListValue> scoped_list(new ListValue()); Value* original_list = scoped_list.get(); - std::unique_ptr<FundamentalValue> scoped_list_element_0( - new FundamentalValue(0)); + scoped_ptr<FundamentalValue> scoped_list_element_0(new FundamentalValue(0)); scoped_list->Append(std::move(scoped_list_element_0)); - std::unique_ptr<FundamentalValue> scoped_list_element_1( - new FundamentalValue(1)); + scoped_ptr<FundamentalValue> scoped_list_element_1(new FundamentalValue(1)); scoped_list->Append(std::move(scoped_list_element_1)); original_dict.Set("list", std::move(scoped_list)); - std::unique_ptr<Value> copy_dict = original_dict.CreateDeepCopy(); - std::unique_ptr<Value> copy_null = original_null->CreateDeepCopy(); - std::unique_ptr<Value> copy_bool = original_bool->CreateDeepCopy(); - std::unique_ptr<Value> copy_int = original_int->CreateDeepCopy(); - std::unique_ptr<Value> copy_double = original_double->CreateDeepCopy(); - std::unique_ptr<Value> copy_string = original_string->CreateDeepCopy(); - std::unique_ptr<Value> copy_binary = original_binary->CreateDeepCopy(); - std::unique_ptr<Value> copy_list = original_list->CreateDeepCopy(); + scoped_ptr<Value> copy_dict = original_dict.CreateDeepCopy(); + scoped_ptr<Value> copy_null = original_null->CreateDeepCopy(); + scoped_ptr<Value> copy_bool = original_bool->CreateDeepCopy(); + scoped_ptr<Value> copy_int = original_int->CreateDeepCopy(); + scoped_ptr<Value> copy_double = original_double->CreateDeepCopy(); + scoped_ptr<Value> copy_string = original_string->CreateDeepCopy(); + scoped_ptr<Value> copy_binary = original_binary->CreateDeepCopy(); + scoped_ptr<Value> copy_list = original_list->CreateDeepCopy(); EXPECT_TRUE(original_dict.Equals(copy_dict.get())); EXPECT_TRUE(original_null->Equals(copy_null.get())); @@ -637,18 +629,18 @@ TEST(ValuesTest, DeepCopyCovariantReturnTypes) { } TEST(ValuesTest, RemoveEmptyChildren) { - std::unique_ptr<DictionaryValue> root(new DictionaryValue); + scoped_ptr<DictionaryValue> root(new DictionaryValue); // Remove empty lists and dictionaries. - root->Set("empty_dict", WrapUnique(new DictionaryValue)); - root->Set("empty_list", WrapUnique(new ListValue)); + root->Set("empty_dict", make_scoped_ptr(new DictionaryValue)); + root->Set("empty_list", make_scoped_ptr(new ListValue)); root->SetWithoutPathExpansion("a.b.c.d.e", - WrapUnique(new DictionaryValue)); + make_scoped_ptr(new DictionaryValue)); root = root->DeepCopyWithoutEmptyChildren(); EXPECT_TRUE(root->empty()); // Make sure we don't prune too much. root->SetBoolean("bool", true); - root->Set("empty_dict", WrapUnique(new DictionaryValue)); + root->Set("empty_dict", make_scoped_ptr(new DictionaryValue)); root->SetString("empty_string", std::string()); root = root->DeepCopyWithoutEmptyChildren(); EXPECT_EQ(2U, root->size()); @@ -660,22 +652,22 @@ TEST(ValuesTest, RemoveEmptyChildren) { // Nested test cases. These should all reduce back to the bool and string // set above. { - root->Set("a.b.c.d.e", WrapUnique(new DictionaryValue)); + root->Set("a.b.c.d.e", make_scoped_ptr(new DictionaryValue)); root = root->DeepCopyWithoutEmptyChildren(); EXPECT_EQ(2U, root->size()); } { - std::unique_ptr<DictionaryValue> inner(new DictionaryValue); - inner->Set("empty_dict", WrapUnique(new DictionaryValue)); - inner->Set("empty_list", WrapUnique(new ListValue)); + scoped_ptr<DictionaryValue> inner(new DictionaryValue); + inner->Set("empty_dict", make_scoped_ptr(new DictionaryValue)); + inner->Set("empty_list", make_scoped_ptr(new ListValue)); root->Set("dict_with_empty_children", std::move(inner)); root = root->DeepCopyWithoutEmptyChildren(); EXPECT_EQ(2U, root->size()); } { - std::unique_ptr<ListValue> inner(new ListValue); - inner->Append(WrapUnique(new DictionaryValue)); - inner->Append(WrapUnique(new ListValue)); + scoped_ptr<ListValue> inner(new ListValue); + inner->Append(make_scoped_ptr(new DictionaryValue)); + inner->Append(make_scoped_ptr(new ListValue)); root->Set("list_with_empty_children", std::move(inner)); root = root->DeepCopyWithoutEmptyChildren(); EXPECT_EQ(2U, root->size()); @@ -683,13 +675,13 @@ TEST(ValuesTest, RemoveEmptyChildren) { // Nested with siblings. { - std::unique_ptr<ListValue> inner(new ListValue()); - inner->Append(WrapUnique(new DictionaryValue)); - inner->Append(WrapUnique(new ListValue)); + scoped_ptr<ListValue> inner(new ListValue()); + inner->Append(make_scoped_ptr(new DictionaryValue)); + inner->Append(make_scoped_ptr(new ListValue)); root->Set("list_with_empty_children", std::move(inner)); - std::unique_ptr<DictionaryValue> inner2(new DictionaryValue); - inner2->Set("empty_dict", WrapUnique(new DictionaryValue)); - inner2->Set("empty_list", WrapUnique(new ListValue)); + scoped_ptr<DictionaryValue> inner2(new DictionaryValue); + inner2->Set("empty_dict", make_scoped_ptr(new DictionaryValue)); + inner2->Set("empty_list", make_scoped_ptr(new ListValue)); root->Set("dict_with_empty_children", std::move(inner2)); root = root->DeepCopyWithoutEmptyChildren(); EXPECT_EQ(2U, root->size()); @@ -697,10 +689,10 @@ TEST(ValuesTest, RemoveEmptyChildren) { // Make sure nested values don't get pruned. { - std::unique_ptr<ListValue> inner(new ListValue); - std::unique_ptr<ListValue> inner2(new ListValue); - inner2->Append(WrapUnique(new StringValue("hello"))); - inner->Append(WrapUnique(new DictionaryValue)); + scoped_ptr<ListValue> inner(new ListValue); + scoped_ptr<ListValue> inner2(new ListValue); + inner2->Append(make_scoped_ptr(new StringValue("hello"))); + inner->Append(make_scoped_ptr(new DictionaryValue)); inner->Append(std::move(inner2)); root->Set("list_with_empty_children", std::move(inner)); root = root->DeepCopyWithoutEmptyChildren(); @@ -715,18 +707,18 @@ TEST(ValuesTest, RemoveEmptyChildren) { } TEST(ValuesTest, MergeDictionary) { - std::unique_ptr<DictionaryValue> base(new DictionaryValue); + scoped_ptr<DictionaryValue> base(new DictionaryValue); base->SetString("base_key", "base_key_value_base"); base->SetString("collide_key", "collide_key_value_base"); - std::unique_ptr<DictionaryValue> base_sub_dict(new DictionaryValue); + scoped_ptr<DictionaryValue> base_sub_dict(new DictionaryValue); base_sub_dict->SetString("sub_base_key", "sub_base_key_value_base"); base_sub_dict->SetString("sub_collide_key", "sub_collide_key_value_base"); base->Set("sub_dict_key", std::move(base_sub_dict)); - std::unique_ptr<DictionaryValue> merge(new DictionaryValue); + scoped_ptr<DictionaryValue> merge(new DictionaryValue); merge->SetString("merge_key", "merge_key_value_merge"); merge->SetString("collide_key", "collide_key_value_merge"); - std::unique_ptr<DictionaryValue> merge_sub_dict(new DictionaryValue); + scoped_ptr<DictionaryValue> merge_sub_dict(new DictionaryValue); merge_sub_dict->SetString("sub_merge_key", "sub_merge_key_value_merge"); merge_sub_dict->SetString("sub_collide_key", "sub_collide_key_value_merge"); merge->Set("sub_dict_key", std::move(merge_sub_dict)); @@ -760,7 +752,7 @@ TEST(ValuesTest, MergeDictionary) { } TEST(ValuesTest, MergeDictionaryDeepCopy) { - std::unique_ptr<DictionaryValue> child(new DictionaryValue); + scoped_ptr<DictionaryValue> child(new DictionaryValue); DictionaryValue* original_child = child.get(); child->SetString("test", "value"); EXPECT_EQ(1U, child->size()); @@ -769,7 +761,7 @@ TEST(ValuesTest, MergeDictionaryDeepCopy) { EXPECT_TRUE(child->GetString("test", &value)); EXPECT_EQ("value", value); - std::unique_ptr<DictionaryValue> base(new DictionaryValue); + scoped_ptr<DictionaryValue> base(new DictionaryValue); base->Set("dict", std::move(child)); EXPECT_EQ(1U, base->size()); @@ -777,7 +769,7 @@ TEST(ValuesTest, MergeDictionaryDeepCopy) { EXPECT_TRUE(base->GetDictionary("dict", &ptr)); EXPECT_EQ(original_child, ptr); - std::unique_ptr<DictionaryValue> merged(new DictionaryValue); + scoped_ptr<DictionaryValue> merged(new DictionaryValue); merged->MergeDictionary(base.get()); EXPECT_EQ(1U, merged->size()); EXPECT_TRUE(merged->GetDictionary("dict", &ptr)); diff --git a/third_party/chromium/crypto/sha2.cc b/third_party/chromium/crypto/sha2.cc index 1ab3fe1..7dcef0b 100644 --- a/third_party/chromium/crypto/sha2.cc +++ b/third_party/chromium/crypto/sha2.cc @@ -7,6 +7,8 @@ #include <algorithm> #include <openssl/sha.h> +#include <base/memory/scoped_ptr.h> + namespace crypto { void SHA256HashString(const std::string& str, uint8_t* output, size_t len) { |