xref: /aosp_15_r20/external/rappor/client/cpp/encoder_demo.cc (revision 2abb31345f6c95944768b5222a9a5ed3fc68cc00)
1 // Copyright 2014 Google Inc. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 // Sample code for encoder.cc.
16 //
17 // This is the code in README.md.  It's here to make sure it actually builds
18 // and runs.
19 
20 #include <cassert>  // assert
21 
22 #include "encoder.h"
23 #include "openssl_hash_impl.h"
24 #include "unix_kernel_rand_impl.h"
25 
main(int argc,char ** argv)26 int main(int argc, char** argv) {
27   // Suppress unused variable warnings
28   (void) argc;
29   (void) argv;
30 
31   FILE* fp = fopen("/dev/urandom", "r");
32   rappor::UnixKernelRand irr_rand(fp);
33 
34   rappor::Deps deps(rappor::Md5, "client-secret", rappor::HmacSha256,
35                     irr_rand);
36   rappor::Params params(32,    // num_bits (k)
37                         2,     // num_hashes (h)
38                         128,   // num_cohorts (m)
39                         0.25,  // probability f for PRR
40                         0.75,  // probability p for IRR
41                         0.5);  // probability q for IRR
42 
43   const char* encoder_id = "metric-name";
44   rappor::Encoder encoder(encoder_id, params, deps);
45 
46   // Now use it to encode values.  The 'out' value can be sent over the
47   // network.
48   rappor::Bits out;
49   assert(encoder.EncodeString("foo", &out));  // returns false on error
50   printf("'foo' encoded with RAPPOR: %0x, cohort %d\n", out, encoder.cohort());
51 
52   // Raw bits
53   assert(encoder.EncodeBits(0x123, &out));  // returns false on error
54   printf("0x123 encoded with RAPPOR: %0x, cohort %d\n", out, encoder.cohort());
55 }
56 
57