1 /* Copyright 2016, Ableton AG, Berlin. All rights reserved. 2 * 3 * This program is free software: you can redistribute it and/or modify 4 * it under the terms of the GNU General Public License as published by 5 * the Free Software Foundation, either version 2 of the License, or 6 * (at your option) any later version. 7 * 8 * This program is distributed in the hope that it will be useful, 9 * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 * GNU General Public License for more details. 12 * 13 * You should have received a copy of the GNU General Public License 14 * along with this program. If not, see <http://www.gnu.org/licenses/>. 15 * 16 * If you would like to incorporate Link into a proprietary software application, 17 * please contact <link-devs@ableton.com>. 18 */ 19 20 #pragma once 21 22 #include <ableton/discovery/NetworkByteStreamSerializable.hpp> 23 #include <algorithm> 24 #include <array> 25 #include <cstdint> 26 #include <random> 27 #include <string> 28 29 namespace ableton 30 { 31 namespace link 32 { 33 34 using NodeIdArray = std::array<std::uint8_t, 8>; 35 36 struct NodeId : NodeIdArray 37 { 38 NodeId() = default; 39 NodeIdableton::link::NodeId40 NodeId(NodeIdArray rhs) 41 : NodeIdArray(std::move(rhs)) 42 { 43 } 44 randomableton::link::NodeId45 static NodeId random() 46 { 47 using namespace std; 48 49 random_device rd; 50 mt19937 gen(rd()); 51 // uint8_t not standardized for this type - use unsigned 52 uniform_int_distribution<unsigned> dist(33, 126); // printable ascii chars 53 54 NodeId nodeId; 55 generate( 56 nodeId.begin(), nodeId.end(), [&] { return static_cast<uint8_t>(dist(gen)); }); 57 return nodeId; 58 } 59 operator <<(std::ostream & stream,const NodeId & id)60 friend std::ostream& operator<<(std::ostream& stream, const NodeId& id) 61 { 62 return stream << std::string{id.cbegin(), id.cend()}; 63 } 64 65 template <typename It> toNetworkByteStream(const NodeId & nodeId,It out)66 friend It toNetworkByteStream(const NodeId& nodeId, It out) 67 { 68 return discovery::toNetworkByteStream(nodeId, std::move(out)); 69 } 70 71 template <typename It> fromNetworkByteStreamableton::link::NodeId72 static std::pair<NodeId, It> fromNetworkByteStream(It begin, It end) 73 { 74 using namespace std; 75 auto result = 76 discovery::Deserialize<NodeIdArray>::fromNetworkByteStream(move(begin), move(end)); 77 return make_pair(NodeId(move(result.first)), move(result.second)); 78 } 79 }; 80 81 } // namespace link 82 } // namespace ableton 83