Search code examples
c++protocol-bufferspackaging

Preferred way of extracting and matching protobuf message typename from an Any package


I've been using Any to package dynamic messages for protobuf. On the receiver end, I use Any.type_url() to match the enclosed message types.

Correct me if I'm wrong, knowing that .GetDescriptor() is unavailable with Any, I still want to make the matching less of a clutter. I tried to extract the message type with brute force like this:

MyAny pouch;

// unpacking pouch
// Assume the message is "type.googleapis.com/MyTypeName"
....


const char* msgPrefix = "type.googleapis.com/";
auto lenPrefix = strlen(msgPrefix);
const std::string& msgURL = pouch.msg().type_url();
MamStr msgName = msgURL.substr(lenPrefix, msgURL.size());

if (msgName == "MyTypeName") {

   // do stuff ...

}

But I'm still wondering if there are cleaner way of skipping the prefix to get the "basename" of the type URL.

Thanks!


Solution

  • You could try

    std::string getBaseName(std::string const & url) { 
        return url.substr(url.find_last_of("/\\") + 1); 
    }
    

    if it suits you well.

    Although there are some cases, it may not explode it correctly.

    Let's say you have two params as basename: http://url.com/example/2

    This will get the latest, which is 2...

    If you are not looking for cross-platform support, you can always go for https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/splitpath-wsplitpath?view=vs-2019