network_id.cc 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // Copyright 2017 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. #include "net/nqe/network_id.h"
  5. #include <tuple>
  6. #include "base/base64.h"
  7. #include "base/strings/string_number_conversions.h"
  8. #include "net/nqe/proto/network_id_proto.pb.h"
  9. namespace net::nqe::internal {
  10. // static
  11. NetworkID NetworkID::FromString(const std::string& network_id) {
  12. std::string base64_decoded;
  13. if (!base::Base64Decode(network_id, &base64_decoded)) {
  14. return NetworkID(NetworkChangeNotifier::CONNECTION_UNKNOWN, std::string(),
  15. INT32_MIN);
  16. }
  17. NetworkIDProto network_id_proto;
  18. if (!network_id_proto.ParseFromString(base64_decoded)) {
  19. return NetworkID(NetworkChangeNotifier::CONNECTION_UNKNOWN, std::string(),
  20. INT32_MIN);
  21. }
  22. return NetworkID(static_cast<NetworkChangeNotifier::ConnectionType>(
  23. network_id_proto.connection_type()),
  24. network_id_proto.id(), network_id_proto.signal_strength());
  25. }
  26. NetworkID::NetworkID(NetworkChangeNotifier::ConnectionType type,
  27. const std::string& id,
  28. int32_t signal_strength)
  29. : type(type), id(id), signal_strength(signal_strength) {
  30. // A valid value of |signal_strength| must be between 0 and 4 (both
  31. // inclusive).
  32. DCHECK((0 <= signal_strength && 4 >= signal_strength) ||
  33. (INT32_MIN == signal_strength));
  34. }
  35. NetworkID::NetworkID(const NetworkID& other) = default;
  36. NetworkID::~NetworkID() = default;
  37. bool NetworkID::operator==(const NetworkID& other) const {
  38. return type == other.type && id == other.id &&
  39. signal_strength == other.signal_strength;
  40. }
  41. bool NetworkID::operator!=(const NetworkID& other) const {
  42. return !operator==(other);
  43. }
  44. NetworkID& NetworkID::operator=(const NetworkID& other) = default;
  45. // Overloaded to support ordered collections.
  46. bool NetworkID::operator<(const NetworkID& other) const {
  47. return std::tie(type, id, signal_strength) <
  48. std::tie(other.type, other.id, other.signal_strength);
  49. }
  50. std::string NetworkID::ToString() const {
  51. NetworkIDProto network_id_proto;
  52. network_id_proto.set_connection_type(static_cast<int>(type));
  53. network_id_proto.set_id(id);
  54. network_id_proto.set_signal_strength(signal_strength);
  55. std::string serialized_network_id;
  56. if (!network_id_proto.SerializeToString(&serialized_network_id))
  57. return "";
  58. std::string base64_encoded;
  59. base::Base64Encode(serialized_network_id, &base64_encoded);
  60. return base64_encoded;
  61. }
  62. } // namespace net::nqe::internal