Skip to content

Commit 05ce3be

Browse files
committed
Optimize ExpanderXmd to copy whole slices
1 parent adab831 commit 05ce3be

File tree

1 file changed

+27
-14
lines changed
  • hash2curve/src/hash2field/expand_msg

1 file changed

+27
-14
lines changed

hash2curve/src/hash2field/expand_msg/xmd.rs

Lines changed: 27 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -108,18 +108,14 @@ where
108108
HashT: BlockSizeUser + Default + FixedOutput + HashMarker,
109109
HashT::OutputSize: IsLessOrEqual<HashT::BlockSize, Output = True>,
110110
{
111-
fn fill_bytes(&mut self, okm: &mut [u8]) -> Result<usize> {
112-
let mut read_bytes = 0;
111+
fn fill_bytes(&mut self, mut okm: &mut [u8]) -> Result<usize> {
112+
if self.remaining == 0 {
113+
return Err(Error);
114+
}
113115

114-
for b in okm {
115-
if self.remaining == 0 {
116-
if read_bytes == 0 {
117-
return Err(Error);
118-
} else {
119-
return Ok(read_bytes);
120-
}
121-
}
116+
let mut read_bytes = 0;
122117

118+
while self.remaining != 0 {
123119
if self.offset == self.b_vals.len() {
124120
self.index += 1;
125121
self.offset = 0;
@@ -138,10 +134,27 @@ where
138134
self.b_vals = b_vals.finalize_fixed();
139135
}
140136

141-
*b = self.b_vals[self.offset];
142-
self.offset += 1;
143-
self.remaining -= 1;
144-
read_bytes += 1;
137+
let bytes_to_read = self
138+
.remaining
139+
.min(okm.len().try_into().unwrap_or(u16::MAX))
140+
.min(
141+
(self.b_vals.len() - self.offset)
142+
.try_into()
143+
.unwrap_or(u16::MAX),
144+
);
145+
146+
if bytes_to_read == 0 {
147+
return Ok(read_bytes);
148+
}
149+
150+
okm[..bytes_to_read.into()].copy_from_slice(
151+
&self.b_vals[self.offset..self.offset + usize::from(bytes_to_read)],
152+
);
153+
okm = &mut okm[bytes_to_read.into()..];
154+
155+
self.offset += usize::from(bytes_to_read);
156+
self.remaining -= bytes_to_read;
157+
read_bytes += usize::from(bytes_to_read);
145158
}
146159

147160
Ok(read_bytes)

0 commit comments

Comments
 (0)