Popular sites on the NTP: Try to keep the ordering constant
[chromium-blink-merge.git] / components / safe_json / testing_json_parser.cc
blobea7e9c5469b45cc7378fa0cffe6df8ee75dce7ad
1 // Copyright 2015 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "components/safe_json/testing_json_parser.h"
7 #include "base/bind.h"
8 #include "base/bind_helpers.h"
9 #include "base/json/json_reader.h"
10 #include "base/location.h"
11 #include "base/memory/scoped_ptr.h"
12 #include "base/message_loop/message_loop.h"
13 #include "base/values.h"
15 namespace safe_json {
17 namespace {
19 SafeJsonParser* CreateTestingJsonParser(
20 const std::string& unsafe_json,
21 const SafeJsonParser::SuccessCallback& success_callback,
22 const SafeJsonParser::ErrorCallback& error_callback) {
23 return new TestingJsonParser(unsafe_json, success_callback, error_callback);
26 } // namespace
28 TestingJsonParser::ScopedFactoryOverride::ScopedFactoryOverride() {
29 SafeJsonParser::SetFactoryForTesting(&CreateTestingJsonParser);
32 TestingJsonParser::ScopedFactoryOverride::~ScopedFactoryOverride() {
33 SafeJsonParser::SetFactoryForTesting(nullptr);
36 TestingJsonParser::TestingJsonParser(const std::string& unsafe_json,
37 const SuccessCallback& success_callback,
38 const ErrorCallback& error_callback)
39 : unsafe_json_(unsafe_json),
40 success_callback_(success_callback),
41 error_callback_(error_callback) {}
43 TestingJsonParser::~TestingJsonParser() {}
45 void TestingJsonParser::Start() {
46 int error_code;
47 std::string error;
48 scoped_ptr<base::Value> value = base::JSONReader::ReadAndReturnError(
49 unsafe_json_, base::JSON_PARSE_RFC, &error_code, &error);
51 // Run the callback asynchronously.
52 base::MessageLoop::current()->PostTask(
53 FROM_HERE, value ? base::Bind(success_callback_, base::Passed(&value))
54 : base::Bind(error_callback_, error));
55 base::MessageLoop::current()->DeleteSoon(FROM_HERE, this);
58 } // namespace