int wav_header_encode(FILE *f, uint16_t format, uint16_t channels, uint32_t srate, uint16_t bps, size_t bytes) { int err; err = chunk_encode(f, "RIFF", 36 + bytes); if (err) return err; if (1 != fwrite("WAVE", 4, 1, f)) return ferror(f); err = chunk_encode(f, "fmt ", WAVE_FMT_SIZE); if (err) return err; err = write_u16(f, format); err |= write_u16(f, channels); err |= write_u32(f, srate); err |= write_u32(f, srate * channels * bps / 8); err |= write_u16(f, channels * bps / 8); err |= write_u16(f, bps); if (err) return err; return chunk_encode(f, "data", bytes); }
TEST(chunk, encode_message) { struct mbuf *mb = mbuf_alloc(1024); int err = 0; err |= chunk_encode(mb, (uint8_t *)"Wiki", 4); err |= chunk_encode(mb, (uint8_t *)"pedia", 5); err |= chunk_encode(mb, (uint8_t *)" in\r\n\r\nchunks.", 14); err |= chunk_encode(mb, (uint8_t *)NULL, 0); ASSERT_EQ(0, err); ASSERT_EQ(str_len(encoded_data), mb->end); ASSERT_TRUE(0 == memcmp(encoded_data, mb->buf, mb->end)); mem_deref(mb); }
static std::string streambuf_to_string (Streambuf& sb, bool final_chunk = false) { std::string s; buffer_append(s, chunk_encode(sb.data(), final_chunk)); return s; }
/** * \brief Encode binary data to Base64 string * * Encode binary data from \p in to Base64 string \p out * * \param in Reference to the binary buffer to be encoded * \param in_sz Size in bytes of \p in * \param out Pre-allocated string of length U_B64_LENGTH(in_sz) + 1 * \param out_sz U_B64_LENGTH(in_sz) + 1 * * \retval 0 on success * \retval ~0 on failure */ int u_b64_encode (const uint8_t *in, size_t in_sz, char *out, size_t out_sz) { size_t i, len; uint8_t buf[3]; char *pout; dbg_return_if (in == NULL, ~0); dbg_return_if (in_sz == 0, ~0); dbg_return_if (out == NULL, ~0); dbg_return_if (out_sz == 0, ~0); for (pout = out; in_sz; ) { /* Get three bytes from 'in'. */ for (len = 0, i = 0; i < 3; ++i) { if (in_sz && in_sz-- > 0) /* Avoid wrapping around in_sz. */ { buf[i] = *in++; ++len; } else buf[i] = '\0'; } /* See if we've harvested enough data to call the block encoder. */ if (len) { /* See if there's room at the output buffer to receive. */ if (out_sz >= 4) { chunk_encode(buf, pout, len); out_sz -= 4; pout += 4; } else return ~0; } } /* Possibly NUL-terminate out string. */ if (out_sz) *pout = '\0'; return 0; }