1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #include "sync/internal_api/public/base/model_type_invalidation_map.h" 6 7 #include <vector> 8 9 #include "base/json/json_writer.h" 10 #include "base/json/string_escape.h" 11 #include "base/memory/scoped_ptr.h" 12 #include "base/values.h" 13 14 namespace syncer { 15 16 ModelTypeInvalidationMap ModelTypeSetToInvalidationMap( 17 ModelTypeSet types, const std::string& payload) { 18 ModelTypeInvalidationMap invalidation_map; 19 for (ModelTypeSet::Iterator it = types.First(); it.Good(); it.Inc()) { 20 // TODO(dcheng): Do we need to set ack_handle? 21 invalidation_map[it.Get()].payload = payload; 22 } 23 return invalidation_map; 24 } 25 26 ModelTypeSet ModelTypeInvalidationMapToSet( 27 const ModelTypeInvalidationMap& invalidation_map) { 28 ModelTypeSet types; 29 for (ModelTypeInvalidationMap::const_iterator it = invalidation_map.begin(); 30 it != invalidation_map.end(); ++it) { 31 types.Put(it->first); 32 } 33 return types; 34 } 35 36 std::string ModelTypeInvalidationMapToString( 37 const ModelTypeInvalidationMap& invalidation_map) { 38 scoped_ptr<base::DictionaryValue> value( 39 ModelTypeInvalidationMapToValue(invalidation_map)); 40 std::string json; 41 base::JSONWriter::Write(value.get(), &json); 42 return json; 43 } 44 45 base::DictionaryValue* ModelTypeInvalidationMapToValue( 46 const ModelTypeInvalidationMap& invalidation_map) { 47 base::DictionaryValue* value = new base::DictionaryValue(); 48 for (ModelTypeInvalidationMap::const_iterator it = invalidation_map.begin(); 49 it != invalidation_map.end(); ++it) { 50 std::string printable_payload; 51 base::JsonDoubleQuote(it->second.payload, 52 false /* put_in_quotes */, 53 &printable_payload); 54 value->SetString(ModelTypeToString(it->first), printable_payload); 55 } 56 return value; 57 } 58 59 void CoalesceStates(const ModelTypeInvalidationMap& update, 60 ModelTypeInvalidationMap* original) { 61 // TODO(dcheng): Where is this called? Do we need to add more clever logic for 62 // handling ack_handle? We probably want to always use the "latest" 63 // ack_handle, which might imply always using the one in update? 64 for (ModelTypeInvalidationMap::const_iterator i = update.begin(); 65 i != update.end(); ++i) { 66 if (original->count(i->first) == 0) { 67 // If this datatype isn't already in our map, add it with 68 // whatever payload it has. 69 (*original)[i->first] = i->second; 70 } else if (i->second.payload.length() > 0) { 71 // If this datatype is already in our map, we only overwrite the 72 // payload if the new one is non-empty. 73 (*original)[i->first].payload = i->second.payload; 74 } 75 } 76 } 77 78 } // namespace syncer 79