Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add UnicodeFuncs with safe-to-implement traits #197

Merged
merged 26 commits into from
Sep 6, 2023
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,11 @@ jobs:
env:
RUST_BACKTRACE: 1

- name: Cargo check no-default-features
run: cargo check --no-default-features
env:
RUST_BACKTRACE: 1

linux-ci-static:
name: stable, Linux, static linking, no pkg-config
runs-on: ubuntu-latest
Expand Down
13 changes: 8 additions & 5 deletions harfbuzz/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,13 @@ categories = ["text-processing"]
path = "../harfbuzz-sys"
version = "0.5.0"
default-features = false
optional = true

[features]
default = ["coretext", "directwrite", "freetype"]
bundled = ["harfbuzz-sys/bundled"]
coretext = ["harfbuzz-sys/coretext"]
directwrite = ["harfbuzz-sys/directwrite"]
freetype = ["harfbuzz-sys/freetype"]
default = ["coretext", "directwrite", "freetype", "harfbuzz-sys", "std"]
bundled = ["harfbuzz-sys?/bundled"]
coretext = ["harfbuzz-sys?/coretext"]
directwrite = ["harfbuzz-sys?/directwrite"]
freetype = ["harfbuzz-sys?/freetype"]
harfbuzz-sys = ["dep:harfbuzz-sys"]
std = []
11 changes: 7 additions & 4 deletions harfbuzz/src/blob.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,12 @@
// except according to those terms.

use crate::sys;
use std::marker::PhantomData;
use std::os::raw::{c_char, c_uint, c_void};
use std::sync::Arc;
use std::{mem, ops, ptr, slice};
use core::ffi::{c_char, c_uint};
use core::marker::PhantomData;
use core::{mem, ops, ptr, slice};

#[cfg(feature = "std")]
use std::{ffi::c_void, sync::Arc, vec::Vec};

/// Blobs wrap a chunk of binary data to handle lifecycle management of data
/// while it is passed between client and HarfBuzz.
Expand Down Expand Up @@ -63,6 +65,7 @@ impl<'a> Blob<'a> {
/// assert_eq!(blob.len(), 256);
/// assert!(!blob.is_empty());
/// ```
#[cfg(feature = "std")]
pub fn new_from_arc_vec(data: Arc<Vec<u8>>) -> Blob<'static> {
let len = data.len();
assert!(len <= c_uint::max_value() as usize);
Expand Down
24 changes: 16 additions & 8 deletions harfbuzz/src/buffer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
// except according to those terms.

use crate::sys;
use crate::UnicodeFuncs;
use crate::{Direction, Language};

/// A series of Unicode characters.
Expand Down Expand Up @@ -99,7 +100,7 @@ impl Buffer {
/// Gives up ownership and returns a raw pointer to the buffer.
pub fn into_raw(self) -> *mut sys::hb_buffer_t {
let raw = self.raw;
std::mem::forget(self);
core::mem::forget(self);
raw
}

Expand All @@ -117,15 +118,22 @@ impl Buffer {
b
}

/// Sets a [`UnicodeFuncs`] instance to use with this buffer.
///
/// Note: `unicode_funcs` is reference counted by HarfBuzz.
pub fn set_unicode_funcs(&mut self, unicode_funcs: &UnicodeFuncs) {
unsafe { sys::hb_buffer_set_unicode_funcs(self.raw, unicode_funcs.as_ptr()) }
}

/// Add UTF-8 encoded text to the buffer.
pub fn add_str(&mut self, text: &str) {
unsafe {
sys::hb_buffer_add_utf8(
self.raw,
text.as_ptr() as *const std::os::raw::c_char,
text.len() as std::os::raw::c_int,
text.as_ptr() as *const core::ffi::c_char,
text.len() as core::ffi::c_int,
0,
text.len() as std::os::raw::c_int,
text.len() as core::ffi::c_int,
)
};
}
Expand All @@ -144,8 +152,8 @@ impl Buffer {
sys::hb_buffer_append(
self.raw,
other.raw,
start as std::os::raw::c_uint,
end as std::os::raw::c_uint,
start as core::ffi::c_uint,
end as core::ffi::c_uint,
)
};
}
Expand Down Expand Up @@ -297,8 +305,8 @@ impl Buffer {
}
}

impl std::fmt::Debug for Buffer {
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
impl core::fmt::Debug for Buffer {
fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::fmt::Result {
fmt.debug_struct("Buffer")
.field("direction", &self.get_direction())
.field("script", &self.get_script())
Expand Down
10 changes: 5 additions & 5 deletions harfbuzz/src/language.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,15 @@ impl Language {
Language {
raw: unsafe {
sys::hb_language_from_string(
lang.as_ptr() as *const std::os::raw::c_char,
lang.len() as std::os::raw::c_int,
lang.as_ptr() as *const core::ffi::c_char,
lang.len() as core::ffi::c_int,
)
},
}
}

pub fn to_string(&self) -> &str {
unsafe { std::ffi::CStr::from_ptr(sys::hb_language_to_string(self.raw)) }
unsafe { core::ffi::CStr::from_ptr(sys::hb_language_to_string(self.raw)) }
.to_str()
.unwrap()
}
Expand Down Expand Up @@ -63,8 +63,8 @@ impl Language {
}
}

impl std::fmt::Debug for Language {
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
impl core::fmt::Debug for Language {
fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::fmt::Result {
fmt.write_str(self.to_string())
}
}
Expand Down
39 changes: 39 additions & 0 deletions harfbuzz/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,10 @@
//! - `directwrite` - Enables bindings to the DirectWrite font engine. (Windows only) (Enabled by default.)
//!
//! - `bundled` - Use the bundled copy of the harfbuzz library rather than one installed on the system.
//!
//! TODO: Add more feature docs here

#![no_std]
#![warn(missing_docs)]
#![deny(
trivial_numeric_casts,
Expand All @@ -26,16 +29,52 @@
unused_qualifications
)]

extern crate alloc;

#[cfg(feature = "std")]
extern crate std;

#[cfg(feature = "harfbuzz-sys")]
pub use harfbuzz_sys as sys;

/// An error type for this crate
#[derive(Debug)]
pub enum HarfBuzzError {
/// Allocation failed within HarfBuzz itself
Alloc,
}
pub use HarfBuzzError as Error;

#[cfg(feature = "harfbuzz-sys")]
mod buffer;
#[cfg(feature = "harfbuzz-sys")]
pub use self::buffer::Buffer;

#[cfg(feature = "harfbuzz-sys")]
mod direction;
#[cfg(feature = "harfbuzz-sys")]
pub use self::direction::Direction;

#[cfg(feature = "harfbuzz-sys")]
mod language;
#[cfg(feature = "harfbuzz-sys")]
pub use self::language::Language;

#[cfg(feature = "harfbuzz-sys")]
mod blob;
#[cfg(feature = "harfbuzz-sys")]
pub use self::blob::Blob;

mod traits;
pub use self::traits::CombiningClassFunc;
pub use self::traits::ComposeFunc;
pub use self::traits::DecomposeFunc;
pub use self::traits::GeneralCategory;
pub use self::traits::GeneralCategoryFunc;
pub use self::traits::MirroringFunc;
pub use self::traits::ScriptFunc;

#[cfg(feature = "harfbuzz-sys")]
mod unicode_funcs;
#[cfg(feature = "harfbuzz-sys")]
pub use self::unicode_funcs::{UnicodeFuncs, UnicodeFuncsBuilder};
89 changes: 89 additions & 0 deletions harfbuzz/src/traits.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
// Copyright 2023 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

/// A general category value. Equivalent to [`hb_unicode_general_category_t`].
///
/// [`hb_unicode_general_category_t`]: crate::sys::hb_unicode_general_category_t
#[repr(u8)]
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[allow(non_camel_case_types)] // the names are defined by Unicode

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suggest dropping the underscores like ICU4X does. That way, the names would be idiomatic for a Rust enum. Even if the names are defined by Unicode, it's pretty obvious to the reader what the applied name transformation would be if the names were idiomatic to Rust.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, note the casing of the letter "u" in PrivateUse/Private_Use.

#[allow(missing_docs)] // the categories are defined by Unicode
pub enum GeneralCategory {
Control = 0,
Format = 1,
Unassigned = 2,
Private_use = 3,
Surrogate = 4,
Lowercase_Letter = 5,
Modifier_Letter = 6,
Other_Letter = 7,
Titlecase_Letter = 8,
Uppercase_Letter = 9,
Spacing_Mark = 10,
Enclosing_Mark = 11,
Non_Spacing_Mark = 12,
Decimal_Number = 13,
Letter_Number = 14,
Other_Number = 15,
Connect_Punctuation = 16,
Dash_Punctuation = 17,
Close_Punctuation = 18,
Final_Punctuation = 19,
Initial_Punctuation = 20,
Other_Punctuation = 21,
Open_Punctuation = 22,
Currency_Symbol = 23,
Modifier_Symbol = 24,
Math_Symbol = 25,
Other_Symbol = 26,
Line_Separator = 27,
Paragraph_Separator = 28,
Space_Separator = 29,
}

/// An object to map from code points to general category properties.
pub trait GeneralCategoryFunc {
/// Given a code point, return the general category as a [`GeneralCategory`].
fn general_category(&self, ch: char) -> GeneralCategory;
}

/// An object to map from code points to combining classes.
pub trait CombiningClassFunc {
/// Given a code point, return the combining class as a `u8` corresponding to a
/// [`hb_unicode_combining_class_t`]. Note that the
/// [Unicode stability policy](https://www.unicode.org/policies/stability_policy.html)
/// guarantees that Canonical Combining Class numeric values fit in a `u8`.
///
/// [`hb_unicode_combining_class_t`]: crate::sys::hb_unicode_combining_class_t
fn combining_class(&self, ch: char) -> u8;
}

/// An object to map from code points to mirrored code points.
pub trait MirroringFunc {
/// Given a code point, return the mirrored code point.
fn mirroring(&self, ch: char) -> char;
}

/// An object to map from code points to script names.
pub trait ScriptFunc {
/// Given a code point, return the script as a 4-byte script name.
fn script(&self, ch: char) -> [u8; 4];
}

/// An object to compose two characters.
pub trait ComposeFunc {
/// Given two code points, return the composed code point.
fn compose(&self, a: char, b: char) -> Option<char>;
}

/// An object to decompose a character.
pub trait DecomposeFunc {
/// Given a code point, return the two decomposed code points.
fn decompose(&self, ab: char) -> Option<(char, char)>;
}
Loading