github.com/mdaxf/iac@v0.0.0-20240519030858-58a061660378/vendor_skip/go.mongodb.org/mongo-driver/x/mongo/driver/topology/diff.go (about)

     1  // Copyright (C) MongoDB, Inc. 2017-present.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License"); you may
     4  // not use this file except in compliance with the License. You may obtain
     5  // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
     6  
     7  package topology
     8  
     9  import "go.mongodb.org/mongo-driver/mongo/description"
    10  
    11  // hostlistDiff is the difference between a topology and a host list.
    12  type hostlistDiff struct {
    13  	Added   []string
    14  	Removed []string
    15  }
    16  
    17  // diffHostList compares the topology description and host list and returns the difference.
    18  func diffHostList(t description.Topology, hostlist []string) hostlistDiff {
    19  	var diff hostlistDiff
    20  
    21  	oldServers := make(map[string]bool)
    22  	for _, s := range t.Servers {
    23  		oldServers[s.Addr.String()] = true
    24  	}
    25  
    26  	for _, addr := range hostlist {
    27  		if oldServers[addr] {
    28  			delete(oldServers, addr)
    29  		} else {
    30  			diff.Added = append(diff.Added, addr)
    31  		}
    32  	}
    33  
    34  	for addr := range oldServers {
    35  		diff.Removed = append(diff.Removed, addr)
    36  	}
    37  
    38  	return diff
    39  }
    40  
    41  // topologyDiff is the difference between two different topology descriptions.
    42  type topologyDiff struct {
    43  	Added   []description.Server
    44  	Removed []description.Server
    45  }
    46  
    47  // diffTopology compares the two topology descriptions and returns the difference.
    48  func diffTopology(old, new description.Topology) topologyDiff {
    49  	var diff topologyDiff
    50  
    51  	oldServers := make(map[string]bool)
    52  	for _, s := range old.Servers {
    53  		oldServers[s.Addr.String()] = true
    54  	}
    55  
    56  	for _, s := range new.Servers {
    57  		addr := s.Addr.String()
    58  		if oldServers[addr] {
    59  			delete(oldServers, addr)
    60  		} else {
    61  			diff.Added = append(diff.Added, s)
    62  		}
    63  	}
    64  
    65  	for _, s := range old.Servers {
    66  		addr := s.Addr.String()
    67  		if oldServers[addr] {
    68  			diff.Removed = append(diff.Removed, s)
    69  		}
    70  	}
    71  
    72  	return diff
    73  }