MCPcopy Create free account
hub / github.com/RustCrypto/formats / encode

Method encode

base64ct/src/encoding.rs:187–234  ·  view source on GitHub ↗
(src: &[u8], dst: &'a mut [u8])

Source from the content-addressed store, hash-verified

185 }
186
187 fn encode<'a>(src: &[u8], dst: &'a mut [u8]) -> Result<&'a str, InvalidLengthError> {
188 let elen = match encoded_len_inner(src.len(), T::PADDED) {
189 Some(v) => v,
190 None => return Err(InvalidLengthError),
191 };
192
193 if elen > dst.len() {
194 return Err(InvalidLengthError);
195 }
196
197 let dst = &mut dst[..elen];
198
199 let mut src_chunks = src.chunks_exact(3);
200 let mut dst_chunks = dst.chunks_exact_mut(4);
201
202 for (s, d) in (&mut src_chunks).zip(&mut dst_chunks) {
203 Self::encode_3bytes(s, d);
204 }
205
206 let src_rem = src_chunks.remainder();
207
208 if T::PADDED {
209 if let Some(dst_rem) = dst_chunks.next() {
210 let mut tmp = [0u8; 3];
211 tmp[..src_rem.len()].copy_from_slice(src_rem);
212 Self::encode_3bytes(&tmp, dst_rem);
213
214 let flag = src_rem.len() == 1;
215 let mask = (flag as u8).wrapping_sub(1);
216 dst_rem[2] = (dst_rem[2] & mask) | (PAD & !mask);
217 dst_rem[3] = PAD;
218 }
219 } else {
220 let dst_rem = dst_chunks.into_remainder();
221
222 let mut tmp_in = [0u8; 3];
223 let mut tmp_out = [0u8; 4];
224 tmp_in[..src_rem.len()].copy_from_slice(src_rem);
225 Self::encode_3bytes(&tmp_in, &mut tmp_out);
226 dst_rem.copy_from_slice(&tmp_out[..dst_rem.len()]);
227 }
228
229 debug_assert!(str::from_utf8(dst).is_ok());
230
231 // SAFETY: values written by `encode_3bytes` are valid one-byte UTF-8 chars
232 #[allow(unsafe_code)]
233 Ok(unsafe { str::from_utf8_unchecked(dst) })
234 }
235
236 #[cfg(feature = "alloc")]
237 fn encode_string(input: &[u8]) -> String {

Callers

nothing calls this directly

Calls 3

encoded_len_innerFunction · 0.85
lenMethod · 0.45
nextMethod · 0.45

Tested by

no test coverage detected