libmoost
/home/mhx/git/github/libmoost/include/moost/murcl/response.hpp
Go to the documentation of this file.
00001 /* vim:set ts=3 sw=3 sts=3 et: */
00036 #ifndef FM_LAST_MOOST_MURCL_RESPONSE_HPP__
00037 #define FM_LAST_MOOST_MURCL_RESPONSE_HPP__
00038 
00039 #include<string>
00040 
00041 #include <curl/curl.h>
00042 
00043 namespace moost { namespace murcl {
00044 
00045 // This is a SHA1 of the string "response", used to validate a cast from void *
00046 char const RESPONSE_SHA1[] = "0ec6d150549780250a9772c06b619bcc46a0e560";
00047 size_t const RESPONSE_SHA1_LEN = sizeof(RESPONSE_SHA1)/sizeof(RESPONSE_SHA1[0]);
00048 
00052 class response
00053 {
00054 public:
00058    struct userdata // This class MUST be a POD type (yes, Ricky, A POD!)
00059    {
00064       char sha1_[RESPONSE_SHA1_LEN];
00066 
00067       std::string * pdata; // this is a pointer... pointers are PODs!
00068    };
00069 
00073    response()
00074    {
00075       strncpy(userdata_.sha1_, RESPONSE_SHA1, sizeof(userdata_.sha1_));
00076       userdata_.pdata = &data_;
00077    }
00078 
00097    static size_t callback( char *ptr, size_t size, size_t nmemb, void *userdata)
00098    {
00099       response::userdata * prud =
00100          reinterpret_cast<response::userdata *>(userdata);
00101 
00102       // make sure we have a valid object to play with
00103       if(!validate(prud))
00104       {
00105          // eek, something has gone pretty badly wrong - abort, abort abort!
00106          return CURL_READFUNC_ABORT;
00107       }
00108 
00109       // Not majorly efficient, but simple and given this is happening as a
00110       // callback in a network connection with latency I think simple trumps!
00111       size *= nmemb;
00112       prud->pdata->append(ptr, size);
00113 
00114       return size;
00115    }
00116 
00123    std::string const & get() const
00124    {
00125       return data_;
00126    }
00127 
00134    userdata * operator()()
00135    {
00136       return &userdata_;
00137    }
00138 
00139 private:
00140    static bool validate(userdata * prud)
00141    {
00142       // check we have a pointer to a valid response object
00143       return 0 == memcmp(prud, RESPONSE_SHA1, RESPONSE_SHA1_LEN);
00144    }
00145 
00146    std::string data_;
00147    userdata userdata_;
00148 
00149 };
00150 
00151 }}
00152 
00153 #endif // FM_LAST_MOOST_MURCL_RESPONSE_HPP__