1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 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 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968
//! Types and functions for working with encodings.
//!
//! This module defines 3 types for working with encodings, these types can
//! be converted back and forth with [`From`]/[`Into`] like so:
//! ``` text
//! Encoding <-> RbEncoding <-> Index
//! |______________________^
//! ```
//! Many functions that require an encoding take thier arguments as
//! `Into<RbEncoding>` or `Into<Index>` to ease working with the different
//! types. The type specified for the `Into` conversion hints at the type the
//! function nativly works with, and thus will avoid any conversion cost.
//!
//! [`Encoding`] and [`RbEncoding`] both implement [`TryConvert`] and
//! `Into<Value>` so can be used as parameters and return values in functions
//! bound to Ruby. Both convert from either an instance of `Encoding` or a
//! string of an encoding name, and convert to an instance of `Encoding`.
use std::{
convert::TryInto,
ffi::{CStr, CString},
fmt,
ops::{Deref, Range},
os::raw::{c_char, c_int},
ptr::{self, NonNull},
};
use rb_sys::{
rb_ascii8bit_encindex, rb_ascii8bit_encoding, rb_default_external_encoding,
rb_default_internal_encoding, rb_enc_ascget, rb_enc_associate_index, rb_enc_check,
rb_enc_codelen, rb_enc_codepoint_len, rb_enc_compatible, rb_enc_copy, rb_enc_default_external,
rb_enc_default_internal, rb_enc_fast_mbclen, rb_enc_find, rb_enc_find_index,
rb_enc_from_encoding, rb_enc_from_index, rb_enc_get_index, rb_enc_mbclen,
rb_enc_precise_mbclen, rb_enc_set_index, rb_enc_to_index, rb_enc_uint_chr, rb_encoding,
rb_filesystem_encindex, rb_filesystem_encoding, rb_find_encoding, rb_locale_encindex,
rb_locale_encoding, rb_to_encoding, rb_to_encoding_index, rb_usascii_encindex,
rb_usascii_encoding, rb_utf8_encindex, rb_utf8_encoding,
};
use crate::{
class,
error::{protect, Error},
exception,
object::Object,
r_string::RString,
try_convert::TryConvert,
value::{private, NonZeroValue, ReprValue, Value, QNIL},
};
/// Wrapper type for a Value known to be an instance of Ruby's Encoding class.
///
/// This is the representation of an encoding exposed to Ruby code.
///
/// All [`Value`] methods should be available on this type through [`Deref`],
/// but some may be missed by this documentation.
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct Encoding(NonZeroValue);
impl Encoding {
/// Return `Some(Encoding)` if `val` is an `Encoding`, `None` otherwise.
///
/// # Examples
///
/// ```
/// use magnus::{eval, encoding::Encoding};
/// # let _cleanup = unsafe { magnus::embed::init() };
///
/// assert!(Encoding::from_value(eval("Encoding::US_ASCII").unwrap()).is_some());
/// assert!(Encoding::from_value(eval("nil").unwrap()).is_none());
/// ```
#[inline]
pub fn from_value(val: Value) -> Option<Self> {
unsafe {
val.is_kind_of(class::encoding())
.then(|| Self(NonZeroValue::new_unchecked(val)))
}
}
/// Returns the default internal encoding as a Ruby object.
///
/// This is the encoding used for anything out-of-process, such as reading
/// from files or sockets.
pub fn default_external() -> Self {
Self::from_value(Value::new(unsafe { rb_enc_default_external() })).unwrap()
}
/// Returns the default external encoding as a Ruby object.
///
/// If set, any out-of-process data is transcoded from the default external
/// encoding to the default internal encoding.
pub fn default_internal() -> Option<Self> {
Self::from_value(Value::new(unsafe { rb_enc_default_internal() }))
}
}
impl Deref for Encoding {
type Target = Value;
fn deref(&self) -> &Self::Target {
self.0.get_ref()
}
}
impl fmt::Display for Encoding {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", unsafe { self.to_s_infallible() })
}
}
impl fmt::Debug for Encoding {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.deref().inspect())
}
}
impl From<Encoding> for Index {
fn from(val: Encoding) -> Self {
let i = unsafe { rb_to_encoding_index(val.as_rb_value()) };
if i == -1 {
panic!("got encoding index -1");
}
Index(i)
}
}
impl From<Encoding> for RbEncoding {
fn from(val: Encoding) -> Self {
let ptr = unsafe { rb_find_encoding(val.as_rb_value()) };
RbEncoding::new(ptr).expect("got NULL rb_encoding")
}
}
impl From<Encoding> for Value {
fn from(val: Encoding) -> Self {
*val
}
}
impl Object for Encoding {}
unsafe impl private::ReprValue for Encoding {
fn to_value(self) -> Value {
*self
}
unsafe fn from_value_unchecked(val: Value) -> Self {
Self(NonZeroValue::new_unchecked(val))
}
}
impl ReprValue for Encoding {}
impl TryConvert for Encoding {
fn try_convert(val: Value) -> Result<Self, Error> {
if let Some(enc) = Self::from_value(val) {
return Ok(enc);
}
RbEncoding::try_convert(val).map(Into::into)
}
}
/// Ruby's internal encoding type.
///
/// This type contains the data for an encoding, and is used with operations
/// such as converting a string from one encoding to another, or reading a
/// string character by character.
#[repr(transparent)]
pub struct RbEncoding(NonNull<rb_encoding>);
impl RbEncoding {
fn new(inner: *mut rb_encoding) -> Option<Self> {
NonNull::new(inner).map(Self)
}
/// Returns the encoding that represents ASCII-8BIT a.k.a. binary.
pub fn ascii8bit() -> Self {
Self::new(unsafe { rb_ascii8bit_encoding() }).unwrap()
}
/// Returns the encoding that represents UTF-8.
pub fn utf8() -> Self {
Self::new(unsafe { rb_utf8_encoding() }).unwrap()
}
/// Returns the encoding that represents US-ASCII.
pub fn usascii() -> Self {
Self::new(unsafe { rb_usascii_encoding() }).unwrap()
}
/// Returns the encoding that represents the process' current locale.
///
/// This is dynamic. If you change the process' locale that should also
/// change the return value of this function.
pub fn locale() -> Self {
Self::new(unsafe { rb_locale_encoding() }).unwrap()
}
/// Returns the filesystem encoding.
///
/// This is the encoding that Ruby expects data from the OS' file system
/// to be encoded as, such as directory names.
pub fn filesystem() -> Self {
Self::new(unsafe { rb_filesystem_encoding() }).unwrap()
}
/// Returns the default external encoding.
///
/// This is the encoding used for anything out-of-process, such as reading
/// from files or sockets.
pub fn default_external() -> Self {
Self::new(unsafe { rb_default_external_encoding() }).unwrap()
}
/// Returns the default internal encoding.
///
/// If set, any out-of-process data is transcoded from the default external
/// encoding to the default internal encoding.
pub fn default_internal() -> Option<Self> {
Self::new(unsafe { rb_default_internal_encoding() })
}
/// Returns the encoding with the name or alias `name`.
///
/// # Examples
///
/// ```
/// use magnus::{eval, encoding::RbEncoding};
/// # let _cleanup = unsafe { magnus::embed::init() };
///
/// assert_eq!(RbEncoding::find("UTF-8").unwrap().name(), "UTF-8");
/// assert_eq!(RbEncoding::find("BINARY").unwrap().name(), "ASCII-8BIT");
/// ```
pub fn find(name: &str) -> Option<Self> {
let name = CString::new(name).unwrap();
let ptr = unsafe { rb_enc_find(name.as_ptr()) };
Self::new(ptr)
}
pub(crate) fn as_ptr(&self) -> *mut rb_encoding {
self.0.as_ptr()
}
/// Returns the canonical name of the encoding.
///
/// # Examples
///
/// ```
/// use magnus::{eval, encoding::RbEncoding};
/// # let _cleanup = unsafe { magnus::embed::init() };
///
/// assert_eq!(RbEncoding::utf8().name(), "UTF-8");
/// assert_eq!(RbEncoding::find("UTF-16").unwrap().name(), "UTF-16");
/// ```
///
/// # Panics
///
/// Panics if the name is not valid UTF-8. Encoding names are expected to
/// be ASCII only.
pub fn name(&self) -> &str {
unsafe { CStr::from_ptr(self.0.as_ref().name).to_str().unwrap() }
}
/// Returns the minimum number of bytes the encoding needs to represent a
/// single character.
///
/// # Examples
///
/// ```
/// use magnus::{eval, encoding::RbEncoding};
/// # let _cleanup = unsafe { magnus::embed::init() };
///
/// assert_eq!(RbEncoding::usascii().mbminlen(), 1);
/// assert_eq!(RbEncoding::utf8().mbminlen(), 1);
/// ```
pub fn mbminlen(&self) -> usize {
unsafe { self.0.as_ref().min_enc_len as usize }
}
/// Returns the maximum number of bytes the encoding may need to represent
/// a single character.
///
/// # Examples
///
/// ```
/// use magnus::{eval, encoding::RbEncoding};
/// # let _cleanup = unsafe { magnus::embed::init() };
///
/// assert_eq!(RbEncoding::usascii().mbmaxlen(), 1);
/// assert_eq!(RbEncoding::utf8().mbmaxlen(), 4);
/// ```
pub fn mbmaxlen(&self) -> usize {
unsafe { self.0.as_ref().max_enc_len as usize }
}
/// Returns the number of bytes of the first character in `slice`.
///
/// If the first byte of `slice` is mid way through a character this will
/// return the number of bytes until the next character boundry.
///
/// If the slice ends before the last byte of the character this will
/// return the number of bytes until the end of the slice.
///
/// See also [`fast_mbclen`](RbEncoding::fast_mbclen) and
/// [`precise_mbclen`](RbEncoding::precise_mbclen).
///
/// # Examples
///
/// ```
/// use magnus::{eval, encoding::{EncodingCapable, RbEncoding}, RString};
/// # let _cleanup = unsafe { magnus::embed::init() };
///
/// let s = RString::new("🦀 café");
/// let encoding: RbEncoding = s.enc_get().into();
/// let mut chars = 0;
///
/// unsafe {
/// let mut bytes = s.as_slice();
/// assert_eq!(bytes.len(), 10);
///
/// while !bytes.is_empty() {
/// chars += 1;
/// let len = encoding.mbclen(bytes);
/// bytes = &bytes[len..];
/// }
/// }
///
/// assert_eq!(chars, 6);
/// ```
pub fn mbclen(&self, slice: &[u8]) -> usize {
let Range { start: p, end: e } = slice.as_ptr_range();
unsafe { rb_enc_mbclen(p as *const c_char, e as *const c_char, self.as_ptr()) as usize }
}
/// Returns the number of bytes of the first character in `slice`.
///
/// If the first byte of `slice` is mid way through a character this will
/// return the number of bytes until the next character boundry.
///
/// If the slice ends before the last byte of the character this will
/// return the theoretical number of bytes until the end of the character,
/// which will be past the end of the slice. If the string has been read
/// from an IO source this may indicate more data needs to be read.
///
/// See also [`mbclen`](RbEncoding::mbclen) and
/// [`precise_mbclen`](RbEncoding::precise_mbclen).
///
/// # Examples
///
/// ```
/// use magnus::{eval, encoding::{EncodingCapable, RbEncoding}, RString};
/// # let _cleanup = unsafe { magnus::embed::init() };
///
/// let s = RString::new("🦀 café");
/// let encoding: RbEncoding = s.enc_get().into();
/// let mut chars = 0;
///
/// unsafe {
/// let mut bytes = s.as_slice();
/// assert_eq!(bytes.len(), 10);
///
/// while !bytes.is_empty() {
/// chars += 1;
/// let len = encoding.fast_mbclen(bytes);
/// bytes = &bytes[len..];
/// }
/// }
///
/// assert_eq!(chars, 6);
/// ```
pub fn fast_mbclen(&self, slice: &[u8]) -> usize {
let Range { start: p, end: e } = slice.as_ptr_range();
unsafe {
rb_enc_fast_mbclen(p as *const c_char, e as *const c_char, self.as_ptr()) as usize
}
}
/// Returns the number of bytes of the first character in `slice`.
///
/// See also [`mbclen`](RbEncoding::mbclen) and
/// [`fast_mbclen`](RbEncoding::fast_mbclen).
///
/// # Examples
///
/// ```
/// use magnus::{eval, encoding::{EncodingCapable, MbcLen, RbEncoding}, RString};
/// # let _cleanup = unsafe { magnus::embed::init() };
///
/// let s = RString::new("🦀 café");
/// let encoding: RbEncoding = s.enc_get().into();
/// let mut chars = 0;
///
/// unsafe {
/// let mut bytes = s.as_slice();
/// assert_eq!(bytes.len(), 10);
///
/// while !bytes.is_empty() {
/// chars += 1;
/// match encoding.precise_mbclen(bytes) {
/// MbcLen::CharFound(len) => bytes = &bytes[len..],
/// MbcLen::NeedMore(len) => panic!("Met end of string expecting {} bytes", len),
/// MbcLen::Invalid => panic!("corrupted string"),
/// }
/// }
/// }
///
/// assert_eq!(chars, 6);
/// ```
pub fn precise_mbclen(&self, slice: &[u8]) -> MbcLen {
let Range { start: p, end: e } = slice.as_ptr_range();
let r =
unsafe { rb_enc_precise_mbclen(p as *const c_char, e as *const c_char, self.as_ptr()) };
if 0 < r {
MbcLen::CharFound(r as usize)
} else if r < -1 {
MbcLen::NeedMore((-1 - r) as usize)
} else if r == -1 {
MbcLen::Invalid
} else {
unreachable!()
}
}
/// If the first character in `slice` is included in ASCII return it and
/// its encoded length in `slice`, otherwise returns None.
///
/// Typically the length will be 1, but some encodings such as UTF-16 will
/// encode ASCII characters in 2 bytes.
///
/// # Examples
///
/// ```
/// use magnus::{eval, encoding::{EncodingCapable, RbEncoding}, RString};
/// # let _cleanup = unsafe { magnus::embed::init() };
///
/// let s = RString::new("example");
/// let encoding: RbEncoding = s.enc_get().into();
/// let mut chars = Vec::new();
///
/// unsafe {
/// let mut bytes = s.as_slice();
///
/// while !bytes.is_empty() {
/// match encoding.ascget(bytes) {
/// Some((char, len)) => {
/// chars.push(char);
/// bytes = &bytes[len..];
/// }
/// None => panic!("string not ASCII"),
/// }
/// }
/// }
///
/// assert_eq!(chars, [101, 120, 97, 109, 112, 108, 101]);
/// ```
pub fn ascget(&self, slice: &[u8]) -> Option<(u8, usize)> {
let Range { start: p, end: e } = slice.as_ptr_range();
let mut len = 0;
let c = unsafe {
rb_enc_ascget(
p as *const c_char,
e as *const c_char,
&mut len as *mut _,
self.as_ptr(),
)
};
if len == 0 {
panic!("{:?}", slice);
}
(c > -1).then(|| (c as u8, len as usize))
}
/// Returns the codepoint and length in bytes of the first character in
/// `slice`.
///
/// # Examples
///
/// ```
/// use magnus::{eval, encoding::{EncodingCapable, RbEncoding}, RString};
/// # let _cleanup = unsafe { magnus::embed::init() };
///
/// let s = RString::new("🦀 café");
/// let encoding: RbEncoding = s.enc_get().into();
/// let mut codepoints = Vec::new();
///
/// unsafe {
/// let mut bytes = s.as_slice();
///
/// while !bytes.is_empty() {
/// let (codepoint, len) = encoding.codepoint_len(bytes).unwrap();
/// codepoints.push(codepoint);
/// bytes = &bytes[len..];
/// }
/// }
///
/// assert_eq!(codepoints, [129408, 32, 99, 97, 102, 233]);
/// ```
pub fn codepoint_len(&self, slice: &[u8]) -> Result<(u32, usize), Error> {
let Range { start: p, end: e } = slice.as_ptr_range();
let mut len = 0;
let mut c = 0;
protect(|| {
c = unsafe {
rb_enc_codepoint_len(
p as *const c_char,
e as *const c_char,
&mut len as *mut _,
self.as_ptr(),
)
};
QNIL
})?;
Ok((c as u32, len as usize))
}
/// Returns the number of bytes required to represent the code point `code`
/// in the encoding of `self`.
///
/// # Examples
///
/// ```
/// use magnus::{eval, encoding::RbEncoding};
/// # let _cleanup = unsafe { magnus::embed::init() };
///
/// assert_eq!(RbEncoding::utf8().codelen(97).unwrap(), 1);
/// assert_eq!(RbEncoding::utf8().codelen(129408).unwrap(), 4);
/// ```
pub fn codelen(&self, code: u32) -> Result<usize, Error> {
let code = code
.try_into()
.map_err(|e: <usize as TryInto<c_int>>::Error| {
Error::new(exception::arg_error(), e.to_string())
})?;
let mut len = 0;
protect(|| {
unsafe { len = rb_enc_codelen(code, self.as_ptr()) as usize }
QNIL
})?;
Ok(len)
}
/// Encode the codepoint `code` as a series of bytes in the encoding `self`
/// and return the result as a Ruby string.
///
/// # Examples
///
/// ```
/// use magnus::{eval, encoding::RbEncoding};
/// # let _cleanup = unsafe { magnus::embed::init() };
///
/// let c = RbEncoding::usascii().chr(97).unwrap();
/// let res: bool = eval!(r#"c == "a""#, c).unwrap();
/// assert!(res);
/// ```
///
/// ```
/// use magnus::{eval, encoding::RbEncoding};
/// # let _cleanup = unsafe { magnus::embed::init() };
///
/// let c = RbEncoding::utf8().chr(129408).unwrap();
/// let res: bool = eval!(r#"c == "🦀""#, c).unwrap();
/// assert!(res);
/// ```
pub fn chr(&self, code: u32) -> Result<RString, Error> {
protect(|| unsafe {
RString::from_rb_value_unchecked(rb_enc_uint_chr(code, self.as_ptr()))
})
}
/// Returns `true` if the first character in `slice` is a newline in the
/// encoding `self`, `false` otherwise.
///
/// # Examples
///
/// ```
/// use magnus::{eval, encoding::RbEncoding};
/// # let _cleanup = unsafe { magnus::embed::init() };
///
/// assert!(RbEncoding::utf8().is_mbc_newline(&[10]));
/// assert!(!RbEncoding::utf8().is_mbc_newline(&[32]));
/// ```
pub fn is_mbc_newline(&self, slice: &[u8]) -> bool {
let Range { start: p, end: e } = slice.as_ptr_range();
unsafe {
self.0.as_ref().is_mbc_newline.unwrap()(p as *const _, e as *const _, self.as_ptr())
!= 0
}
}
/// Returns whether the given codepoint `code` is of the character type
/// `ctype` in the encoding `self`.
///
/// # Examples
///
/// ```
/// use magnus::{eval, encoding::{CType, RbEncoding}};
/// # let _cleanup = unsafe { magnus::embed::init() };
///
/// assert!(RbEncoding::utf8().is_code_ctype(9, CType::Space)); // "\t"
/// assert!(RbEncoding::utf8().is_code_ctype(32, CType::Space)); // " "
/// assert!(!RbEncoding::utf8().is_code_ctype(65, CType::Space)); // "A"
/// assert!(RbEncoding::utf8().is_code_ctype(65, CType::Alnum)); // "A"
/// assert!(RbEncoding::utf8().is_code_ctype(65, CType::Upper)); // "A"
/// ```
pub fn is_code_ctype(&self, code: u32, ctype: CType) -> bool {
unsafe { self.0.as_ref().is_code_ctype.unwrap()(code, ctype as _, self.as_ptr()) != 0 }
}
}
/// Return value for [`RbEncoding::precise_mbclen`].
pub enum MbcLen {
/// Found a valid char, value is the char's length.
CharFound(usize),
/// The slice ended before the end of the current char. Value is the
/// theoretical total length of the char.
NeedMore(usize),
/// The bytes at the start of the slice are not valid for the encoding.
Invalid,
}
/// A character type.
#[repr(u32)]
#[derive(Debug, Copy, Clone)]
pub enum CType {
/// Newline.
Newline = 0,
/// Alphabetical.
Alpha = 1,
/// Blank.
Blank = 2,
/// Control.
Cntrl = 3,
/// Digit.
Digit = 4,
/// Graph.
Graph = 5,
/// Lowercase.
Lower = 6,
/// Printable.
Print = 7,
/// Punctuation.
Punct = 8,
/// Whitespace.
Space = 9,
/// Uppercase.
Upper = 10,
/// Xdigit.
Xdigit = 11,
/// Word.
Word = 12,
/// Alphanumeric.
Alnum = 13,
/// ASCII.
Ascii = 14,
}
impl From<RbEncoding> for Encoding {
fn from(val: RbEncoding) -> Self {
Encoding::from_value(Value::new(unsafe { rb_enc_from_encoding(val.as_ptr()) })).unwrap()
}
}
impl From<RbEncoding> for Index {
fn from(val: RbEncoding) -> Self {
Index(unsafe { rb_enc_to_index(val.as_ptr()) })
}
}
impl From<RbEncoding> for Value {
fn from(val: RbEncoding) -> Self {
*Encoding::from(val)
}
}
impl TryConvert for RbEncoding {
fn try_convert(val: Value) -> Result<Self, Error> {
let mut ptr = ptr::null_mut();
protect(|| {
ptr = unsafe { rb_to_encoding(val.as_rb_value()) };
QNIL
})?;
Ok(Self::new(ptr).unwrap())
}
}
/// The index of an encoding in Ruby's internal encodings table.
///
/// This is the type Ruby uses to label encoding capable types, so is used with
/// operations that require reading or setting that label.
#[derive(Clone, Copy, Eq, PartialEq)]
#[repr(transparent)]
pub struct Index(c_int);
impl Index {
/// Returns the index for ASCII-8BIT a.k.a. binary.
pub fn ascii8bit() -> Self {
Self(unsafe { rb_ascii8bit_encindex() })
}
/// Returns the index for UTF-8.
pub fn utf8() -> Self {
Self(unsafe { rb_utf8_encindex() })
}
/// Returns the index for US-ASCII.
pub fn usascii() -> Self {
Self(unsafe { rb_usascii_encindex() })
}
/// Returns the index for the process' current locale encoding.
///
/// This is dynamic. If you change the process' locale that should also
/// change the return value of this function.
pub fn locale() -> Self {
Self(unsafe { rb_locale_encindex() })
}
/// Returns the index for filesystem encoding.
///
/// This is the encoding that Ruby expects data from the OS' file system
/// to be encoded as, such as directory names.
pub fn filesystem() -> Self {
Self(unsafe { rb_filesystem_encindex() })
}
/// Returns the index for the encoding with the name or alias `name`.
///
/// # Examples
///
/// ```
/// use magnus::{eval, encoding};
/// # let _cleanup = unsafe { magnus::embed::init() };
///
/// assert!(encoding::Index::find("UTF-8").is_ok());
/// assert!(encoding::Index::find("BINARY").is_ok());
/// assert!(encoding::Index::find("none").is_err());
/// ```
pub fn find(name: &str) -> Result<Self, Error> {
let name = CString::new(name).unwrap();
let mut i = 0;
protect(|| {
i = unsafe { rb_enc_find_index(name.as_ptr()) };
QNIL
})?;
if i == -1 {
return Err(Error::new(
exception::runtime_error(),
format!("Encoding {:?} exists, but can not be loaded", name),
));
}
Ok(Index(i))
}
pub(crate) fn to_int(self) -> c_int {
self.0
}
}
impl From<Index> for RbEncoding {
fn from(val: Index) -> Self {
RbEncoding::new(unsafe { rb_enc_from_index(val.to_int()) }).expect("no encoding for index")
}
}
impl TryConvert for Index {
fn try_convert(val: Value) -> Result<Self, Error> {
let i = unsafe { rb_to_encoding_index(val.as_rb_value()) };
if i == -1 && RString::from_value(val).is_some() {
return Err(Error::new(
exception::runtime_error(),
format!("ArgumentError: unknown encoding name - {}", val),
));
} else if i == -1 {
return RString::try_convert(val)?.try_convert();
}
Ok(Index(i))
}
}
/// Possible states of how a string matches its encoding.
#[repr(u32)]
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum Coderange {
/// It is unknown if the string is valid for its encoding.
Unknown = 0,
/// The string is entirely within the 0 to 127 ASCII range.
SevenBit = 1048576,
/// The string is valid for its encoding.
Valid = 2097152,
/// The string holds values that are invalid for its encoding.
Broken = 3145728,
}
/// Trait that marks Ruby types cable of having an encoding.
pub trait EncodingCapable: Deref<Target = Value> {
/// Get the encoding of `self`.
///
/// # Examples
///
/// ```
/// use magnus::{encoding::{self, EncodingCapable}, RString};
/// # let _cleanup = unsafe { magnus::embed::init() };
///
/// assert!(RString::new("example").enc_get() == encoding::Index::utf8());
/// ```
fn enc_get(&self) -> Index {
let i = unsafe { rb_enc_get_index(self.as_rb_value()) };
if i == -1 {
panic!("{} not encoding capable", self.deref());
}
Index(i)
}
/// Set `self`'s encoding.
///
/// Returns `Err` if `self` is frozen or the encoding can not be loaded.
///
/// See also [`EncodingCapable::enc_associate`].
///
/// # Examples
///
/// ```
/// use magnus::{encoding::{self, EncodingCapable}, RString};
/// # let _cleanup = unsafe { magnus::embed::init() };
///
/// let s = RString::new("example");
/// assert!(s.enc_get() == encoding::Index::utf8());
/// s.enc_set(encoding::Index::usascii());
/// assert!(s.enc_get() == encoding::Index::usascii());
/// ```
fn enc_set<T>(&self, enc: T) -> Result<(), Error>
where
T: Into<Index>,
{
protect(|| {
unsafe { rb_enc_set_index(self.as_rb_value(), enc.into().to_int()) };
QNIL
})?;
Ok(())
}
/// Set `self`'s encoding, along with performing additional fix-up `self`'s
/// contents.
///
/// For example, Ruby's strings contain an additional terminating null byte
/// hidden from Ruby, but allowing for easy c string interop. This method
/// will adjust the length of that terminating char depending on the
/// encoding.
///
/// Returns `Err` if `self` is frozen or the encoding can not be loaded.
///
/// # Examples
///
/// ```
/// use magnus::{encoding::{self, EncodingCapable}, RString};
/// # let _cleanup = unsafe { magnus::embed::init() };
///
/// let s = RString::new("example");
/// assert!(s.enc_get() == encoding::Index::utf8());
/// s.enc_associate(encoding::Index::usascii());
/// assert!(s.enc_get() == encoding::Index::usascii());
/// ```
fn enc_associate<T>(&self, enc: T) -> Result<(), Error>
where
T: Into<Index>,
{
protect(|| {
Value::new(unsafe { rb_enc_associate_index(self.as_rb_value(), enc.into().to_int()) })
})?;
Ok(())
}
}
/// Returns the common encoding between `v1` and `v2`, or `None`.
///
/// Returns `None` if there is no common compatible encoding.
///
/// See also [`check`].
///
/// # Examples
///
/// ```
/// use magnus::{encoding::{self, EncodingCapable}, RString};
/// # let _cleanup = unsafe { magnus::embed::init() };
///
/// let a = RString::new("a");
/// let b = RString::new("b");
///
/// assert!(a.enc_get() == encoding::Index::utf8());
/// b.enc_set(encoding::Index::usascii());
///
/// assert_eq!(encoding::compatible(a, b).unwrap().name(), "UTF-8");
/// ```
pub fn compatible<T, U>(v1: T, v2: U) -> Option<RbEncoding>
where
T: EncodingCapable,
U: EncodingCapable,
{
RbEncoding::new(unsafe { rb_enc_compatible(v1.as_rb_value(), v2.as_rb_value()) })
}
/// Returns the common encoding between `v1` and `v2`, or `Err`.
///
/// Returns `Err` if there is no common compatible encoding.
///
/// See also [`compatible`].
///
/// # Examples
///
/// ```
/// use magnus::{encoding::{self, EncodingCapable}, RString};
/// # let _cleanup = unsafe { magnus::embed::init() };
///
/// let a = RString::new("a");
/// let b = RString::new("b");
///
/// assert!(a.enc_get() == encoding::Index::utf8());
/// b.enc_set(encoding::Index::usascii());
///
/// assert_eq!(encoding::check(a, b).unwrap().name(), "UTF-8");
/// ```
pub fn check<T, U>(v1: T, v2: U) -> Result<RbEncoding, Error>
where
T: EncodingCapable,
U: EncodingCapable,
{
let mut ptr = ptr::null_mut();
protect(|| {
ptr = unsafe { rb_enc_check(v1.as_rb_value(), v2.as_rb_value()) };
QNIL
})?;
Ok(RbEncoding::new(ptr).unwrap())
}
/// Compies the encoding from `src` to `dst`.
///
/// This does not reconcode `dst.`
///
/// Similar to [`EncodingCapable::enc_associate`], except takes the encoding of
/// `src` rather than an encoding object or index.
///
/// # Examples
///
/// ```
/// use magnus::{encoding::{self, EncodingCapable}, RString};
/// # let _cleanup = unsafe { magnus::embed::init() };
///
/// let a = RString::new("a");
/// assert!(a.enc_get() == encoding::Index::utf8());
/// let b = RString::new("b");
/// assert!(b.enc_get() == encoding::Index::utf8());
///
/// a.enc_set(encoding::Index::usascii());
/// encoding::copy(b, a).unwrap();
///
/// assert!(b.enc_get() == encoding::Index::usascii());
/// ```
pub fn copy<T, U>(dst: T, src: U) -> Result<(), Error>
where
T: EncodingCapable,
U: EncodingCapable,
{
protect(|| {
unsafe { rb_enc_copy(dst.as_rb_value(), src.as_rb_value()) };
QNIL
})?;
Ok(())
}