loca.cc (2834B)
1 // Copyright (c) 2009-2017 The OTS Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #include "loca.h" 6 7 #include "head.h" 8 #include "maxp.h" 9 10 // loca - Index to Location 11 // http://www.microsoft.com/typography/otspec/loca.htm 12 13 namespace ots { 14 15 bool OpenTypeLOCA::Parse(const uint8_t *data, size_t length) { 16 Buffer table(data, length); 17 18 // We can't do anything useful in validating this data except to ensure that 19 // the values are monotonically increasing. 20 21 OpenTypeMAXP *maxp = static_cast<OpenTypeMAXP*>( 22 GetFont()->GetTypedTable(OTS_TAG_MAXP)); 23 OpenTypeHEAD *head = static_cast<OpenTypeHEAD*>( 24 GetFont()->GetTypedTable(OTS_TAG_HEAD)); 25 if (!maxp || !head) { 26 return Error("Required maxp or head tables are missing"); 27 } 28 29 const unsigned num_glyphs = maxp->num_glyphs; 30 unsigned last_offset = 0; 31 this->offsets.resize(num_glyphs + 1); 32 // maxp->num_glyphs is uint16_t, thus the addition never overflows. 33 34 if (head->index_to_loc_format == 0) { 35 // Note that the <= here (and below) is correct. There is one more offset 36 // than the number of glyphs in order to give the length of the final 37 // glyph. 38 for (unsigned i = 0; i <= num_glyphs; ++i) { 39 uint16_t offset = 0; 40 if (!table.ReadU16(&offset)) { 41 return Error("Failed to read offset for glyph %d", i); 42 } 43 if (offset < last_offset) { 44 return Error("Out of order offset %d < %d for glyph %d", offset, last_offset, i); 45 } 46 last_offset = offset; 47 this->offsets[i] = offset * 2; 48 } 49 } else { 50 for (unsigned i = 0; i <= num_glyphs; ++i) { 51 uint32_t offset = 0; 52 if (!table.ReadU32(&offset)) { 53 return Error("Failed to read offset for glyph %d", i); 54 } 55 if (offset < last_offset) { 56 return Error("Out of order offset %d < %d for glyph %d", offset, last_offset, i); 57 } 58 last_offset = offset; 59 this->offsets[i] = offset; 60 } 61 } 62 63 return true; 64 } 65 66 bool OpenTypeLOCA::Serialize(OTSStream *out) { 67 OpenTypeHEAD *head = static_cast<OpenTypeHEAD*>( 68 GetFont()->GetTypedTable(OTS_TAG_HEAD)); 69 70 if (!head) { 71 return Error("Required head table is missing"); 72 } 73 74 if (head->index_to_loc_format == 0) { 75 for (unsigned i = 0; i < this->offsets.size(); ++i) { 76 const uint16_t offset = static_cast<uint16_t>(this->offsets[i] >> 1); 77 if ((offset != (this->offsets[i] >> 1)) || 78 !out->WriteU16(offset)) { 79 return Error("Failed to write glyph offset for glyph %d", i); 80 } 81 } 82 } else { 83 for (unsigned i = 0; i < this->offsets.size(); ++i) { 84 if (!out->WriteU32(this->offsets[i])) { 85 return Error("Failed to write glyph offset for glyph %d", i); 86 } 87 } 88 } 89 90 return true; 91 } 92 93 } // namespace ots