Make range generic

This commit is contained in:
Brendan Zabarauskas 2014-05-07 11:40:32 -07:00
parent 15d3257a29
commit 8c6eb08dcb
10 changed files with 79 additions and 69 deletions

View file

@ -395,7 +395,7 @@ pub struct TextDisplayItem {
pub text_run: Arc<~TextRun>, pub text_run: Arc<~TextRun>,
/// The range of text within the text run. /// The range of text within the text run.
pub range: Range, pub range: Range<uint>,
/// The color of the text. /// The color of the text.
pub text_color: Color, pub text_color: Color,

View file

@ -330,7 +330,7 @@ impl Font {
pub fn draw_text_into_context(&mut self, pub fn draw_text_into_context(&mut self,
rctx: &RenderContext, rctx: &RenderContext,
run: &~TextRun, run: &~TextRun,
range: &Range, range: &Range<uint>,
baseline_origin: Point2D<Au>, baseline_origin: Point2D<Au>,
color: Color) { color: Color) {
use libc::types::common::c99::{uint16_t, uint32_t}; use libc::types::common::c99::{uint16_t, uint32_t};
@ -391,7 +391,7 @@ impl Font {
} }
} }
pub fn measure_text(&self, run: &TextRun, range: &Range) -> RunMetrics { pub fn measure_text(&self, run: &TextRun, range: &Range<uint>) -> RunMetrics {
// TODO(Issue #199): alter advance direction for RTL // TODO(Issue #199): alter advance direction for RTL
// TODO(Issue #98): using inter-char and inter-word spacing settings when measuring text // TODO(Issue #98): using inter-char and inter-word spacing settings when measuring text
let mut advance = Au(0); let mut advance = Au(0);
@ -405,7 +405,7 @@ impl Font {
pub fn measure_text_for_slice(&self, pub fn measure_text_for_slice(&self,
glyphs: &GlyphStore, glyphs: &GlyphStore,
slice_range: &Range) slice_range: &Range<uint>)
-> RunMetrics { -> RunMetrics {
let mut advance = Au(0); let mut advance = Au(0);
for (_i, glyph) in glyphs.iter_glyphs_for_char_range(slice_range) { for (_i, glyph) in glyphs.iter_glyphs_for_char_range(slice_range) {

View file

@ -598,7 +598,7 @@ impl<'a> GlyphStore {
} }
#[inline] #[inline]
pub fn iter_glyphs_for_char_range(&'a self, rang: &Range) -> GlyphIterator<'a> { pub fn iter_glyphs_for_char_range(&'a self, rang: &Range<uint>) -> GlyphIterator<'a> {
if rang.begin() >= self.entry_buffer.len() { if rang.begin() >= self.entry_buffer.len() {
fail!("iter_glyphs_for_range: range.begin beyond length!"); fail!("iter_glyphs_for_range: range.begin beyond length!");
} }

View file

@ -276,10 +276,10 @@ impl Shaper {
} }
// some helpers // some helpers
let mut glyph_span: Range = Range::empty(); let mut glyph_span: Range<uint> = Range::empty();
// this span contains first byte of first char, to last byte of last char in range. // this span contains first byte of first char, to last byte of last char in range.
// so, end() points to first byte of last+1 char, if it's less than byte_max. // so, end() points to first byte of last+1 char, if it's less than byte_max.
let mut char_byte_span: Range = Range::empty(); let mut char_byte_span: Range<uint> = Range::empty();
let mut y_pos = Au(0); let mut y_pos = Au(0);
// main loop over each glyph. each iteration usually processes 1 glyph and 1+ chars. // main loop over each glyph. each iteration usually processes 1 glyph and 1+ chars.

View file

@ -23,14 +23,14 @@ pub struct TextRun {
pub struct SliceIterator<'a> { pub struct SliceIterator<'a> {
glyph_iter: Items<'a, Arc<GlyphStore>>, glyph_iter: Items<'a, Arc<GlyphStore>>,
range: Range, range: Range<uint>,
offset: uint, offset: uint,
} }
impl<'a> Iterator<(&'a GlyphStore, uint, Range)> for SliceIterator<'a> { impl<'a> Iterator<(&'a GlyphStore, uint, Range<uint>)> for SliceIterator<'a> {
// inline(always) due to the inefficient rt failures messing up inline heuristics, I think. // inline(always) due to the inefficient rt failures messing up inline heuristics, I think.
#[inline(always)] #[inline(always)]
fn next(&mut self) -> Option<(&'a GlyphStore, uint, Range)> { fn next(&mut self) -> Option<(&'a GlyphStore, uint, Range<uint>)> {
loop { loop {
let slice_glyphs = self.glyph_iter.next(); let slice_glyphs = self.glyph_iter.next();
if slice_glyphs.is_none() { if slice_glyphs.is_none() {
@ -52,13 +52,13 @@ impl<'a> Iterator<(&'a GlyphStore, uint, Range)> for SliceIterator<'a> {
} }
pub struct LineIterator<'a> { pub struct LineIterator<'a> {
range: Range, range: Range<uint>,
clump: Option<Range>, clump: Option<Range<uint>>,
slices: SliceIterator<'a>, slices: SliceIterator<'a>,
} }
impl<'a> Iterator<Range> for LineIterator<'a> { impl<'a> Iterator<Range<uint>> for LineIterator<'a> {
fn next(&mut self) -> Option<Range> { fn next(&mut self) -> Option<Range<uint>> {
// Loop until we hit whitespace and are in a clump. // Loop until we hit whitespace and are in a clump.
loop { loop {
match self.slices.next() { match self.slices.next() {
@ -175,14 +175,14 @@ impl<'a> TextRun {
&*self.glyphs &*self.glyphs
} }
pub fn range_is_trimmable_whitespace(&self, range: &Range) -> bool { pub fn range_is_trimmable_whitespace(&self, range: &Range<uint>) -> bool {
for (slice_glyphs, _, _) in self.iter_slices_for_range(range) { for (slice_glyphs, _, _) in self.iter_slices_for_range(range) {
if !slice_glyphs.is_whitespace() { return false; } if !slice_glyphs.is_whitespace() { return false; }
} }
true true
} }
pub fn metrics_for_range(&self, range: &Range) -> RunMetrics { pub fn metrics_for_range(&self, range: &Range<uint>) -> RunMetrics {
// TODO(Issue #199): alter advance direction for RTL // TODO(Issue #199): alter advance direction for RTL
// TODO(Issue #98): using inter-char and inter-word spacing settings when measuring text // TODO(Issue #98): using inter-char and inter-word spacing settings when measuring text
let mut advance = Au(0); let mut advance = Au(0);
@ -194,14 +194,14 @@ impl<'a> TextRun {
RunMetrics::new(advance, self.font_metrics.ascent, self.font_metrics.descent) RunMetrics::new(advance, self.font_metrics.ascent, self.font_metrics.descent)
} }
pub fn metrics_for_slice(&self, glyphs: &GlyphStore, slice_range: &Range) -> RunMetrics { pub fn metrics_for_slice(&self, glyphs: &GlyphStore, slice_range: &Range<uint>) -> RunMetrics {
let mut advance = Au(0); let mut advance = Au(0);
for (_i, glyph) in glyphs.iter_glyphs_for_char_range(slice_range) { for (_i, glyph) in glyphs.iter_glyphs_for_char_range(slice_range) {
advance = advance + glyph.advance(); advance = advance + glyph.advance();
} }
RunMetrics::new(advance, self.font_metrics.ascent, self.font_metrics.descent) RunMetrics::new(advance, self.font_metrics.ascent, self.font_metrics.descent)
} }
pub fn min_width_for_range(&self, range: &Range) -> Au { pub fn min_width_for_range(&self, range: &Range<uint>) -> Au {
let mut max_piece_width = Au(0); let mut max_piece_width = Au(0);
debug!("iterating outer range {:?}", range); debug!("iterating outer range {:?}", range);
for (_, offset, slice_range) in self.iter_slices_for_range(range) { for (_, offset, slice_range) in self.iter_slices_for_range(range) {
@ -212,7 +212,7 @@ impl<'a> TextRun {
max_piece_width max_piece_width
} }
pub fn iter_slices_for_range(&'a self, range: &Range) -> SliceIterator<'a> { pub fn iter_slices_for_range(&'a self, range: &Range<uint>) -> SliceIterator<'a> {
SliceIterator { SliceIterator {
glyph_iter: self.glyphs.iter(), glyph_iter: self.glyphs.iter(),
range: *range, range: *range,
@ -220,7 +220,7 @@ impl<'a> TextRun {
} }
} }
pub fn iter_natural_lines_for_range(&'a self, range: &Range) -> LineIterator<'a> { pub fn iter_natural_lines_for_range(&'a self, range: &Range<uint>) -> LineIterator<'a> {
LineIterator { LineIterator {
range: *range, range: *range,
clump: None, clump: None,

View file

@ -226,12 +226,12 @@ pub struct ScannedTextBoxInfo {
pub run: Arc<~TextRun>, pub run: Arc<~TextRun>,
/// The range within the above text run that this represents. /// The range within the above text run that this represents.
pub range: Range, pub range: Range<uint>,
} }
impl ScannedTextBoxInfo { impl ScannedTextBoxInfo {
/// Creates the information specific to a scanned text box from a range and a text run. /// Creates the information specific to a scanned text box from a range and a text run.
pub fn new(run: Arc<~TextRun>, range: Range) -> ScannedTextBoxInfo { pub fn new(run: Arc<~TextRun>, range: Range<uint>) -> ScannedTextBoxInfo {
ScannedTextBoxInfo { ScannedTextBoxInfo {
run: run, run: run,
range: range, range: range,
@ -1146,7 +1146,7 @@ impl Box {
let mut pieces_processed_count: uint = 0; let mut pieces_processed_count: uint = 0;
let mut remaining_width: Au = max_width; let mut remaining_width: Au = max_width;
let mut left_range = Range::new(text_box_info.range.begin(), 0); let mut left_range = Range::new(text_box_info.range.begin(), 0);
let mut right_range: Option<Range> = None; let mut right_range: Option<Range<uint>> = None;
debug!("split_to_width: splitting text box (strlen={:u}, range={}, \ debug!("split_to_width: splitting text box (strlen={:u}, range={}, \
avail_width={})", avail_width={})",
@ -1222,7 +1222,7 @@ impl Box {
None None
}; };
let right_box = right_range.map_or(None, |range: Range| { let right_box = right_range.map_or(None, |range: Range<uint>| {
let new_text_box_info = ScannedTextBoxInfo::new(text_box_info.run.clone(), let new_text_box_info = ScannedTextBoxInfo::new(text_box_info.run.clone(),
range); range);
let mut new_metrics = new_text_box_info.run.metrics_for_range(&range); let mut new_metrics = new_text_box_info.run.metrics_for_range(&range);

View file

@ -189,7 +189,7 @@ impl InlineBoxAccumulator {
fn from_inline_node(node: &ThreadSafeLayoutNode) -> InlineBoxAccumulator { fn from_inline_node(node: &ThreadSafeLayoutNode) -> InlineBoxAccumulator {
let mut boxes = InlineBoxes::new(); let mut boxes = InlineBoxes::new();
boxes.map.push(node.style().clone(), Range::new(0, 0)); boxes.map.push(node.style().clone(), Range::new(0u, 0));
InlineBoxAccumulator { InlineBoxAccumulator {
boxes: boxes, boxes: boxes,
has_enclosing_range: true, has_enclosing_range: true,

View file

@ -56,7 +56,7 @@ use sync::Arc;
/// left corner of the green zone is the same as that of the line, but /// left corner of the green zone is the same as that of the line, but
/// the green zone can be taller and wider than the line itself. /// the green zone can be taller and wider than the line itself.
pub struct LineBox { pub struct LineBox {
pub range: Range, pub range: Range<uint>,
pub bounds: Rect<Au>, pub bounds: Rect<Au>,
pub green_zone: Size2D<Au> pub green_zone: Size2D<Au>
} }
@ -977,12 +977,12 @@ pub struct FragmentRange {
/// The style of the DOM node that this range refers to. /// The style of the DOM node that this range refers to.
pub style: Arc<ComputedValues>, pub style: Arc<ComputedValues>,
/// The range, in indices into the fragment list. /// The range, in indices into the fragment list.
pub range: Range, pub range: Range<uint>,
} }
impl FragmentRange { impl FragmentRange {
/// Creates a new fragment range from the given values. /// Creates a new fragment range from the given values.
fn new(style: Arc<ComputedValues>, range: Range) -> FragmentRange { fn new(style: Arc<ComputedValues>, range: Range<uint>) -> FragmentRange {
FragmentRange { FragmentRange {
style: style, style: style,
range: range, range: range,
@ -1053,7 +1053,7 @@ impl FragmentMap {
} }
/// Adds the given node to the fragment map. /// Adds the given node to the fragment map.
pub fn push(&mut self, style: Arc<ComputedValues>, range: Range) { pub fn push(&mut self, style: Arc<ComputedValues>, range: Range<uint>) {
self.list.push(FragmentRange::new(style, range)) self.list.push(FragmentRange::new(style, range))
} }

View file

@ -31,7 +31,7 @@ fn can_coalesce_text_nodes(boxes: &[Box], left_i: uint, right_i: uint) -> bool {
/// A stack-allocated object for scanning an inline flow into `TextRun`-containing `TextBox`es. /// A stack-allocated object for scanning an inline flow into `TextRun`-containing `TextBox`es.
pub struct TextRunScanner { pub struct TextRunScanner {
pub clump: Range, pub clump: Range<uint>,
} }
impl TextRunScanner { impl TextRunScanner {
@ -210,7 +210,7 @@ impl TextRunScanner {
// Next, concatenate all of the transformed strings together, saving the new // Next, concatenate all of the transformed strings together, saving the new
// character indices. // character indices.
let mut run_str: ~str = "".to_owned(); let mut run_str: ~str = "".to_owned();
let mut new_ranges: Vec<Range> = vec!(); let mut new_ranges: Vec<Range<uint>> = vec!();
let mut char_total = 0; let mut char_total = 0;
for i in range(0, transformed_strs.len()) { for i in range(0, transformed_strs.len()) {
let added_chars = transformed_strs.get(i).char_len(); let added_chars = transformed_strs.get(i).char_len();

View file

@ -5,10 +5,12 @@
use std::cmp::{max, min}; use std::cmp::{max, min};
use std::iter; use std::iter;
use std::fmt; use std::fmt;
use std::num;
use std::num::Bounded;
pub enum RangeRelation { pub enum RangeRelation<T> {
OverlapsBegin(/* overlap */ uint), OverlapsBegin(/* overlap */ T),
OverlapsEnd(/* overlap */ uint), OverlapsEnd(/* overlap */ T),
ContainedBy, ContainedBy,
Contains, Contains,
Coincides, Coincides,
@ -17,20 +19,20 @@ pub enum RangeRelation {
} }
#[deriving(Clone)] #[deriving(Clone)]
pub struct Range { pub struct Range<T> {
off: uint, off: T,
len: uint len: T,
} }
impl fmt::Show for Range { impl<T: Int + TotalOrd> fmt::Show for Range<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f.buf, "[{} .. {})", self.begin(), self.end()) write!(f.buf, "[{} .. {})", self.begin(), self.end())
} }
} }
impl Range { impl<T: Int + TotalOrd> Range<T> {
#[inline] #[inline]
pub fn new(off: uint, len: uint) -> Range { pub fn new(off: T, len: T) -> Range<T> {
Range { Range {
off: off, off: off,
len: len, len: len,
@ -38,68 +40,76 @@ impl Range {
} }
#[inline] #[inline]
pub fn empty() -> Range { pub fn empty() -> Range<T> {
Range::new(0, 0) Range::new(num::zero(), num::zero())
} }
}
impl Range {
#[inline]
pub fn begin(&self) -> uint { self.off }
#[inline]
pub fn length(&self) -> uint { self.len }
#[inline]
pub fn end(&self) -> uint { self.off + self.len }
#[inline] #[inline]
pub fn eachi(&self) -> iter::Range<uint> { pub fn begin(&self) -> T { self.off }
#[inline]
pub fn length(&self) -> T { self.len }
#[inline]
pub fn end(&self) -> T { self.off + self.len }
#[inline]
pub fn eachi(&self) -> iter::Range<T> {
range(self.off, self.off + self.len) range(self.off, self.off + self.len)
} }
#[inline] #[inline]
pub fn contains(&self, i: uint) -> bool { pub fn contains(&self, i: T) -> bool {
i >= self.begin() && i < self.end() i >= self.begin() && i < self.end()
} }
#[inline] #[inline]
pub fn is_valid_for_string(&self, s: &str) -> bool { pub fn is_valid_for_string(&self, s: &str) -> bool {
self.begin() < s.len() && self.end() <= s.len() && self.length() <= s.len() let s_len = s.len();
match num::cast(s_len) {
Some(len) => {
self.begin() < len && self.end() <= len && self.length() <= len
},
None => {
debug!("Range<T>::is_valid_for_string: string length ({}) is longer than the max \
value for T ({})", s_len, { let val: T = Bounded::max_value(); val });
false
},
}
} }
#[inline] #[inline]
pub fn is_empty(&self) -> bool { pub fn is_empty(&self) -> bool {
self.len == 0 self.len.is_zero()
} }
#[inline] #[inline]
pub fn shift_by(&mut self, i: int) { pub fn shift_by(&mut self, i: int) {
self.off = ((self.off as int) + i) as uint; self.off = num::cast(self.off.to_int().unwrap() + i).unwrap();
} }
#[inline] #[inline]
pub fn extend_by(&mut self, i: int) { pub fn extend_by(&mut self, i: int) {
self.len = ((self.len as int) + i) as uint; self.len = num::cast(self.len.to_int().unwrap() + i).unwrap();
} }
#[inline] #[inline]
pub fn extend_to(&mut self, i: uint) { pub fn extend_to(&mut self, i: T) {
self.len = i - self.off; self.len = i - self.off;
} }
#[inline] #[inline]
pub fn adjust_by(&mut self, off_i: int, len_i: int) { pub fn adjust_by(&mut self, off_i: int, len_i: int) {
self.off = ((self.off as int) + off_i) as uint; self.off = num::cast(self.off.to_int().unwrap() + off_i).unwrap();
self.len = ((self.len as int) + len_i) as uint; self.len = num::cast(self.len.to_int().unwrap() + len_i).unwrap();
} }
#[inline] #[inline]
pub fn reset(&mut self, off_i: uint, len_i: uint) { pub fn reset(&mut self, off_i: T, len_i: T) {
self.off = off_i; self.off = off_i;
self.len = len_i; self.len = len_i;
} }
#[inline] #[inline]
pub fn intersect(&self, other: &Range) -> Range { pub fn intersect(&self, other: &Range<T>) -> Range<T> {
let begin = max(self.begin(), other.begin()); let begin = max(self.begin(), other.begin());
let end = min(self.end(), other.end()); let end = min(self.end(), other.end());
@ -114,7 +124,7 @@ impl Range {
/// from the point of view of `self`. So, 'EntirelyBefore' means /// from the point of view of `self`. So, 'EntirelyBefore' means
/// that the `self` range is entirely before `other` range. /// that the `self` range is entirely before `other` range.
#[inline] #[inline]
pub fn relation_to_range(&self, other: &Range) -> RangeRelation { pub fn relation_to_range(&self, other: &Range<T>) -> RangeRelation<T> {
if other.begin() > self.end() { if other.begin() > self.end() {
return EntirelyBefore; return EntirelyBefore;
} }
@ -143,19 +153,19 @@ impl Range {
} }
#[inline] #[inline]
pub fn repair_after_coalesced_range(&mut self, other: &Range) { pub fn repair_after_coalesced_range(&mut self, other: &Range<T>) {
let relation = self.relation_to_range(other); let relation = self.relation_to_range(other);
debug!("repair_after_coalesced_range: possibly repairing range {:?}", self); debug!("repair_after_coalesced_range: possibly repairing range {:?}", self);
debug!("repair_after_coalesced_range: relation of original range and coalesced range({:?}): {:?}", debug!("repair_after_coalesced_range: relation of original range and coalesced range({:?}): {:?}",
other, relation); other, relation);
match relation { match relation {
EntirelyBefore => { }, EntirelyBefore => { },
EntirelyAfter => { self.shift_by(-(other.length() as int)); }, EntirelyAfter => { self.shift_by(-other.length().to_int().unwrap()); },
Coincides | ContainedBy => { self.reset(other.begin(), 1); }, Coincides | ContainedBy => { self.reset(other.begin(), num::one()); },
Contains => { self.extend_by(-(other.length() as int)); }, Contains => { self.extend_by(-other.length().to_int().unwrap()); },
OverlapsBegin(overlap) => { self.extend_by(1 - (overlap as int)); }, OverlapsBegin(overlap) => { self.extend_by(1 - overlap.to_int().unwrap()); },
OverlapsEnd(overlap) => { OverlapsEnd(overlap) => {
let len = self.length() - overlap + 1; let len = self.length() - overlap + num::one();
self.reset(other.begin(), len); self.reset(other.begin(), len);
} }
}; };