Skip to content

Commit

Permalink
Return Ruby Encoding class instead of enum
Browse files Browse the repository at this point in the history
  • Loading branch information
krystof-k committed Feb 5, 2024
1 parent ce6afea commit c6f3933
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
10 changes: 9 additions & 1 deletion ext/compact_enc_det/compact_enc_det.cc
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#include <ruby.h>
#include "compact_enc_det/compact_enc_det/compact_enc_det.h"
#include "compact_enc_det/util/encodings/encodings.h"

// Define custom Ruby class CompactEncDet::DetectEncodingResult
// for the result of CompactEncDet.detect_encoding
Expand Down Expand Up @@ -75,10 +76,17 @@ static VALUE detect_encoding(int argc, VALUE *argv, VALUE self)
NIL_P(ignore_7bit_mail_encodings) ? false : RTEST(ignore_7bit_mail_encodings),
&bytes_consumed,
&is_reliable);

// Convert the encoding enum to string using MimeEncodingName
const char* encoding_mime_name = MimeEncodingName(encoding);
VALUE rb_encoding_mime_name = rb_str_new_cstr(encoding_mime_name);

// Find the Ruby Encoding class
VALUE rb_encoding = rb_funcall(rb_cEncoding, rb_intern("find"), 1, rb_encoding_mime_name);

// Return the detected encoding as a Ruby class
VALUE result = rb_class_new_instance(0, NULL, rb_cDetectEncodingResult);
rb_iv_set(result, "@encoding", rb_int_new(encoding));
rb_iv_set(result, "@encoding", rb_encoding);
rb_iv_set(result, "@bytes_consumed", rb_int_new(bytes_consumed));
rb_iv_set(result, "@is_reliable", is_reliable ? Qtrue : Qfalse);
return result;
Expand Down
2 changes: 1 addition & 1 deletion test/compact_enc_det_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ def test_detect_encoding_known_english
text = File.read("test/fixtures/utf-8.txt")
result = CompactEncDet.detect_encoding(text, text.bytesize)

assert_equal 22, result.encoding
assert_equal Encoding::UTF_8, result.encoding
assert_operator 0, :<, result.bytes_consumed
assert_equal true, result.is_reliable?
end
Expand Down

0 comments on commit c6f3933

Please sign in to comment.