1 // Copyright 2014 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 #import "ios/chrome/browser/crash_report/crash_report_multi_parameter.h"
7 #include "base/json/json_writer.h"
8 #include "base/logging.h"
9 #import "base/mac/scoped_nsobject.h"
10 #include "base/memory/scoped_ptr.h"
11 #include "base/strings/sys_string_conversions.h"
12 #include "base/values.h"
13 #import "ios/chrome/browser/crash_report/breakpad_helper.h"
16 // Maximum size of a breakpad parameter. he length of the dictionary serialized
17 // into JSON cannot exceed this length. See declaration in (BreakPad.h) for
19 const int kMaximumBreakpadValueSize = 255;
22 @implementation CrashReportMultiParameter {
23 base::scoped_nsobject<NSString> crashReportKey_;
24 scoped_ptr<base::DictionaryValue> dictionary_;
27 - (instancetype)init {
32 - (instancetype)initWithKey:(NSString*)key {
33 if ((self = [super init])) {
34 DCHECK([key length] && ([key length] <= kMaximumBreakpadValueSize));
35 dictionary_.reset(new base::DictionaryValue());
36 crashReportKey_.reset([key copy]);
41 - (void)removeValue:(NSString*)key {
42 dictionary_->Remove(base::SysNSStringToUTF8(key).c_str(), nullptr);
43 [self updateCrashReport];
46 - (void)setValue:(NSString*)key withValue:(int)value {
47 dictionary_->SetInteger(base::SysNSStringToUTF8(key).c_str(), value);
48 [self updateCrashReport];
51 - (void)incrementValue:(NSString*)key {
53 std::string utf8_string = base::SysNSStringToUTF8(key);
54 if (dictionary_->GetInteger(utf8_string.c_str(), &value)) {
55 dictionary_->SetInteger(utf8_string.c_str(), value + 1);
57 dictionary_->SetInteger(utf8_string.c_str(), 1);
59 [self updateCrashReport];
62 - (void)decrementValue:(NSString*)key {
64 std::string utf8_string = base::SysNSStringToUTF8(key);
65 if (dictionary_->GetInteger(utf8_string.c_str(), &value)) {
67 dictionary_->Remove(utf8_string.c_str(), nullptr);
69 dictionary_->SetInteger(utf8_string.c_str(), value - 1);
71 [self updateCrashReport];
75 - (void)updateCrashReport {
76 std::string stateAsJson;
77 base::JSONWriter::Write(*dictionary_.get(), &stateAsJson);
78 if (stateAsJson.length() > kMaximumBreakpadValueSize) {
82 breakpad_helper::AddReportParameter(
84 [NSString stringWithCString:stateAsJson.c_str()
85 encoding:[NSString defaultCStringEncoding]],