Method: Krypt::Base64.encode

Defined in:
ext/krypt/core/krypt_b64.c

.Krypt::Base64.encode(data, [cols = nil]) ⇒ String

Encodes a String, or an object allowing conversion with to_str, in Base64 encoding. The optional cols is an Integer parameter that may be used to specify the line length of the resulting Base64 string. As the result is being constructed in chunks of 4 characters at a time, a value of cols that is not a multiple of 4 will result in line feeds after the next higher multiple of 4 - for example, if cols is specified as 22, then the result will have line feeds after every 24 characters of output.

Returns:

  • (String)


341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
# File 'ext/krypt/core/krypt_b64.c', line 341

static VALUE
krypt_base64_module_encode(int argc, VALUE *argv, VALUE self)
{
    VALUE data;
    VALUE cols = Qnil;
    VALUE ret;
    int c;
    size_t len;
    size_t result_len;
    uint8_t *bytes;
    uint8_t *result = NULL;

    rb_scan_args(argc, argv, "11", &data, &cols);

    if (NIL_P(data))
	rb_raise(eKryptBase64Error, "Data must not be nil");
    if (NIL_P(cols))
	c = -1;
    else
	c = NUM2INT(cols);

    StringValue(data);
    len = (size_t) RSTRING_LEN(data);
    bytes = (uint8_t *) RSTRING_PTR(data);

    if (krypt_base64_encode(bytes, len, c, &result, &result_len) == KRYPT_ERR)
	krypt_error_raise(eKryptBase64Error, "Processing the value failed.");

    ret = rb_str_new((const char *) result, result_len);
    rb_enc_associate(ret, rb_usascii_encoding());
    xfree(result);
    return ret;
}