token.h 2.62 KB
#ifndef OSDEV_COMPONENTS_MQTT_TOKEN_H
#define OSDEV_COMPONENTS_MQTT_TOKEN_H

// std
#include <ostream>
#include <string>

// paho
#include <MQTTAsync.h>

namespace osdev {
namespace components {
namespace mqtt {

/*!
 *  \brief The Token class defines an operation token
 */
class Token
{
public:
    /*! @brief  Construct an invalid token.
     *  The token number is -1 in that case. The client is undefined, in this case empty.
     */
    Token();

    /*! @brief  Constructs token for an operation originating from specific client wrapper.
     *  @param  clientId    - Identifies the client wrapper
     *  @param  tokenNr     - Identifies the operation done on that client.
     */
    Token( const std::string &clientId, std::int32_t tokenNr );

    /*! @return True when token has a valid token number, false otherwise. */
    bool isValid() const { return -1 == m_token; }

    /*! @return The operation token */
    const std::string& clientId() const { return m_clientId; }

    /*! @return The operation token */
    std::int32_t token() const { return m_token; }

    /*! @return True if Tokens have the same clientId and token number, false otherwise. */
    bool equals( const Token &rhs ) const;

    /*!
     *  @brief Token is ordered.
     *  First on lexical test of clientId and with same clientId on token number.
     */
    bool smallerThan( const Token &rhs ) const;

private:
    std::string  m_clientId;             ///< Identified the client
    std::int32_t m_token;                ///< Identifies the operation on that client.
};

/**
 *  @return True if Tokens have the same clientId and token number, false otherwise.
 */
inline bool operator==( const Token &lhs, const Token &rhs )
{
    return lhs.equals( rhs );
}

inline bool operator==( const Token &lhs, std::int32_t rhs )
{
    return lhs.token() == rhs;
}

inline bool operator==( std::int32_t lhs, const Token &rhs )
{
    return lhs == rhs;
}

template <typename TLeft, typename TRight>
inline bool operator!=( const TLeft &lhs, const TRight &rhs )
{
    return !( lhs == rhs );
}

/*!
 *  @return True if Token lhs is smaller than token rhs
 */
inline bool operator<( const Token &lhs, std::int32_t rhs )
{
    return lhs.token() < rhs;
}

inline bool operator<( std::int32_t lhs, const Token &rhs )
{
    return lhs < rhs.token();
}

inline bool operator<( const Token &lhs, const Token &rhs )
{
    return lhs.smallerThan( rhs );
}

/*!
 *  @brief  Stream operator for a Token
 */
std::ostream& operator<<( std::ostream &os, const Token &rhs );

}       // End namespace mqtt
}       // End namespace components
}       // End namespace osdev

#endif  // OSDEV_COMPONENTS_MQTT_TOKEN_H