1 // Copyright 2015 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 #include "unix_kernel_rand_impl.h"
16
17 #include <stdint.h> // uint64_t
18
19 namespace rappor {
20
21 const int kMaxBitWidth = 32; // also in encoder.cc
22
GetMask(float prob,int num_bits,Bits * mask_out) const23 bool UnixKernelRand::GetMask(float prob, int num_bits, Bits* mask_out) const {
24 uint8_t rand_buf[kMaxBitWidth];
25 size_t num_elems = fread(&rand_buf, sizeof(uint8_t), num_bits, fp_);
26 if (num_elems != static_cast<size_t>(num_bits)) { // fread error
27 return false;
28 }
29 uint8_t threshold_256 = static_cast<uint8_t>(prob * 256);
30
31 Bits mask = 0;
32 for (int i = 0; i < num_bits; ++i) {
33 uint8_t bit = (rand_buf[i] < threshold_256);
34 mask |= (bit << i);
35 }
36 *mask_out = mask;
37 return true;
38 }
39
40 } // namespace rappor
41