Commit message: Change BasicIO read/write methods to use size_t
CVE: CVE-2019-13504
Vulnerability description: There is an out-of-bounds read in Exiv2::MrwImage::readMetadata in mrwimage.cpp in Exiv2 through 0.27.2.

Project: exiv2
File: jpgimage.cpp

    void JpegBase::printStructure(std::ostream& out, PrintStructureOption option, int depth)
    {
        if (io_->open() != 0)
            throw Error(kerDataSourceOpenFailed, io_->path(), strError());
        // Ensure that this is the correct image type
        if (!isThisType(*io_, false)) {
            if (io_->error() || io_->eof())
                throw Error(kerFailedToReadImageData);
            throw Error(kerNotAJpeg);
        }

        bool bPrint = option == kpsBasic || option == kpsRecursive;
        Exiv2::Uint32Vector iptcDataSegs;

        if (bPrint || option == kpsXMP || option == kpsIccProfile || option == kpsIptcErase) {
            // nmonic for markers
            std::string nm[256];
            nm[0xd8] = "SOI";
            nm[0xd9] = "EOI";
            nm[0xda] = "SOS";
            nm[0xdb] = "DQT";
            nm[0xdd] = "DRI";
            nm[0xfe] = "COM";

            // 0xe0 .. 0xef are APPn
            // 0xc0 .. 0xcf are SOFn (except 4)
            nm[0xc4] = "DHT";
            for (int i = 0; i <= 15; i++) {
                char MN[10];
                sprintf(MN, "APP%d", i);
                nm[0xe0 + i] = MN;
                if (i != 4) {
                    sprintf(MN, "SOF%d", i);
                    nm[0xc0 + i] = MN;
                }
            }

            // which markers have a length field?
            bool mHasLength[256];
            for (int i = 0; i < 256; i++)
                mHasLength[i] = (i >= sof0_ && i <= sof15_) || (i >= app0_ && i <= (app0_ | 0x0F)) ||
                                (i == dht_ || i == dqt_ || i == dri_ || i == com_ || i == sos_);

            // Container for the signature
            bool bExtXMP = false;
            const long bufMinSize = 36;
            DataBuf buf(bufMinSize);

            // Read section marker
            int marker = advanceToMarker();
            if (marker < 0)
                throw Error(kerNotAJpeg);

            bool done = false;
            bool first = true;
            while (!done) {
                // print marker bytes
                if (first && bPrint) {
                    out << "STRUCTURE OF JPEG FILE: " << io_->path() << std::endl;
                    out << " address | marker       |  length | data" << std::endl;
                    REPORT_MARKER;
                }
                first = false;
                bool bLF = bPrint;

                // Read size and signature
                std::memset(buf.pData_, 0x0, buf.size_);
                size_t bufRead = io_->read(buf.pData_, bufMinSize);
                if (io_->error())
                    throw Error(kerFailedToReadImageData);
                if (bufRead < 2)
                    throw Error(kerNotAJpeg);
                const uint16_t size = mHasLength[marker] ? getUShort(buf.pData_, bigEndian) : 0;
                if (bPrint && mHasLength[marker])
                    out << Internal::stringFormat(" | %7d ", size);

                // print signature for APPn
                if (marker >= app0_ && marker <= (app0_ | 0x0F)) {
                    // http://www.adobe.com/content/dam/Adobe/en/devnet/xmp/pdfs/XMPSpecificationPart3.pdf p75
                    const std::string signature =
                        string_from_unterminated(reinterpret_cast<const char*>(buf.pData_ + 2), buf.size_ - 2);

                    // 728 rmills@rmillsmbp:~/gnu/exiv2/ttt $ exiv2 -pS test/data/exiv2-bug922.jpg
                    // STRUCTURE OF JPEG FILE: test/data/exiv2-bug922.jpg
                    // address | marker     | length  | data
                    //       0 | 0xd8 SOI   |       0
                    //       2 | 0xe1 APP1  |     911 | Exif..MM.*.......%.........#....
                    //     915 | 0xe1 APP1  |     870 | http://ns.adobe.com/xap/1.0/.<x:
                    //    1787 | 0xe1 APP1  |   65460 | http://ns.adobe.com/xmp/extensio
                    if (option == kpsXMP && signature.find("http://ns.adobe.com/x") == 0) {
                        // extract XMP
                        if (size > 0) {
                            io_->seek(-(int64_t)bufRead, BasicIo::cur);
                            std::vector<byte> xmp(size + 1);
                            io_->read(&xmp[0], size);
                            int start = 0;

                            // http://wwwimages.adobe.com/content/dam/Adobe/en/devnet/xmp/pdfs/XMPSpecificationPart3.pdf
                            // if we find HasExtendedXMP, set the flag and ignore this block
                            // the first extended block is a copy of the Standard block.
                            // a robust implementation allows extended blocks to be out of sequence
                            // we could implement out of sequence with a dictionary of sequence/offset
                            // and dumping the XMP in a post read operation similar to kpsIptcErase
                            // for the moment, dumping 'on the fly' is working fine
                            if (!bExtXMP) {
                                while (xmp.at(start)) {
                                    start++;
                                }
                                start++;
                                const std::string xmp_from_start = string_from_unterminated(
                                    reinterpret_cast<const char*>(&xmp.at(start)), size - start);
                                if (xmp_from_start.find("HasExtendedXMP", start) != xmp_from_start.npos) {
                                    start = size;  // ignore this packet, we'll get on the next time around
                                    bExtXMP = true;
                                }
                            } else {
                                start = 2 + 35 + 32 + 4 + 4;  // Adobe Spec, p19
                            }

                            out.write(reinterpret_cast<const char*>(&xmp.at(start)), size - start);
                            bufRead = size;
                            done = !bExtXMP;
                        }
                    } else if (option == kpsIccProfile && signature.compare(iccId_) == 0) {
                        // extract ICCProfile
                        if (size > 0) {
                            io_->seek(-(int64_t)bufRead, BasicIo::cur);  // back to buffer (after marker)
                            io_->seek(14 + 2, BasicIo::cur);    // step over header
                            DataBuf icc(size - (14 + 2));
                            io_->read(icc.pData_, icc.size_);
                            out.write(reinterpret_cast<const char*>(icc.pData_), icc.size_);
#ifdef DEBUG
                            std::cout << "iccProfile size = " << icc.size_ << std::endl;
#endif
                            bufRead = size;
                        }
                    } else if (option == kpsIptcErase && signature.compare("Photoshop 3.0") == 0) {
                        // delete IPTC data segment from JPEG
                        if (size > 0) {
                            io_->seek(-(int64_t)bufRead, BasicIo::cur);
                            iptcDataSegs.push_back(io_->tell());
                            iptcDataSegs.push_back(size);
                        }
                    } else if (bPrint) {
                        const size_t start = size > 0 ? 2 : 0;
                        const size_t end = start + (size > 32 ? 32 : size);
                        out << "| " << Internal::binaryToString(makeSlice(buf, start, end));
                        if (signature.compare(iccId_) == 0) {
                            // extract the chunk information from the buffer
                            //
                            // the buffer looks like this in this branch
                            // ICC_PROFILE\0AB
                            // where A & B are bytes (the variables chunk & chunks)
                            //
                            // We cannot extract the variables A and B from the signature string, as they are beyond the
                            // null termination (and signature ends there).
                            // => Read the chunk info from the DataBuf directly
                            enforce<std::out_of_range>(buf.size_ - 2 > 14, "Buffer too small to extract chunk information.");
                            const int chunk = buf.pData_[2 + 12];
                            const int chunks = buf.pData_[2 + 13];
                            out << Internal::stringFormat(" chunk %d/%d", chunk, chunks);
                        }
                    }

                    // for MPF: http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/MPF.html
                    // for FLIR: http://owl.phy.queensu.ca/~phil/exiftool/TagNames/FLIR.html
                    bool bFlir = option == kpsRecursive && marker == (app0_ + 1) && signature.compare("FLIR") == 0;
                    bool bExif = option == kpsRecursive && marker == (app0_ + 1) && signature.compare("Exif") == 0;
                    bool bMPF = option == kpsRecursive && marker == (app0_ + 2) && signature.compare("MPF") == 0;
                    bool bPS = option == kpsRecursive && signature.compare("Photoshop 3.0") == 0;
                    if (bFlir || bExif || bMPF || bPS) {
                        // extract Exif data block which is tiff formatted
                        if (size > 0) {
                            out << std::endl;

                            // allocate storage and current file position
                            byte* exif = new byte[size];
                            uint32_t restore = io_->tell();

                            // copy the data to memory
                            io_->seek(-(int64_t)bufRead, BasicIo::cur);
                            io_->read(exif, size);
                            uint32_t start = signature.compare("Exif") == 0 ? 8 : 6;
                            uint32_t max = (uint32_t)size - 1;

                            // is this an fff block?
                            if (bFlir) {
                                start = 0;
                                bFlir = false;
                                while (start < max) {
                                    if (std::strcmp((const char*)(exif + start), "FFF") == 0) {
                                        bFlir = true;
                                        break;
                                    }
                                    start++;
                                }
                            }

                            // there is a header in FLIR, followed by a tiff block
                            // Hunt down the tiff using brute force
                            if (bFlir) {
                                // FLIRFILEHEAD* pFFF = (FLIRFILEHEAD*) (exif+start) ;
                                while (start < max) {
                                    if (exif[start] == 'I' && exif[start + 1] == 'I')
                                        break;
                                    if (exif[start] == 'M' && exif[start + 1] == 'M')
                                        break;
                                    start++;
                                }
                                if (start < max)
                                    std::cout << "  FFF start = " << start << std::endl;
                                // << " index = " << pFFF->dwIndexOff << std::endl;
                            }

                            if (bPS) {
                                IptcData::printStructure(out, makeSlice(exif, 0, size), depth);
                            } else {
                                // create a copy on write memio object with the data, then print the structure
                                BasicIo::UniquePtr p = BasicIo::UniquePtr(new MemIo(exif + start, size - start));
                                if (start < max)
                                    printTiffStructure(*p, out, option, depth);
                            }

                            // restore and clean up
                            io_->seek(restore, Exiv2::BasicIo::beg);
                            delete[] exif;
                            bLF = false;
                        }
                    }
                }

                // print COM marker
                if (bPrint && marker == com_) {
                    // size includes 2 for the two bytes for size!
                    const int n = (size - 2) > 32 ? 32 : size - 2;
                    // start after the two bytes
                    out << "| "
                        << Internal::binaryToString(
                               makeSlice(buf, 2, n + 2 /* cannot overflow as n is at most size - 2 */));
                }

                // Skip the segment if the size is known
                if (io_->seek(size - bufRead, BasicIo::cur))
                    throw Error(kerFailedToReadImageData);

                if (bLF)
                    out << std::endl;

                if (marker != sos_) {
                    // Read the beginning of the next segment
                    marker = advanceToMarker();
                    enforce(marker>=0, kerNoImageInInputData);
                    REPORT_MARKER;
                }
                done |= marker == eoi_ || marker == sos_;
                if (done && bPrint)
                    out << std::endl;
            }
        }
        if (option == kpsIptcErase && iptcDataSegs.size()) {
#ifdef DEBUG
            std::cout << "iptc data blocks: " << iptcDataSegs.size() << std::endl;
            uint32_t toggle = 0;
            for (Uint32Vector_i i = iptcDataSegs.begin(); i != iptcDataSegs.end(); i++) {
                std::cout << *i;
                if (toggle++ % 2)
                    std::cout << std::endl;
                else
                    std::cout << ' ';
            }
#endif
            uint32_t count = (uint32_t)iptcDataSegs.size();

            // figure out which blocks to copy
            uint64_t* pos = new uint64_t[count + 2];
            pos[0] = 0;
            // copy the data that is not iptc
            Uint32Vector_i it = iptcDataSegs.begin();
            for (uint64_t i = 0; i < count; i++) {
                bool bOdd = (i % 2) != 0;
                bool bEven = !bOdd;
                pos[i + 1] = bEven ? *it : pos[i] + *it;
                ++it;
            }
            pos[count + 1] = io_->size() - pos[count];
#ifdef DEBUG
            for (uint64_t i = 0; i < count + 2; i++)
                std::cout << pos[i] << " ";
            std::cout << std::endl;
#endif
            // $ dd bs=1 skip=$((0)) count=$((13164)) if=ETH0138028.jpg of=E1.jpg
            // $ dd bs=1 skip=$((49304)) count=2000000  if=ETH0138028.jpg of=E2.jpg
            // cat E1.jpg E2.jpg > E.jpg
            // exiv2 -pS E.jpg

            // binary copy io_ to a temporary file
            BasicIo::UniquePtr tempIo(new MemIo);

            assert(tempIo.get() != 0);
            for (uint64_t i = 0; i < (count / 2) + 1; i++) {
                uint64_t start = pos[2 * i] + 2;  // step JPG 2 byte marker
                if (start == 2)
                    start = 0;  // read the file 2 byte SOI
                long length = (long)(pos[2 * i + 1] - start);
                if (length) {
#ifdef DEBUG
                    std::cout << start << ":" << length << std::endl;
#endif
                    io_->seek(start, BasicIo::beg);
                    DataBuf buf(length);
                    io_->read(buf.pData_, buf.size_);
                    tempIo->write(buf.pData_, buf.size_);
                }
            }
            delete[] pos;

            io_->seek(0, BasicIo::beg);
            io_->transfer(*tempIo);  // may throw
            io_->seek(0, BasicIo::beg);
            readMetadata();
        }
    }  // JpegBase::printStructure

Project: exiv2
File: tiff-test.cpp

catch (const AnyError& e) {
    std::cout << e << "\n";
}

Project: exiv2
File: value.cpp

    long StringValueBase::count() const
    {
        return size();
    }

Project: exiv2
File: rafimage.cpp

    RafImage::RafImage(BasicIo::UniquePtr io, bool /*create*/)
        : Image(ImageType::raf, mdExif | mdIptc | mdXmp, std::move(io))
    {
    } // RafImage::RafImage

Project: exiv2
File: image.cpp

    std::string& Image::xmpPacket()
    {
        // Serialize the current XMP
        if (xmpData_.count() > 0 && !writeXmpFromPacket()) {
            XmpParser::encode(xmpPacket_, xmpData_, XmpParser::useCompactFormat | XmpParser::omitAllFormatting);
        }
        return xmpPacket_;
    }

Project: exiv2
File: tiffcomposite_int.cpp

    TiffComponent::UniquePtr newTiffMnEntry(uint16_t tag, IfdId group)
    {
        return TiffComponent::UniquePtr(new TiffMnEntry(tag, group, mnId));
    }

Project: exiv2
File: convert.cpp

    void Converter::cnvXmpGPSCoord(const char* from, const char* to)
    {
        Exiv2::XmpData::iterator pos = xmpData_->findKey(XmpKey(from));
        if (pos == xmpData_->end()) return;
        if (!prepareExifTarget(to)) return;
        std::string value = pos->toString();
        if (!pos->value().ok()) {
#ifndef SUPPRESS_WARNINGS
            EXV_WARNING << "Failed to convert " << from << " to " << to << "\n";
#endif
            return;
        }
        if (value.empty()) {
#ifndef SUPPRESS_WARNINGS
            EXV_WARNING << from << " is empty\n";
#endif
            return;
        }

        double deg = 0.0;
        double min = 0.0;
        double sec = 0.0;
        char ref  = value[value.length() - 1];
        char sep1 = '\0';
        char sep2 = '\0';

        value.erase(value.length() - 1);

        std::istringstream in(value);

        in >> deg >> sep1 >> min >> sep2;

        if (sep2 == ',') {
            in >> sec;
        }
        else {
            sec = (min - static_cast<int>(min)) * 60.0;
            min = static_cast<double>(static_cast<int>(min));
            sep2 = ',';
        }

        if (   in.bad() || !(ref == 'N' || ref == 'S' || ref == 'E' || ref == 'W')
            || sep1 != ',' || sep2 != ',' || !in.eof()) {
#ifndef SUPPRESS_WARNINGS
            EXV_WARNING << "Failed to convert " << from << " to " << to << "\n";
#endif
            return;
        }

        Rational rdeg = floatToRationalCast(static_cast<float>(deg));
        Rational rmin = floatToRationalCast(static_cast<float>(min));
        Rational rsec = floatToRationalCast(static_cast<float>(sec));

        std::ostringstream array;
        array << rdeg << " " << rmin << " " << rsec;
        (*exifData_)[to] = array.str();

        prepareExifTarget((std::string(to) + "Ref").c_str(), true);
        char ref_str[2] = {ref, 0};
        (*exifData_)[std::string(to) + "Ref"] = ref_str;

        if (erase_) xmpData_->erase(pos);
    }

Project: exiv2
File: tiffcomposite_int.cpp

    TiffComponent* TiffIfdMakernote::doAddNext(TiffComponent::UniquePtr tiffComponent)
    {
        return ifd_.addNext(std::move(tiffComponent));
    }

Project: exiv2
File: iptc.cpp

    int IptcParser::decode(IptcData& iptcData, const byte* pData, size_t size)
    {
#ifdef DEBUG
        std::cerr << "IptcParser::decode, size = " << size << "\n";
#endif
        const byte* pRead = pData;
        const byte* const pEnd = pData + size;
        iptcData.clear();

        uint16_t record = 0;
        uint16_t dataSet = 0;
        uint32_t sizeData = 0;
        byte extTest = 0;

        while (6 <= static_cast<size_t>(pEnd - pRead)) {
            // First byte should be a marker. If it isn't, scan forward and skip
            // the chunk bytes present in some images. This deviates from the
            // standard, which advises to treat such cases as errors.
            if (*pRead++ != marker_) continue;
            record = *pRead++;
            dataSet = *pRead++;

            extTest = *pRead;
            if (extTest & 0x80) {
                // extended dataset
                uint16_t sizeOfSize = (getUShort(pRead, bigEndian) & 0x7FFF);
                if (sizeOfSize > 4) return 5;
                pRead += 2;
                if (sizeOfSize > static_cast<size_t>(pEnd - pRead)) return 6;
                sizeData = 0;
                for (; sizeOfSize > 0; --sizeOfSize) {
                    sizeData |= *pRead++ << (8 *(sizeOfSize-1));
                }
            }
            else {
                // standard dataset
                sizeData = getUShort(pRead, bigEndian);
                pRead += 2;
            }
            if (sizeData <= static_cast<size_t>(pEnd - pRead)) {
                int rc = 0;
                if ((rc = readData(iptcData, dataSet, record, pRead, sizeData)) != 0) {
#ifndef SUPPRESS_WARNINGS
                    EXV_WARNING << "Failed to read IPTC dataset "
                                << IptcKey(dataSet, record)
                                << " (rc = " << rc << "); skipped.\n";
#endif
                }
            }
#ifndef SUPPRESS_WARNINGS
            else {
                EXV_WARNING << "IPTC dataset " << IptcKey(dataSet, record)
                            << " has invalid size " << sizeData << "; skipped.\n";
                return 7;
            }
#endif
            pRead += sizeData;
        }

        return 0;
    } // IptcParser::decode

Project: exiv2
File: exif.cpp

    void ExifData::add(const Exifdatum& exifdatum)
    {
        // allow duplicates
        exifMetadata_.push_back(exifdatum);
    }

Project: exiv2
File: jpgimage.cpp

    bool isExvType(BasicIo& iIo, bool advance)
    {
        bool result = true;
        byte tmpBuf[7];
        iIo.read(tmpBuf, 7);
        if (iIo.error() || iIo.eof()) return false;

        if (   0xff != tmpBuf[0] || 0x01 != tmpBuf[1]
            || memcmp(tmpBuf + 2, ExvImage::exiv2Id_, 5) != 0) {
            result = false;
        }
        if (!advance || !result) iIo.seek(-7, BasicIo::cur);
        return result;
    }

Project: exiv2
File: iptc.cpp

    size_t Iptcdatum::count() const
    {
        return value_.get() == 0 ? 0 : value_->count();
    }

Project: exiv2
File: exif.cpp

    Exifdatum::Exifdatum(const Exifdatum& rhs)
        : Metadatum(rhs)
    {
        if (rhs.key_.get() != 0) key_ = rhs.key_->clone(); // deep copy
        if (rhs.value_.get() != 0) value_ = rhs.value_->clone(); // deep copy
    }

Project: exiv2
File: types.cpp

    std::ostream& operator<<(std::ostream& os, const Rational& r)
    {
        return os << r.first << "/" << r.second;
    }

Project: exiv2
File: jp2image.cpp

    void Jp2Image::printStructure(std::ostream& out, PrintStructureOption option, int depth)
    {
        if (io_->open() != 0)
            throw Error(kerDataSourceOpenFailed, io_->path(), strError());

        // Ensure that this is the correct image type
        if (!isJp2Type(*io_, false)) {
            if (io_->error() || io_->eof())
                throw Error(kerFailedToReadImageData);
            throw Error(kerNotAJpeg);
        }

        bool bPrint = option == kpsBasic || option == kpsRecursive;
        bool bRecursive = option == kpsRecursive;
        bool bICC = option == kpsIccProfile;
        bool bXMP = option == kpsXMP;
        bool bIPTCErase = option == kpsIptcErase;

        if (bPrint) {
            out << "STRUCTURE OF JPEG2000 FILE: " << io_->path() << std::endl;
            out << " address |   length | box       | data" << std::endl;
        }

        if (bPrint || bXMP || bICC || bIPTCErase) {
            Jp2BoxHeader box = {1, 1};
            Jp2BoxHeader subBox = {1, 1};
            Jp2UuidBox uuid = {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}};
            bool bLF = false;

            while (box.length && box.type != kJp2BoxTypeClose && io_->read((byte*)&box, sizeof(box)) == sizeof(box)) {
                long position = io_->tell();
                box.length = getLong((byte*)&box.length, bigEndian);
                box.type = getLong((byte*)&box.type, bigEndian);

                if (bPrint) {
                    out << Internal::stringFormat("%8ld | %8ld | ", (size_t)(position - sizeof(box)),
                                                  (size_t)box.length)
                        << toAscii(box.type) << "      | ";
                    bLF = true;
                    if (box.type == kJp2BoxTypeClose)
                        lf(out, bLF);
                }
                if (box.type == kJp2BoxTypeClose)
                    break;

                switch (box.type) {
                    case kJp2BoxTypeJp2Header: {
                        lf(out, bLF);

                        while (io_->read((byte*)&subBox, sizeof(subBox)) == sizeof(subBox) &&
                               io_->tell() < position + (long)box.length)  // don't read beyond the box!
                        {
                            int address = io_->tell() - sizeof(subBox);
                            subBox.length = getLong((byte*)&subBox.length, bigEndian);
                            subBox.type = getLong((byte*)&subBox.type, bigEndian);

                            if (subBox.length < sizeof(box) || subBox.length > io_->size() - io_->tell()) {
                                throw Error(kerCorruptedMetadata);
                            }

                            DataBuf data(subBox.length - sizeof(box));
                            io_->read(data.pData_, data.size_);
                            if (bPrint) {
                                out << Internal::stringFormat("%8ld | %8ld |  sub:", (size_t)address,
                                                              (size_t)subBox.length)
                                    << toAscii(subBox.type) << " | "
                                    << Internal::binaryToString(makeSlice(data, 0, std::min(30_z, data.size_)));
                                bLF = true;
                            }

                            if (subBox.type == kJp2BoxTypeColorHeader) {
                                long pad = 3;  // don't know why there are 3 padding bytes
                                if (bPrint) {
                                    out << " | pad:";
                                    for (int i = 0; i < 3; i++)
                                        out << " " << (int)data.pData_[i];
                                }
                                long iccLength = getULong(data.pData_ + pad, bigEndian);
                                if (bPrint) {
                                    out << " | iccLength:" << iccLength;
                                }
                                if (bICC) {
                                    out.write((const char*)data.pData_ + pad, iccLength);
                                }
                            }
                            lf(out, bLF);
                        }
                    } break;

                    case kJp2BoxTypeUuid: {
                        if (io_->read((byte*)&uuid, sizeof(uuid)) == sizeof(uuid)) {
                            bool bIsExif = memcmp(uuid.uuid, kJp2UuidExif, sizeof(uuid)) == 0;
                            bool bIsIPTC = memcmp(uuid.uuid, kJp2UuidIptc, sizeof(uuid)) == 0;
                            bool bIsXMP = memcmp(uuid.uuid, kJp2UuidXmp, sizeof(uuid)) == 0;

                            bool bUnknown = !(bIsExif || bIsIPTC || bIsXMP);

                            if (bPrint) {
                                if (bIsExif)
                                    out << "Exif: ";
                                if (bIsIPTC)
                                    out << "IPTC: ";
                                if (bIsXMP)
                                    out << "XMP : ";
                                if (bUnknown)
                                    out << "????: ";
                            }

                            DataBuf rawData;
                            rawData.alloc(box.length - sizeof(uuid) - sizeof(box));
                            size_t bufRead = io_->read(rawData.pData_, rawData.size_);
                            if (io_->error())
                                throw Error(kerFailedToReadImageData);
                            if (bufRead != rawData.size_)
                                throw Error(kerInputDataReadFailed);

                            if (bPrint) {
                                out << Internal::binaryToString(makeSlice(rawData, 0, 40));
                                out.flush();
                            }
                            lf(out, bLF);

                            if (bIsExif && bRecursive && rawData.size_ > 0) {
                                if ((rawData.pData_[0] == rawData.pData_[1]) &&
                                    (rawData.pData_[0] == 'I' || rawData.pData_[0] == 'M')) {
                                    BasicIo::UniquePtr p = BasicIo::UniquePtr(new MemIo(rawData.pData_, rawData.size_));
                                    printTiffStructure(*p, out, option, depth);
                                }
                            }

                            if (bIsIPTC && bRecursive) {
                                IptcData::printStructure(out, makeSlice(rawData.pData_, 0, rawData.size_), depth);
                            }

                            if (bIsXMP && bXMP) {
                                out.write((const char*)rawData.pData_, rawData.size_);
                            }
                        }
                    } break;

                    default:
                        break;
                }

                // Move to the next box.
                io_->seek(static_cast<long>(position - sizeof(box) + box.length), BasicIo::beg);
                if (io_->error())
                    throw Error(kerFailedToReadImageData);
                if (bPrint)
                    lf(out, bLF);
            }
        }
    }  // JpegBase::printStructure

Project: exiv2
File: exif.cpp

    Exifdatum::~Exifdatum()
    {
    }

Project: exiv2
File: tiffcomposite_int.cpp

    TiffIfdMakernote::TiffIfdMakernote(uint16_t  tag,
                                       IfdId     group,
                                       IfdId     mnGroup,
                                       MnHeader* pHeader,
                                       bool      hasNext)
        : TiffComponent(tag, group),
          pHeader_(pHeader),
          ifd_(tag, mnGroup, hasNext),
          mnOffset_(0),
          imageByteOrder_(invalidByteOrder)
    {
    }

Project: exiv2
File: tiffvisitor_int.cpp

    void TiffEncoder::visitSubIfd(TiffSubIfd* object)
    {
        encodeTiffComponent(object);
    }

Project: exiv2
File: tiffcomposite_int.cpp

    uint32_t TiffImageEntry::doSizeImage() const
    {
        if (!pValue()) return 0;
        uint32_t len = pValue()->sizeDataArea();
        if (len == 0) {
            for (Strips::const_iterator i = strips_.begin(); i != strips_.end(); ++i) {
                len += i->second;
            }
        }
        return len;
    } // TiffImageEntry::doSizeImage

Project: exiv2
File: jp2image.cpp

    static bool isBigEndian()
    {
        union {
            uint32_t i;
            char c[4];
        } e = { 0x01000000 };

        return e.c[0]?true:false;
    }

Project: exiv2
File: mrwimage.cpp

    void MrwImage::readMetadata()
    {
#ifdef DEBUG
        std::cerr << "Reading MRW file " << io_->path() << "\n";
#endif
        if (io_->open() != 0) {
            throw Error(kerDataSourceOpenFailed, io_->path(), strError());
        }
        IoCloser closer(*io_);
        // Ensure that this is the correct image type
        if (!isMrwType(*io_, false)) {
            if (io_->error() || io_->eof()) throw Error(kerFailedToReadImageData);
            throw Error(kerNotAnImage, "MRW");
        }
        clearMetadata();

        // Find the TTW block and read it into a buffer
        uint32_t const len = 8;
        byte tmp[len];
        io_->read(tmp, len);
        uint32_t pos = len;
        uint32_t const end = getULong(tmp + 4, bigEndian);

        pos += len;
        if (pos > end) throw Error(kerFailedToReadImageData);
        io_->read(tmp, len);
        if (io_->error() || io_->eof()) throw Error(kerFailedToReadImageData);

        while (memcmp(tmp + 1, "TTW", 3) != 0) {
            uint32_t const siz = getULong(tmp + 4, bigEndian);
            pos += siz;
            if (pos > end) throw Error(kerFailedToReadImageData);
            io_->seek(siz, BasicIo::cur);
            if (io_->error() || io_->eof()) throw Error(kerFailedToReadImageData);

            pos += len;
            if (pos > end) throw Error(kerFailedToReadImageData);
            io_->read(tmp, len);
            if (io_->error() || io_->eof()) throw Error(kerFailedToReadImageData);
        }

        DataBuf buf(getULong(tmp + 4, bigEndian));
        io_->read(buf.pData_, buf.size_);
        if (io_->error() || io_->eof()) throw Error(kerFailedToReadImageData);

        ByteOrder bo = TiffParser::decode(exifData_,
                                          iptcData_,
                                          xmpData_,
                                          buf.pData_,
                                          (uint32_t)buf.size_);
        setByteOrder(bo);
    } // MrwImage::readMetadata

Project: exiv2
File: image.cpp

    Image::Image(ImageType type, uint16_t supportedMetadata, BasicIo::UniquePtr io)
        : io_(std::move(io)),
          pixelWidth_(0),
          pixelHeight_(0),
          imageType_(type),
          supportedMetadata_(supportedMetadata),
#ifdef EXV_HAVE_XMP_TOOLKIT
          writeXmpFromPacket_(false),
#else
          writeXmpFromPacket_(true),
#endif
          byteOrder_(invalidByteOrder),
          tags_(),
          init_(true)
    {
    }

Project: exiv2
File: iptc.cpp

    const Value& Iptcdatum::value() const
    {
        if (value_.get() == 0) throw Error(kerValueNotSet);
        return *value_;
    }

Project: exiv2
File: convert.cpp

    void Converter::cnvExifGPSCoord(const char* from, const char* to)
    {
        Exiv2::ExifData::iterator pos = exifData_->findKey(ExifKey(from));
        if (pos == exifData_->end()) return;
        if (!prepareXmpTarget(to)) return;
        if (pos->count() != 3) {
#ifndef SUPPRESS_WARNINGS
            EXV_WARNING << "Failed to convert " << from << " to " << to << "\n";
#endif
            return;
        }
        Exiv2::ExifData::iterator refPos = exifData_->findKey(ExifKey(std::string(from) + "Ref"));
        if (refPos == exifData_->end()) {
#ifndef SUPPRESS_WARNINGS
            EXV_WARNING << "Failed to convert " << from << " to " << to << "\n";
#endif
            return;
        }
        double deg[3];
        for (int i = 0; i < 3; ++i) {
            const int32_t z = pos->toRational(i).first;
            const int32_t d = pos->toRational(i).second;
            if (d == 0) {
#ifndef SUPPRESS_WARNINGS
                EXV_WARNING << "Failed to convert " << from << " to " << to << "\n";
#endif
                return;
            }
            // Hack: Need Value::toDouble
            deg[i] = static_cast<double>(z)/d;
        }
        double min = deg[0] * 60.0 + deg[1] + deg[2] / 60.0;
        int ideg = static_cast<int>(min / 60.0);
        min -= ideg * 60;
        std::ostringstream oss;
        oss << ideg << ","
            << std::fixed << std::setprecision(7) << min
            << refPos->toString().c_str()[0];
        (*xmpData_)[to] = oss.str();

        if (erase_) exifData_->erase(pos);
        if (erase_) exifData_->erase(refPos);
    }

Project: exiv2
File: tiffcomposite_int.cpp

    void TiffMnEntry::doAccept(TiffVisitor& visitor)
    {
        visitor.visitMnEntry(this);
        if (mn_) mn_->accept(visitor);
        if (!visitor.go(TiffVisitor::geKnownMakernote)) {
            delete mn_;
            mn_ = 0;
        }

    } // TiffMnEntry::doAccept

Project: exiv2
File: image.cpp

    void Image::setXmpPacket(const std::string& xmpPacket)
    {
        xmpPacket_ = xmpPacket;
        if ( XmpParser::decode(xmpData_, xmpPacket) ) {
            throw Error(kerInvalidXMP);
        }
        xmpPacket_ = xmpPacket;
    }

Project: exiv2
File: basicio.cpp

    DWORD FileIo::Impl::winNumberOfLinks() const
    {
        DWORD nlink = 1;

        HANDLE hFd = (HANDLE)_get_osfhandle(fileno(fp_));
        if (hFd != INVALID_HANDLE_VALUE) {
            typedef BOOL (WINAPI * GetFileInformationByHandle_t)(HANDLE, LPBY_HANDLE_FILE_INFORMATION);
            HMODULE hKernel = ::GetModuleHandleA("kernel32.dll");
            if (hKernel) {
                GetFileInformationByHandle_t pfcn_GetFileInformationByHandle = (GetFileInformationByHandle_t)GetProcAddress(hKernel, "GetFileInformationByHandle");
                if (pfcn_GetFileInformationByHandle) {
                    BY_HANDLE_FILE_INFORMATION fi = {0,0,0,0,0,0,0,0,0,0,0,0,0};
                    if (pfcn_GetFileInformationByHandle(hFd, &fi)) {
                        nlink = fi.nNumberOfLinks;
                    }
#ifdef DEBUG
                    else EXV_DEBUG << "GetFileInformationByHandle failed\n";
#endif
                }
#ifdef DEBUG
                else EXV_DEBUG << "GetProcAddress(hKernel, \"GetFileInformationByHandle\") failed\n";
#endif
            }
#ifdef DEBUG
            else EXV_DEBUG << "GetModuleHandleA(\"kernel32.dll\") failed\n";
#endif
        }
#ifdef DEBUG
        else EXV_DEBUG << "_get_osfhandle failed: INVALID_HANDLE_VALUE\n";
#endif

        return nlink;
    } // FileIo::Impl::winNumberOfLinks

Project: exiv2
File: xmpsidecar.cpp

    Image::UniquePtr newXmpInstance(BasicIo::UniquePtr io, bool create)
    {
        Image::UniquePtr image(new XmpSidecar(std::move(io), create));
        if (!image->good()) {
            image.reset();
        }
        return image;
    }

Project: exiv2
File: iptc.cpp

        bool operator()(const Exiv2::Iptcdatum& iptcdatum) const
        {
            return dataset_ == iptcdatum.tag() && record_ == iptcdatum.record();
        }

Project: exiv2
File: image.cpp

    bool ImageFactory::checkType(ImageType type, BasicIo& io, bool advance)
    {
        const Registry* r = find(registry, type);
        if (0 != r) {
            return r->isThisType_(io, advance);
        }
        return false;
    }

Project: exiv2
File: tiffcomposite_int.cpp

    uint32_t TiffEntryBase::writeOffset(byte*     buf,
                                        int32_t   offset,
                                        TiffType  tiffType,
                                        ByteOrder byteOrder)
    {
        uint32_t rc = 0;
        switch(tiffType) {
        case ttUnsignedShort:
        case ttSignedShort:
            if (static_cast<uint32_t>(offset) > 0xffff) throw Error(kerOffsetOutOfRange);
            rc = s2Data(buf, static_cast<int16_t>(offset), byteOrder);
            break;
        case ttUnsignedLong:
        case ttSignedLong:
            rc = l2Data(buf, static_cast<int32_t>(offset), byteOrder);
            break;
        default:
            throw Error(kerUnsupportedDataAreaOffsetType);
            break;
        }
        return rc;
    } // TiffEntryBase::writeOffset

Project: exiv2
File: exif.cpp

    Exifdatum& Exifdatum::operator=(const int16_t& value)
    {
        return Exiv2::setValue(*this, value);
    }

Project: exiv2
File: jp2image.cpp

    bool isJp2Type(BasicIo& iIo, bool advance)
    {
        const int32_t len = 12;
        byte buf[len];
        iIo.read(buf, len);
        if (iIo.error() || iIo.eof())
        {
            return false;
        }
        bool matched = (memcmp(buf, Jp2Signature, len) == 0);
        if (!advance || !matched)
        {
            iIo.seek(-len, BasicIo::cur);
        }
        return matched;
    }

Project: exiv2
File: value.cpp

    TimeValue::TimeValue(int hour, int minute,
                         int second, int tzHour,
                         int tzMinute)
        : Value(date)
    {
        time_.hour = hour;
        time_.minute = minute;
        time_.second = second;
        time_.tzHour = tzHour;
        time_.tzMinute = tzMinute;
    }

Project: exiv2
File: makernote_int.cpp

    size_t Nikon3MnHeader::size() const
    {
        return sizeOfSignature();
    }

Project: exiv2
File: xmp.cpp

    XMP_OptionBits xmpArrayOptionBits(Exiv2::XmpValue::XmpStruct xs)
    {
        XMP_OptionBits var(0);
        switch (xs) {
        case Exiv2::XmpValue::xsNone:
            break;
        case Exiv2::XmpValue::xsStruct:
            XMP_SetOption(var, kXMP_PropValueIsStruct);
            break;
        }
        return var;
    }

Project: exiv2
File: image.cpp

    XmpData& Image::xmpData()
    {
        return xmpData_;
    }

Project: exiv2
File: makernote_int.cpp

    int sonyCsSelector(uint16_t /*tag*/, const byte* /*pData*/, uint32_t /*size*/, TiffComponent* const pRoot)
    {
        std::string model = getExifModel(pRoot);
        if (model.empty()) return -1;
        int idx = 0;
        if (   model.find("DSLR-A330") != std::string::npos
            || model.find("DSLR-A380") != std::string::npos) {
            idx = 1;
        }
        return idx;
    }

Project: exiv2
File: actions.cpp

    int printStructure(std::ostream& out, Exiv2::PrintStructureOption option, const std::string& path)
    {
        if (!Exiv2::fileExists(path, true)) {
            std::cerr << path << ": " << _("Failed to open the file\n");
            return -1;
        }
        Exiv2::Image::UniquePtr image = Exiv2::ImageFactory::open(path);
        image->printStructure(out, option);
        return 0;
    }

Project: exiv2
File: psdimage.cpp

    uint32_t PsdImage::writeIptcData(const IptcData& iptcData, BasicIo& out) const
    {
        uint32_t resLength = 0;

        if (iptcData.count() > 0) {
            DataBuf rawIptc = IptcParser::encode(iptcData);
            if (rawIptc.size_ > 0) {
#ifdef DEBUG
                std::cerr << std::hex << "write: resourceId: " << kPhotoshopResourceID_IPTC_NAA << "\n";
                std::cerr << std::dec << "Writing IPTC_NAA: size: " << rawIptc.size_ << "\n";
#endif
                byte buf[8];
                if (out.write(reinterpret_cast<const byte*>(Photoshop::irbId_[0]), 4) != 4)
                    throw Error(kerImageWriteFailed);
                us2Data(buf, kPhotoshopResourceID_IPTC_NAA, bigEndian);
                if (out.write(buf, 2) != 2)
                    throw Error(kerImageWriteFailed);
                us2Data(buf, 0, bigEndian);                      // nullptr resource name
                if (out.write(buf, 2) != 2)
                    throw Error(kerImageWriteFailed);
                ul2Data(buf, (uint32_t)rawIptc.size_, bigEndian);
                if (out.write(buf, 4) != 4)
                    throw Error(kerImageWriteFailed);
                // Write encoded Iptc data
                if (out.write(rawIptc.pData_, rawIptc.size_) != rawIptc.size_)
                    throw Error(kerImageWriteFailed);
                resLength += (uint32_t)rawIptc.size_ + 12;
                if (rawIptc.size_ & 1)  // even padding
                {
                    buf[0] = 0;
                    if (out.write(buf, 1) != 1)
                        throw Error(kerImageWriteFailed);
                    resLength++;
                }
            }
        }
        return resLength;
    }

Project: exiv2
File: tiffcomposite_int.cpp

    uint32_t TiffIfdMakernote::baseOffset() const
    {
        if (!pHeader_) return 0;
        return pHeader_->baseOffset(mnOffset_);
    }

Project: exiv2
File: makernote_int.cpp

    bool Nikon3MnHeader::read(const byte* pData,
                              uint32_t    size,
                              ByteOrder   /*byteOrder*/)
    {
        if (!pData || size < sizeOfSignature()) return false;
        if (0 != memcmp(pData, signature_, 6)) return false;
        buf_.alloc(sizeOfSignature());
        std::memcpy(buf_.pData_, pData, buf_.size_);
        TiffHeader th;
        if (!th.read(buf_.pData_ + 10, 8)) return false;
        byteOrder_ = th.byteOrder();
        start_ = 10 + th.offset();
        return true;
    } // Nikon3MnHeader::read

Project: exiv2
File: convert.cpp

    void Converter::cnvXmpValue(const char* from, const char* to)
    {
        Exiv2::XmpData::iterator pos = xmpData_->findKey(XmpKey(from));
        if (pos == xmpData_->end()) return;
        if (!prepareExifTarget(to)) return;
        std::string value;
        if (!getTextValue(value, pos)) {
#ifndef SUPPRESS_WARNINGS
            EXV_WARNING << "Failed to convert " << from << " to " << to << "\n";
#endif
            return;
        }
        // Todo: Escape non-ASCII characters in XMP text values
        ExifKey key(to);
        Exifdatum ed(key);
        if (0 == ed.setValue(value)) {
            exifData_->add(ed);
        }
        if (erase_) xmpData_->erase(pos);
    }

Project: exiv2
File: tiffcomposite_int.cpp

    TiffDataEntryBase::~TiffDataEntryBase()
    {
    }

Project: exiv2
File: value.cpp

    Rational DataValue::toRational(long n) const
    {
        ok_ = true;
        return Rational(value_[n], 1);
    }

Project: exiv2
File: value.cpp

    int DateValue::read(const byte* buf, size_t len, ByteOrder /*byteOrder*/)
    {
        // Hard coded to read Iptc style dates
        if (len != 8) {
#ifndef SUPPRESS_WARNINGS
            EXV_WARNING << Error(kerUnsupportedDateFormat) << "\n";
#endif
            return 1;
        }
        // Make the buffer a 0 terminated C-string for sscanf
        char b[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0 };
        std::memcpy(b, reinterpret_cast<const char*>(buf), 8);
        int scanned = sscanf(b, "%4d%2d%2d",
                             &date_.year, &date_.month, &date_.day);
        if (scanned != 3) {
#ifndef SUPPRESS_WARNINGS
            EXV_WARNING << Error(kerUnsupportedDateFormat) << "\n";
#endif
            return 1;
        }
        return 0;
    }

Project: exiv2
File: xmp.cpp

    bool XmpData::empty() const
    {
        return count() == 0;
    }

Project: exiv2
File: actions.cpp

    int setModeAndPrintStructure(Exiv2::PrintStructureOption option, const std::string& path)
    {
        _setmode(_fileno(stdout), O_BINARY);
        return printStructure(std::cout, option, path);
    }

Project: exiv2
File: tiffcomposite_int.cpp

    uint32_t TiffIfdMakernote::writeHeader(IoWrapper& ioWrapper, ByteOrder byteOrder) const
    {
        if (!pHeader_) return 0;
        return (uint32_t)pHeader_->write(ioWrapper, byteOrder);
    }

Project: exiv2
File: tiffcomposite_int.cpp

    uint32_t TiffEntryBase::doSizeData() const
    {
        return 0;
    } // TiffEntryBase::doSizeData

Project: exiv2
File: preview.cpp

    PreviewImage::PreviewImage(const PreviewProperties& properties, DataBuf data)
        : properties_(properties)
    {
        pData_ = data.pData_;
        size_ = (uint32_t)data.size_;
        std::pair<byte*, long> ret = data.release();
        UNUSED(ret);
    }

Project: exiv2
File: tiffcomposite_int.cpp

    bool TiffBinaryArray::initialize(TiffComponent* const pRoot)
    {
        if (cfgSelFct_ == 0) return true; // Not a complex array

        int idx = cfgSelFct_(tag(), pData(), TiffEntryBase::doSize(), pRoot);
        if (idx > -1) {
            arrayCfg_ = &arraySet_[idx].cfg_;
            arrayDef_ = arraySet_[idx].def_;
            defSize_  = arraySet_[idx].defSize_;
        }
        return idx > -1;
    }

Project: exiv2
File: exif.cpp

    std::string Exifdatum::toString() const
    {
        return value_.get() == 0 ? "" : value_->toString();
    }

Project: exiv2
File: types.cpp

    static void checkDataBufBounds(const DataBuf& buf, size_t end) {
        enforce<std::invalid_argument>(end <= static_cast<size_t>(std::numeric_limits<long>::max()),
                                       "end of slice too large to be compared with DataBuf bounds.");
        enforce<std::out_of_range>(end <= buf.size_, "Invalid slice bounds specified");
    }

Project: exiv2
File: iptc.cpp

    DataBuf IptcParser::encode(const IptcData& iptcData)
    {
        DataBuf buf(iptcData.size());
        byte *pWrite = buf.pData_;

        // Copy the iptc data sets and sort them by record but preserve the order of datasets
        IptcMetadata sortedIptcData;
        std::copy(iptcData.begin(), iptcData.end(), std::back_inserter(sortedIptcData));
        std::stable_sort(sortedIptcData.begin(), sortedIptcData.end(), cmpIptcdataByRecord);

        IptcData::const_iterator iter = sortedIptcData.begin();
        IptcData::const_iterator end = sortedIptcData.end();
        for ( ; iter != end; ++iter) {
            // marker, record Id, dataset num
            *pWrite++ = marker_;
            *pWrite++ = static_cast<byte>(iter->record());
            *pWrite++ = static_cast<byte>(iter->tag());

            // extended or standard dataset?
            size_t dataSize = iter->size();
            if (dataSize > 32767) {
                // always use 4 bytes for extended length
                uint16_t sizeOfSize = 4 | 0x8000;
                us2Data(pWrite, sizeOfSize, bigEndian);
                pWrite += 2;
                ul2Data(pWrite, static_cast<uint32_t>(dataSize), bigEndian);
                pWrite += 4;
            }
            else {
                us2Data(pWrite, static_cast<uint16_t>(dataSize), bigEndian);
                pWrite += 2;
            }
            pWrite += iter->value().copy(pWrite, bigEndian);
        }

        return buf;
    } // IptcParser::encode

Project: exiv2
File: value.cpp

    std::string CommentValue::comment(const char* encoding) const
    {
        std::string c;
        if (value_.length() < 8) {
            return c;
        }
        c = value_.substr(8);
        if (charsetId() == unicode) {
            const char* from = encoding == 0 || *encoding == '\0' ? detectCharset(c) : encoding;
            convertStringCharset(c, from, "UTF-8");
        }
        return c;
    }

Project: exiv2
File: tiffvisitor_int.cpp

    void TiffEncoder::encodeOffsetEntry(TiffEntryBase* object, const Exifdatum* datum)
    {
        assert(object != 0);
        assert(datum != 0);

        size_t newSize = datum->size();
        if (newSize > object->size_) { // value doesn't fit, encode for intrusive writing
            setDirty();
            object->updateValue(datum->getValue(), byteOrder()); // clones the value
#ifdef DEBUG
            ExifKey key(object->tag(), groupName(object->group()));
            std::cerr << "UPDATING DATA     " << key;
            std::cerr << "\t\t\t ALLOCATED " << object->size() << " BYTES";
#endif
        }
        else {
            object->setValue(datum->getValue()); // clones the value
#ifdef DEBUG
            ExifKey key(object->tag(), groupName(object->group()));
            std::cerr << "NOT UPDATING      " << key;
            std::cerr << "\t\t\t PRESERVE VALUE DATA";
#endif
        }

    } // TiffEncoder::encodeOffsetEntry

Project: exiv2
File: crwimage.cpp

    void CrwParser::encode(
              Blob&     blob,
        const byte*     pData,
              uint32_t  size,
        const CrwImage* pCrwImage
    )
    {
        // Parse image, starting with a CIFF header component
        CiffHeader::UniquePtr head(new CiffHeader);
        if (size != 0) {
            head->read(pData, size);
        }

        // Encode Exif tags from image into the CRW parse tree and write the
        // structure to the binary image blob
        CrwMap::encode(head.get(), *pCrwImage);
        head->write(blob);

    } // CrwParser::encode

Project: exiv2
File: tiffcomposite_int.cpp

    void TiffSizeEntry::doEncode(TiffEncoder& encoder, const Exifdatum* datum)
    {
        encoder.encodeSizeEntry(this, datum);
    } // TiffSizeEntry::doEncode

Project: exiv2
File: image.cpp

    void Image::printTiffStructure(BasicIo& io, std::ostream& out, Exiv2::PrintStructureOption option,int depth,size_t offset /*=0*/)
    {
        if ( option == kpsBasic || option == kpsXMP || option == kpsRecursive || option == kpsIccProfile ) {
            // buffer
            const size_t dirSize = 32;
            DataBuf  dir(dirSize);

            // read header (we already know for certain that we have a Tiff file)
            io.read(dir.pData_,  8);
            char c = (char) dir.pData_[0] ;
            bool bSwap   = ( c == 'M' && isLittleEndianPlatform() )
                        || ( c == 'I' && isBigEndianPlatform()    )
                        ;
            uint32_t start = byteSwap4(dir,4,bSwap);
            printIFDStructure(io,out,option,start+(uint32_t)offset,bSwap,c,depth);
        }
    }

Project: exiv2
File: exif.cpp

    std::ostream& Exifdatum::write(std::ostream& os, const ExifData* pMetadata) const
    {
        if (value().count() == 0) return os;
        PrintFct fct = printValue;
        const TagInfo* ti = Internal::tagInfo(tag(), static_cast<IfdId>(ifdId()));
        if (ti != 0) fct = ti->printFct_;
        return fct(os, value(), pMetadata);
    }

Project: exiv2
File: image.cpp

    void Image::setXmpData(const XmpData& xmpData)
    {
        xmpData_ = xmpData;
        writeXmpFromPacket(false);
    }

Project: exiv2
File: tiff-test.cpp

void mini1(const char* path)
{
    ExifData exifData;
    Blob blob;
    WriteMethod wm;

    // Write nothing to a new structure, without a previous binary image
    wm = ExifParser::encode(blob, 0, 0, bigEndian, exifData);
    enforce(wm == wmIntrusive, Exiv2::kerErrorMessage, "encode returned an unexpected value");
    assert(blob.size() == 0);
    std::cout << "Test 1: Writing empty Exif data without original binary data: ok.\n";

    // Write nothing, this time with a previous binary image
    DataBuf buf = readFile(path);
    wm = ExifParser::encode(blob, buf.pData_, (uint32_t)buf.size_, bigEndian, exifData);
    enforce(wm == wmIntrusive, Exiv2::kerErrorMessage, "encode returned an unexpected value");
    assert(blob.size() == 0);
    std::cout << "Test 2: Writing empty Exif data with original binary data: ok.\n";

    // Write something to a new structure, without a previous binary image
    exifData["Exif.Photo.DateTimeOriginal"] = "Yesterday at noon";
    wm = ExifParser::encode(blob, 0, 0, bigEndian, exifData);
    enforce(wm == wmIntrusive, Exiv2::kerErrorMessage, "encode returned an unexpected value");
    std::cout << "Test 3: Wrote non-empty Exif data without original binary data:\n";
    exifData.clear();
    ByteOrder bo = ExifParser::decode(exifData, &blob[0], (uint32_t) blob.size());
    enforce(bo == bigEndian, Exiv2::kerErrorMessage, "decode returned an unexpected value");
    print(exifData);
}

Project: exiv2
File: value.cpp

    Rational XmpArrayValue::toRational(long n) const
    {
        return parseRational(value_[n], ok_);
    }

Project: exiv2
File: makernote_int.cpp

    size_t Olympus2MnHeader::write(IoWrapper& ioWrapper,
                                    ByteOrder /*byteOrder*/) const
    {
        ioWrapper.write(signature_, sizeOfSignature());
        return sizeOfSignature();
    } // Olympus2MnHeader::write

Project: exiv2
File: preview.cpp

    DataBuf LoaderTiff::getData() const
    {
        const ExifData &exifData = image_.exifData();

        ExifData preview;

        // copy tags
        for (ExifData::const_iterator pos = exifData.begin(); pos != exifData.end(); ++pos) {
            if (pos->groupName() == group_) {
                /*
                   Write only the necessary TIFF image tags
                   tags that especially could cause problems are:
                   "NewSubfileType" - the result is no longer a thumbnail, it is a standalone image
                   "Orientation" - this tag typically appears only in the "Image" group. Deleting it ensures
                                   consistent result for all previews, including JPEG
                */
                uint16_t tag = pos->tag();
                if (tag != 0x00fe && tag != 0x00ff && Internal::isTiffImageTag(tag, Internal::ifd0Id)) {
                    preview.add(ExifKey(tag, "Image"), &pos->value());
                }
            }
        }

        Value &dataValue = const_cast<Value&>(preview["Exif.Image." + offsetTag_].value());

        if (dataValue.sizeDataArea() == 0) {
            // image data are not available via exifData, read them from image_.io()
            BasicIo &io = image_.io();

            if (io.open() != 0) {
                throw Error(kerDataSourceOpenFailed, io.path(), strError());
            }
            IoCloser closer(io);

            const Exiv2::byte* base = io.mmap();

            const Value &sizes = preview["Exif.Image." + sizeTag_].value();

            if (sizes.count() == dataValue.count()) {
                if (sizes.count() == 1) {
                    // this saves one copying of the buffer
                    uint32_t offset = dataValue.toLong(0);
                    uint32_t size = sizes.toLong(0);
                    if (Safe::add(offset, size) <= static_cast<uint32_t>(io.size()))
                        dataValue.setDataArea(base + offset, size);
                }
                else {
                    // FIXME: the buffer is probably copied twice, it should be optimized
                    enforce(size_ <= static_cast<uint32_t>(io.size()), kerCorruptedMetadata);
                    DataBuf buf(size_);
                    uint32_t idxBuf = 0;
                    for (int i = 0; i < sizes.count(); i++) {
                        uint32_t offset = dataValue.toLong(i);
                        uint32_t size = sizes.toLong(i);
                        enforce(Safe::add(idxBuf, size) < size_, kerCorruptedMetadata);
                        if (size!=0 && Safe::add(offset, size) <= static_cast<uint32_t>(io.size()))
                            memcpy(&buf.pData_[idxBuf], base + offset, size);
                        idxBuf += size;
                    }
                    dataValue.setDataArea(buf.pData_, (uint32_t)buf.size_);
                }
            }
        }

        // Fix compression value in the CR2 IFD2 image
        if (0 == strcmp(group_, "Image2") && image_.mimeType() == "image/x-canon-cr2") {
            preview["Exif.Image.Compression"] = uint16_t(1);
        }

        // write new image
        MemIo mio;
        IptcData emptyIptc;
        XmpData  emptyXmp;
        TiffParser::encode(mio, 0, 0, Exiv2::littleEndian, preview, emptyIptc, emptyXmp);
        return DataBuf(mio.mmap(), (long) mio.size());
    }

Project: exiv2
File: xmp.cpp

    Xmpdatum::Xmpdatum(const Xmpdatum& rhs)
        : Metadatum(rhs), p_(new Impl(*rhs.p_))
    {
    }

Project: exiv2
File: exif.cpp

        explicit FindExifdatumByKey(const std::string& key) : key_(key)
        {
        }

Project: exiv2
File: jpgimage.cpp

    int JpegImage::writeHeader(BasicIo& outIo) const
    {
        // Jpeg header
        byte tmpBuf[2];
        tmpBuf[0] = 0xff;
        tmpBuf[1] = soi_;
        if (outIo.write(tmpBuf, 2) != 2) return 4;
        if (outIo.error()) return 4;
        return 0;
    }

Project: exiv2
File: tiffcomposite_int.cpp

    bool cmpTagLt(TiffComponent const* lhs, TiffComponent const* rhs)
    {
        assert(lhs != 0);
        assert(rhs != 0);
        if (lhs->tag() != rhs->tag()) return lhs->tag() < rhs->tag();
        return lhs->idx() < rhs->idx();
    }

Project: exiv2
File: xmp.cpp

    Rational Xmpdatum::toRational(long n) const
    {
        return p_->value_.get() == 0 ? Rational(-1, 1) : p_->value_->toRational(n);
    }

Project: exiv2
File: tiffimage.cpp

    ByteOrder TiffHeaderBase::byteOrder() const
    {
        return byteOrder_;
    }

Project: exiv2
File: value.cpp

    DateValue::DateValue(int year, int month, int day)
        : Value(date)
    {
        date_.year = year;
        date_.month = month;
        date_.day = day;
    }

Project: exiv2
File: convert.cpp

    bool iso88591ToUtf8(std::string& str)
    {
        bool ret = mb2wc(28591, str);
        if (ret) ret = wc2mb(CP_UTF8, str);
        return ret;
    }

Project: exiv2
File: pngchunk_int.cpp

        std::string PngChunk::writeRawProfile(const std::string& profileData, const char* profileType)
        {
            static byte hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

            std::ostringstream oss;
            oss << '\n' << profileType << '\n' << std::setw(8) << profileData.size();
            const char* sp = profileData.data();
            for (std::string::size_type i = 0; i < profileData.size(); ++i) {
                if (i % 36 == 0)
                    oss << '\n';
                oss << hex[((*sp >> 4) & 0x0f)];
                oss << hex[((*sp++) & 0x0f)];
            }
            oss << '\n';
            return oss.str();

        }  // PngChunk::writeRawProfile

Project: exiv2
File: tiffcomposite_int.cpp

    uint32_t TiffIfdMakernote::sizeHeader() const
    {
        if (!pHeader_) return 0;
        return (uint32_t)pHeader_->size();
    }

Project: exiv2
File: exif.cpp

    void ExifData::sortByTag()
    {
        exifMetadata_.sort(cmpMetadataByTag);
    }

Project: exiv2
File: makernote_int.cpp

    size_t SigmaMnHeader::write(IoWrapper& ioWrapper,
                                  ByteOrder /*byteOrder*/) const
    {
        ioWrapper.write(signature1_, sizeOfSignature());
        return sizeOfSignature();
    } // SigmaMnHeader::write

Project: exiv2
File: basicio.cpp

    size_t FileIo::write(BasicIo& src)
    {
        assert(p_->fp_ != 0);
        if (static_cast<BasicIo*>(this) == &src) return 0;
        if (!src.isopen()) return 0;
        if (p_->switchMode(Impl::opWrite) != 0) return 0;

        byte buf[4096];
        size_t readCount = 0;
        size_t writeTotal = 0;
        while ((readCount = src.read(buf, sizeof(buf)))) {
            const size_t writeCount = static_cast<long>(std::fwrite(buf, 1, static_cast<size_t>(readCount), p_->fp_));
            writeTotal += writeCount;
            if (writeCount != readCount) {
                // try to reset back to where write stopped
                src.seek(writeCount-readCount, BasicIo::cur);
                break;
            }
        }

        return writeTotal;
    }

Project: exiv2
File: basicio.cpp

    HttpIo::HttpImpl::HttpImpl(const std::string& url, size_t blockSize)
        : Impl(url, blockSize)
        , hostInfo_(Exiv2::Uri::Parse(url))
    {
        Exiv2::Uri::Decode(hostInfo_);
    }

Project: exiv2
File: types.cpp

    long us2Data(byte* buf, uint16_t s, ByteOrder byteOrder)
    {
        if (byteOrder == littleEndian) {
            buf[0] = (byte) (s & 0x00ff);
            buf[1] = (byte)((s & 0xff00) >> 8);
        }
        else {
            buf[0] = (byte)((s & 0xff00) >> 8);
            buf[1] = (byte) (s & 0x00ff);
        }
        return 2;
    }

Project: exiv2
File: xmp.cpp

    XmpData::iterator XmpData::begin()
    {
        return xmpMetadata_.begin();
    }

Project: exiv2
File: actions.cpp

    std::unique_ptr<Insert> Insert::clone() const
    {
        return std::unique_ptr<Insert>(clone_());
    }

Project: exiv2
File: value.cpp

    Rational StringValueBase::toRational(long n) const
    {
        ok_ = true;
        return Rational(value_[n], 1);
    }

Project: exiv2
File: value.cpp

    AsciiValue::AsciiValue(const std::string& buf)
        : StringValueBase(asciiString, buf)
    {
    }

Project: exiv2
File: jpgimage.cpp

    int ExvImage::writeHeader(BasicIo& outIo) const
    {
        // Exv header
        byte tmpBuf[7];
        tmpBuf[0] = 0xff;
        tmpBuf[1] = 0x01;
        std::memcpy(tmpBuf + 2, exiv2Id_, 5);
        if (outIo.write(tmpBuf, 7) != 7) return 4;
        if (outIo.error()) return 4;
        return 0;
    }

Project: exiv2
File: tiffvisitor_int.cpp

    void TiffCopier::visitDataEntry(TiffDataEntry* object)
    {
        copyObject(object);
    }

Project: exiv2
File: image.cpp

    bool Image::isPrintXMP(uint16_t type, Exiv2::PrintStructureOption option)
    {
        return type == 700 && option == kpsXMP;
    }

Project: exiv2
File: makernote_int.cpp

    uint32_t Olympus2MnHeader::baseOffset(uint32_t mnOffset) const
    {
        return mnOffset;
    }

Project: exiv2
File: tiffcomposite_int.cpp

    uint32_t TiffMnEntry::doWrite(IoWrapper& ioWrapper,
                                  ByteOrder byteOrder,
                                  int32_t   offset,
                                  uint32_t  valueIdx,
                                  uint32_t  dataIdx,
                                  uint32_t& imageIdx)
    {
        if (!mn_) {
            return TiffEntryBase::doWrite(ioWrapper, byteOrder, offset, valueIdx, dataIdx, imageIdx);
        }
        return mn_->write(ioWrapper, byteOrder, offset + valueIdx, uint32_t(-1), uint32_t(-1), imageIdx);
    } // TiffMnEntry::doWrite

Project: exiv2
File: types.cpp

    DataBuf::DataBuf(const byte* pData, size_t size)
        : pData_(0), size_(0)
    {
        if (size > 0) {
            pData_ = new byte[size];
            std::memcpy(pData_, pData, size);
            size_ = size;
        }
    }

Project: exiv2
File: preview.cpp

        virtual bool valid() const { return valid_; }

Project: exiv2
File: tiffvisitor_int.cpp

    void TiffFinder::visitSizeEntry(TiffSizeEntry* object)
    {
        findObject(object);
    }

Project: exiv2
File: convert.cpp

    void Converter::cnvExifFlash(const char* from, const char* to)
    {
        Exiv2::ExifData::iterator pos = exifData_->findKey(ExifKey(from));
        if (pos == exifData_->end() || pos->count() == 0) return;
        if (!prepareXmpTarget(to)) return;
        int value = pos->toLong();
        if (!pos->value().ok()) {
#ifndef SUPPRESS_WARNINGS
            EXV_WARNING << "Failed to convert " << from << " to " << to << "\n";
#endif
            return;
        }

        (*xmpData_)["Xmp.exif.Flash/exif:Fired"] = static_cast<bool>(value & 1);
        (*xmpData_)["Xmp.exif.Flash/exif:Return"] = (value >> 1) & 3;
        (*xmpData_)["Xmp.exif.Flash/exif:Mode"] = (value >> 3) & 3;
        (*xmpData_)["Xmp.exif.Flash/exif:Function"] = static_cast<bool>((value >> 5) & 1);
        (*xmpData_)["Xmp.exif.Flash/exif:RedEyeMode"] = static_cast<bool>((value >> 6) & 1);

        if (erase_) exifData_->erase(pos);
    }

Project: exiv2
File: tiffvisitor_int.cpp

    void TiffEncoder::visitBinaryArrayEnd(TiffBinaryArray* object)
    {
        assert(object != 0);

        if (object->cfg() == 0 || !object->decoded()) return;
        std::uint32_t size = object->TiffEntryBase::doSize();
        if (size == 0) return;
        if (!object->initialize(pRoot_)) return;

        // Re-encrypt buffer if necessary
        const CryptFct cryptFct = object->cfg()->cryptFct_;
        if (cryptFct != 0) {
            const byte* pData = object->pData();
            DataBuf buf = cryptFct(object->tag(), pData, size, pRoot_);
            if (buf.size_ > 0) {
                pData = buf.pData_;
                size = static_cast<std::uint32_t>(buf.size_);
            }
            if (!object->updOrigDataBuf(pData, size)) {
                setDirty();
            }
        }
    }

Project: exiv2
File: actions.cpp

    int Insert::insertXmpPacket(const std::string& path, const std::string& xmpPath) const
    {
        int rc = 0;
        bool bStdin = xmpPath == "-";
        if (bStdin) {
            Exiv2::DataBuf xmpBlob;
            Params::instance().getStdin(xmpBlob);
            rc = insertXmpPacket(path, xmpBlob, true);
        } else {
            if (!Exiv2::fileExists(xmpPath, true)) {
                std::cerr << xmpPath << ": " << _("Failed to open the file\n");
                rc = -1;
            }
            if (rc == 0 && !Exiv2::fileExists(path, true)) {
                std::cerr << path << ": " << _("Failed to open the file\n");
                rc = -1;
            }
            if (rc == 0) {
                Exiv2::DataBuf xmpBlob = Exiv2::readFile(xmpPath);
                rc = insertXmpPacket(path, xmpBlob);
            }
        }
        return rc;

    }

Project: exiv2
File: makernote_int.cpp

    SamsungMnHeader::SamsungMnHeader()
    {
        read(0, 0, invalidByteOrder);
    }

Project: exiv2
File: types.cpp

    double getDouble(const byte* buf, ByteOrder byteOrder)
    {
        // This algorithm assumes that the internal representation of the double
        // type is the 8-byte IEEE 754 binary64 format, which is common but not
        // required by the C++ standard.
        static_assert(sizeof(double) == 8, "double type requires 8-byte IEEE 754 binary64 format");
        union {
            uint64_t ull_;
            double   d_;
        } u;
        u.ull_ = 0;
        if (byteOrder == littleEndian) {
            u.ull_ =   static_cast<uint64_t>(buf[7]) << 56
                     | static_cast<uint64_t>(buf[6]) << 48
                     | static_cast<uint64_t>(buf[5]) << 40
                     | static_cast<uint64_t>(buf[4]) << 32
                     | static_cast<uint64_t>(buf[3]) << 24
                     | static_cast<uint64_t>(buf[2]) << 16
                     | static_cast<uint64_t>(buf[1]) <<  8
                     | static_cast<uint64_t>(buf[0]);
        }
        else {
            u.ull_ =   static_cast<uint64_t>(buf[0]) << 56
                     | static_cast<uint64_t>(buf[1]) << 48
                     | static_cast<uint64_t>(buf[2]) << 40
                     | static_cast<uint64_t>(buf[3]) << 32
                     | static_cast<uint64_t>(buf[4]) << 24
                     | static_cast<uint64_t>(buf[5]) << 16
                     | static_cast<uint64_t>(buf[6]) <<  8
                     | static_cast<uint64_t>(buf[7]);
        }
        return u.d_;
    }

Project: exiv2
File: makernote_int.cpp

    size_t PentaxDngMnHeader::size() const
    {
        return header_.size_;
    }

Project: exiv2
File: image.cpp

    Image::UniquePtr ImageFactory::create(ImageType type)
    {
        BasicIo::UniquePtr io(new MemIo);
        Image::UniquePtr image = create(type, std::move(io));
        if (image.get() == 0) {
            throw Error(kerUnsupportedImageType, static_cast<int>(type));
        }
        return image;
    }

Project: exiv2
File: convert.cpp

        bool overwrite() const { return overwrite_; }

Project: exiv2
File: image.cpp

    bool Image::good() const
    {
        if (io_->open() != 0) return false;
        IoCloser closer(*io_);
        return ImageFactory::checkType(imageType_, *io_, false);
    }

Project: exiv2
File: jp2image.cpp

    void Jp2Image::doWriteMetadata(BasicIo& outIo)
    {
        if (!io_->isopen()) throw Error(kerInputDataReadFailed);
        if (!outIo.isopen()) throw Error(kerImageWriteFailed);

#ifdef DEBUG
        std::cout << "Exiv2::Jp2Image::doWriteMetadata: Writing JPEG-2000 file " << io_->path() << std::endl;
        std::cout << "Exiv2::Jp2Image::doWriteMetadata: tmp file created " << outIo.path() << std::endl;
#endif

        // Ensure that this is the correct image type
        if (!isJp2Type(*io_, true))
        {
            if (io_->error() || io_->eof()) throw Error(kerInputDataReadFailed);
            throw Error(kerNoImageInInputData);
        }

        // Write JPEG2000 Signature.
        if (outIo.write(Jp2Signature, 12) != 12) throw Error(kerImageWriteFailed);

        Jp2BoxHeader box = {0,0};

        byte    boxDataSize[4];
        byte    boxUUIDtype[4];
        DataBuf bheaderBuf(8);     // Box header : 4 bytes (data size) + 4 bytes (box type).

        // FIXME: Andreas, why the loop do not stop when EOF is taken from _io. The loop go out by an exception
        // generated by a zero size data read.

        while(io_->tell() < (long) io_->size())
        {
#ifdef DEBUG
            std::cout << "Exiv2::Jp2Image::doWriteMetadata: Position: " << io_->tell() << " / " << io_->size() << std::endl;
#endif

            // Read chunk header.

            std::memset(bheaderBuf.pData_, 0x00, bheaderBuf.size_);
            size_t bufRead = io_->read(bheaderBuf.pData_, bheaderBuf.size_);
            if (io_->error()) throw Error(kerFailedToReadImageData);
            if (bufRead != bheaderBuf.size_) throw Error(kerInputDataReadFailed);

            // Decode box header.

            box.length = getLong(bheaderBuf.pData_,     bigEndian);
            box.type   = getLong(bheaderBuf.pData_ + 4, bigEndian);

#ifdef DEBUG
            std::cout << "Exiv2::Jp2Image::doWriteMetadata: box type: " << toAscii(box.type)
                      << " length: " << box.length << std::endl;
#endif

            if (box.length == 0)
            {
#ifdef DEBUG
                std::cout << "Exiv2::Jp2Image::doWriteMetadata: Null Box size has been found. "
                             "This is the last box of file." << std::endl;
#endif
                box.length = (uint32_t) (io_->size() - io_->tell() + 8);
            }
            if (box.length == 1)
            {
                // FIXME. Special case. the real box size is given in another place.
            }

            // Read whole box : Box header + Box data (not fixed size - can be null).

            DataBuf boxBuf(box.length);                             // Box header (8 bytes) + box data.
            memcpy(boxBuf.pData_, bheaderBuf.pData_, 8);               // Copy header.
            bufRead = io_->read(boxBuf.pData_ + 8, box.length - 8); // Extract box data.
            if (io_->error())
            {
#ifdef DEBUG
                std::cout << "Exiv2::Jp2Image::doWriteMetadata: Error reading source file" << std::endl;
#endif

                throw Error(kerFailedToReadImageData);
            }

            if (bufRead != (long)(box.length - 8))
            {
#ifdef DEBUG
                std::cout << "Exiv2::Jp2Image::doWriteMetadata: Cannot read source file data" << std::endl;
#endif
                throw Error(kerInputDataReadFailed);
            }

            switch(box.type)
            {
                case kJp2BoxTypeJp2Header:
                {
                    DataBuf newBuf;
                    encodeJp2Header(boxBuf,newBuf);
#ifdef DEBUG
                    std::cout << "Exiv2::Jp2Image::doWriteMetadata: Write JP2Header box (length: " << box.length << ")" << std::endl;
#endif
                    if (outIo.write(newBuf.pData_, newBuf.size_) != newBuf.size_) throw Error(kerImageWriteFailed);

                    // Write all updated metadata here, just after JP2Header.

                    if (exifData_.count() > 0)
                    {
                        // Update Exif data to a new UUID box

                        Blob blob;
                        ExifParser::encode(blob, littleEndian, exifData_);
                        if (blob.size())
                        {
                            DataBuf rawExif(static_cast<long>(blob.size()));
                            memcpy(rawExif.pData_, &blob[0], blob.size());

                            DataBuf boxData(8 + 16 + rawExif.size_);
                            ul2Data(boxDataSize, static_cast<uint32_t>(boxData.size_), Exiv2::bigEndian);
                            ul2Data(boxUUIDtype, kJp2BoxTypeUuid, Exiv2::bigEndian);
                            memcpy(boxData.pData_,          boxDataSize,    4);
                            memcpy(boxData.pData_ + 4,      boxUUIDtype,    4);
                            memcpy(boxData.pData_ + 8,      kJp2UuidExif,   16);
                            memcpy(boxData.pData_ + 8 + 16, rawExif.pData_, rawExif.size_);

#ifdef DEBUG
                            std::cout << "Exiv2::Jp2Image::doWriteMetadata: Write box with Exif metadata (length: "
                                      << boxData.size_ << std::endl;
#endif
                            if (outIo.write(boxData.pData_, boxData.size_) != boxData.size_) throw Error(kerImageWriteFailed);
                        }
                    }

                    if (iptcData_.count() > 0)
                    {
                        // Update Iptc data to a new UUID box

                        DataBuf rawIptc = IptcParser::encode(iptcData_);
                        if (rawIptc.size_ > 0)
                        {
                            DataBuf boxData(8 + 16 + rawIptc.size_);
                            ul2Data(boxDataSize, (uint32_t)boxData.size_, Exiv2::bigEndian);
                            ul2Data(boxUUIDtype, kJp2BoxTypeUuid, Exiv2::bigEndian);
                            memcpy(boxData.pData_,          boxDataSize,    4);
                            memcpy(boxData.pData_ + 4,      boxUUIDtype,    4);
                            memcpy(boxData.pData_ + 8,      kJp2UuidIptc,   16);
                            memcpy(boxData.pData_ + 8 + 16, rawIptc.pData_, rawIptc.size_);

#ifdef DEBUG
                            std::cout << "Exiv2::Jp2Image::doWriteMetadata: Write box with Iptc metadata (length: "
                                      << boxData.size_ << std::endl;
#endif
                            if (outIo.write(boxData.pData_, boxData.size_) != boxData.size_) throw Error(kerImageWriteFailed);
                        }
                    }

                    if (writeXmpFromPacket() == false)
                    {
                        if (XmpParser::encode(xmpPacket_, xmpData_) > 1)
                        {
#ifndef SUPPRESS_WARNINGS
                            EXV_ERROR << "Failed to encode XMP metadata." << std::endl;
#endif
                        }
                    }
                    if (xmpPacket_.size() > 0)
                    {
                        // Update Xmp data to a new UUID box

                        DataBuf xmp(reinterpret_cast<const byte*>(xmpPacket_.data()), static_cast<long>(xmpPacket_.size()));
                        DataBuf boxData(8 + 16 + xmp.size_);
                        ul2Data(boxDataSize, (uint32_t)boxData.size_, Exiv2::bigEndian);
                        ul2Data(boxUUIDtype, kJp2BoxTypeUuid, Exiv2::bigEndian);
                        memcpy(boxData.pData_,          boxDataSize,  4);
                        memcpy(boxData.pData_ + 4,      boxUUIDtype,  4);
                        memcpy(boxData.pData_ + 8,      kJp2UuidXmp,  16);
                        memcpy(boxData.pData_ + 8 + 16, xmp.pData_,   xmp.size_);

#ifdef DEBUG
                        std::cout << "Exiv2::Jp2Image::doWriteMetadata: Write box with XMP metadata (length: "
                                  << boxData.size_ << ")" << std::endl;
#endif
                        if (outIo.write(boxData.pData_, boxData.size_) != boxData.size_) throw Error(kerImageWriteFailed);
                    }

                    break;
                }

                case kJp2BoxTypeUuid:
                {
                    if(memcmp(boxBuf.pData_ + 8, kJp2UuidExif, 16) == 0)
                    {
#ifdef DEBUG
                        std::cout << "Exiv2::Jp2Image::doWriteMetadata: strip Exif Uuid box" << std::endl;
#endif
                    }
                    else if(memcmp(boxBuf.pData_ + 8, kJp2UuidIptc, 16) == 0)
                    {
#ifdef DEBUG
                        std::cout << "Exiv2::Jp2Image::doWriteMetadata: strip Iptc Uuid box" << std::endl;
#endif
                    }
                    else if(memcmp(boxBuf.pData_ + 8, kJp2UuidXmp,  16) == 0)
                    {
#ifdef DEBUG
                        std::cout << "Exiv2::Jp2Image::doWriteMetadata: strip Xmp Uuid box" << std::endl;
#endif
                    }
                    else
                    {
#ifdef DEBUG
                        std::cout << "Exiv2::Jp2Image::doWriteMetadata: write Uuid box (length: " << box.length << ")" << std::endl;
#endif
                        if (outIo.write(boxBuf.pData_, boxBuf.size_) != boxBuf.size_) throw Error(kerImageWriteFailed);
                    }
                    break;
                }

                default:
                {
#ifdef DEBUG
                    std::cout << "Exiv2::Jp2Image::doWriteMetadata: write box (length: " << box.length << ")" << std::endl;
#endif
                    if (outIo.write(boxBuf.pData_, boxBuf.size_) != boxBuf.size_) throw Error(kerImageWriteFailed);

                    break;
                }
            }
        }

#ifdef DEBUG
        std::cout << "Exiv2::Jp2Image::doWriteMetadata: EOF" << std::endl;
#endif

    } // Jp2Image::doWriteMetadata

Project: exiv2
File: tiffvisitor_int.cpp

    Exiv2::ByteOrder stringToByteOrder(const std::string& val)
    {
        Exiv2::ByteOrder bo = Exiv2::invalidByteOrder;
        if (0 == strcmp("II", val.c_str())) bo = Exiv2::littleEndian;
        else if (0 == strcmp("MM", val.c_str())) bo = Exiv2::bigEndian;

        return bo;
    }

Project: exiv2
File: xmp.cpp

    void XmpData::clear()
    {
        xmpMetadata_.clear();
    }

Project: exiv2
File: bigtiffimage.cpp

    Image::UniquePtr newBigTiffInstance(BasicIo::UniquePtr io, bool)
    {
        return Image::UniquePtr(new BigTiffImage(std::move(io)));
    }

Project: exiv2
File: tiffvisitor_int.cpp

    void TiffReader::visitBinaryArray(TiffBinaryArray* object)
    {
        assert(object != 0);

        if (!postProc_) {
            // Defer reading children until after all other components are read, but
            // since state (offset) is not set during post-processing, read entry here
            readTiffEntry(object);
            object->iniOrigDataBuf();
            postList_.push_back(object);
            return;
        }

        // Check duplicates
        TiffFinder finder(object->tag(), object->group());
        pRoot_->accept(finder);
        TiffEntryBase* te = dynamic_cast<TiffEntryBase*>(finder.result());
        if (te && te->idx() != object->idx()) {
#ifndef SUPPRESS_WARNINGS
            EXV_WARNING << "Not decoding duplicate binary array tag 0x"
                        << std::setw(4) << std::setfill('0') << std::hex
                        << object->tag() << std::dec << ", group "
                        << groupName(object->group()) << ", idx " << object->idx()
                        << "\n";
#endif
            object->setDecoded(false);
            return;
        }

        if (object->TiffEntryBase::doSize() == 0) return;
        if (!object->initialize(pRoot_)) return;
        const ArrayCfg* cfg = object->cfg();
        if (cfg == 0) return;

        const CryptFct cryptFct = cfg->cryptFct_;
        if (cryptFct != 0) {
            const byte* pData = object->pData();
            int32_t size = object->TiffEntryBase::doSize();
            DataBuf buf = cryptFct(object->tag(), pData, size, pRoot_);
            if (buf.size_ > 0) object->setData(buf);
        }

        const ArrayDef* defs = object->def();
        const ArrayDef* defsEnd = defs + object->defSize();
        const ArrayDef* def = &cfg->elDefaultDef_;
        ArrayDef gap = *def;

        for (uint32_t idx = 0; idx < object->TiffEntryBase::doSize(); ) {
            if (defs) {
                def = std::find(defs, defsEnd, idx);
                if (def == defsEnd) {
                    if (cfg->concat_) {
                        // Determine gap-size
                        const ArrayDef* xdef = defs;
                        for (; xdef != defsEnd && xdef->idx_ <= idx; ++xdef) {}
                        uint32_t gapSize = 0;
                        if (xdef != defsEnd && xdef->idx_ > idx) {
                            gapSize = xdef->idx_ - idx;
                        }
                        else {
                            gapSize = object->TiffEntryBase::doSize() - idx;
                        }
                        gap.idx_ = idx;
                        gap.tiffType_ = cfg->elDefaultDef_.tiffType_;
                        gap.count_ = gapSize / cfg->tagStep();
                        if (gap.count_ * cfg->tagStep() != gapSize) {
                            gap.tiffType_ = ttUndefined;
                            gap.count_ = gapSize;
                        }
                        def = &gap;
                    }
                    else {
                        def = &cfg->elDefaultDef_;
                    }
                }
            }
            idx += object->addElement(idx, *def); // idx may be different from def->idx_
        }

    } // TiffReader::visitBinaryArray

Project: exiv2
File: value.cpp

    int TimeValue::scanTime6(const char* buf, const char* format)
    {
        int rc = 1;
        Time t;
        char plusMinus;
        int scanned = sscanf(buf, format, &t.hour, &t.minute, &t.second,
                             &plusMinus, &t.tzHour, &t.tzMinute);
        if (   scanned    == 6
            && t.hour     >= 0 && t.hour     < 24
            && t.minute   >= 0 && t.minute   < 60
            && t.second   >= 0 && t.second   < 60
            && t.tzHour   >= 0 && t.tzHour   < 24
            && t.tzMinute >= 0 && t.tzMinute < 60) {
            time_ = t;
            if (plusMinus == '-') {
                time_.tzHour *= -1;
                time_.tzMinute *= -1;
            }
            rc = 0;
        }
        return rc;
    }

Project: exiv2
File: value.cpp

    Rational TimeValue::toRational(long n) const
    {
        return Rational(toLong(n), 1);
    }

Project: exiv2
File: convert.cpp

    bool wc2mb(UINT cp, std::string& str)
    {
        if (str.empty())
            return true;
        if (str.size() & 1) {
#ifdef DEBUG
            EXV_DEBUG << "wc2mb: Size " << str.size() << " of input string is not even.\n";
#endif
            return false;
        }
        int len = WideCharToMultiByte(cp, 0, (LPCWSTR)str.data(), (int)str.size() / 2, 0, 0, 0, 0);
        if (len == 0) {
#ifdef DEBUG
            EXV_DEBUG << "wc2mb: Failed to determine required size of output buffer.\n";
#endif
            return false;
        }
        std::vector<std::string::value_type> out;
        out.reserve(len);
        int ret = WideCharToMultiByte(cp, 0, (LPCWSTR)str.data(), (int)str.size() / 2, (LPSTR)out.data(), len, 0, 0);
        if (ret == 0) {
#ifdef DEBUG
            EXV_DEBUG << "wc2mb: Failed to convert the input string to a multi byte string.\n";
#endif
            return false;
        }
        str.assign(out.data(), static_cast<size_t>(len));
        return true;
    }

Project: exiv2
File: iptc.cpp

    size_t Iptcdatum::size() const
    {
        return value_.get() == 0 ? 0 : value_->size();
    }

Project: exiv2
File: tiffvisitor_int.cpp

    TiffFinder::~TiffFinder()
    {
    }

Project: exiv2
File: tiffcomposite_int.cpp

    TiffComponent* TiffIfdMakernote::doAddChild(TiffComponent::UniquePtr tiffComponent)
    {
        return ifd_.addChild(std::move(tiffComponent));
    }

Project: exiv2
File: tiffcomposite_int.cpp

    TiffComponent::UniquePtr newTiffBinaryElement(uint16_t tag, IfdId group)
    {
        return TiffComponent::UniquePtr(new TiffBinaryElement(tag, group));
    }

Project: exiv2
File: iptc.cpp

    Iptcdatum& Iptcdatum::operator=(const Iptcdatum& rhs)
    {
        if (this == &rhs) return *this;
        Metadatum::operator=(rhs);

        key_.reset();
        if (rhs.key_.get() != 0) key_ = rhs.key_->clone(); // deep copy

        value_.reset();
        if (rhs.value_.get() != 0) value_ = rhs.value_->clone(); // deep copy

        return *this;
    } // Iptcdatum::operator=

Project: exiv2
File: exif.cpp

    int Exifdatum::setValue(const std::string& value)
    {
        if (value_.get() == 0) {
            TypeId type = key_->defaultTypeId();
            value_ = Value::create(type);
        }
        return value_->read(value);
    }

Project: exiv2
File: exif.cpp

    bool ExifData::empty() const { return count() == 0; }

Project: exiv2
File: tiffvisitor_int.cpp

    void TiffDecoder::visitSizeEntry(TiffSizeEntry* object)
    {
        decodeTiffEntry(object);
    }

Project: exiv2
File: pgfimage.cpp

    void PgfImage::doWriteMetadata(BasicIo& outIo)
    {
        if (!io_->isopen()) throw Error(kerInputDataReadFailed);
        if (!outIo.isopen()) throw Error(kerImageWriteFailed);

#ifdef DEBUG
        std::cout << "Exiv2::PgfImage::doWriteMetadata: Writing PGF file " << io_->path() << "\n";
        std::cout << "Exiv2::PgfImage::doWriteMetadata: tmp file created " << outIo.path() << "\n";
#endif

        // Ensure that this is the correct image type
        if (!isPgfType(*io_, true))
        {
            if (io_->error() || io_->eof()) throw Error(kerInputDataReadFailed);
            throw Error(kerNoImageInInputData);
        }

        // Ensure PGF version.
        byte mnb            = readPgfMagicNumber(*io_);

        readPgfHeaderSize(*io_);

        int w, h;
        DataBuf header      = readPgfHeaderStructure(*io_, w, h);

        Image::UniquePtr img  = ImageFactory::create(ImageType::png);

        img->setExifData(exifData_);
        img->setIptcData(iptcData_);
        img->setXmpData(xmpData_);
        img->writeMetadata();
        size_t imgSize = img->io().size();
        DataBuf imgBuf = img->io().read((long)imgSize);

#ifdef DEBUG
        std::cout << "Exiv2::PgfImage::doWriteMetadata: Creating image to host metadata (" << imgSize << " bytes)\n";
#endif

        //---------------------------------------------------------------

        // Write PGF Signature.
        if (outIo.write(pgfSignature, 3) != 3) throw Error(kerImageWriteFailed);

        // Write Magic number.
        if (outIo.putb(mnb) == EOF) throw Error(kerImageWriteFailed);

        // Write new Header size.
        size_t newHeaderSize = header.size_ + imgSize;
        DataBuf buffer(4);
        memcpy (buffer.pData_, &newHeaderSize, 4);
        byteSwap_(buffer,0,bSwap_);
        if (outIo.write(buffer.pData_, 4) != 4) throw Error(kerImageWriteFailed);

#ifdef DEBUG
        std::cout << "Exiv2::PgfImage: new PGF header size : " << newHeaderSize << " bytes\n";

        printf("%x\n", buffer.pData_[0]);
        printf("%x\n", buffer.pData_[1]);
        printf("%x\n", buffer.pData_[2]);
        printf("%x\n", buffer.pData_[3]);
#endif

        // Write Header data.
        if (outIo.write(header.pData_, header.size_) != header.size_) throw Error(kerImageWriteFailed);

        // Write new metadata byte array.
        if (outIo.write(imgBuf.pData_, imgBuf.size_) != imgBuf.size_) throw Error(kerImageWriteFailed);

        // Copy the rest of PGF image data.

        DataBuf buf(4096);
        size_t readSize = 0;
        while ((readSize=io_->read(buf.pData_, buf.size_)))
        {
            if (outIo.write(buf.pData_, readSize) != readSize) throw Error(kerImageWriteFailed);
        }
        if (outIo.error()) throw Error(kerImageWriteFailed);

    } // PgfImage::doWriteMetadata

Project: exiv2
File: tiffcomposite_int.cpp

    TiffEntry::~TiffEntry()
    {
    }

Project: exiv2
File: makernote_int.cpp

    ByteOrder Nikon3MnHeader::byteOrder() const
    {
        return byteOrder_;
    }

Project: exiv2
File: makernote_int.cpp

    TiffComponent* newPentaxMn(uint16_t tag, IfdId group, IfdId /*mnGroup*/, const byte* pData, uint32_t size,
                               ByteOrder /*byteOrder*/)
    {
        if (size > 8 && std::string(reinterpret_cast<const char*>(pData), 8) == std::string("PENTAX \0", 8)) {
            // Require at least the header and an IFD with 1 entry
            if (size < PentaxDngMnHeader::sizeOfSignature() + 18)
                return 0;
            return newPentaxDngMn2(tag, group, (tag == 0xc634 ? pentaxDngId:pentaxId));
        } else if (size > 4 && std::string(reinterpret_cast<const char*>(pData), 4) == std::string("AOC\0", 4)) {
            // Require at least the header and an IFD with 1 entry
            if (size < PentaxMnHeader::sizeOfSignature() + 18)
                return 0;
            return newPentaxMn2(tag, group, pentaxId);
        } else
            return 0;
    }

Project: exiv2
File: tiffvisitor_int.cpp

    void TiffDecoder::decodeXmp(const TiffEntryBase* object)
    {
        // add Exif tag anyway
        decodeStdTiffEntry(object);

        byte const* pData = 0;
        long size = 0;
        getObjData(pData, size, 0x02bc, ifd0Id, object);
        if (pData) {
            std::string xmpPacket;
            xmpPacket.assign(reinterpret_cast<const char*>(pData), size);
            std::string::size_type idx = xmpPacket.find_first_of('<');
            if (idx != std::string::npos && idx > 0) {
#ifndef SUPPRESS_WARNINGS
                EXV_WARNING << "Removing " << static_cast<unsigned long>(idx)
                            << " characters from the beginning of the XMP packet\n";
#endif
                xmpPacket = xmpPacket.substr(idx);
            }
            if (XmpParser::decode(xmpData_, xmpPacket)) {
#ifndef SUPPRESS_WARNINGS
                EXV_WARNING << "Failed to decode XMP metadata.\n";
#endif
            }
        }
    } // TiffDecoder::decodeXmp

Project: exiv2
File: actions.cpp

    int FixIso::run(const std::string& path)
    {
        try {
            if (!Exiv2::fileExists(path, true)) {
                std::cerr << path << ": " << _("Failed to open the file\n");
                return -1;
            }
            Timestamp ts;
            if (Params::instance().preserve_)
                ts.read(path);

            Exiv2::Image::UniquePtr image = Exiv2::ImageFactory::open(path);
            image->readMetadata();
            Exiv2::ExifData& exifData = image->exifData();
            if (exifData.empty()) {
                std::cerr << path << ": " << _("No Exif data found in the file\n");
                return -3;
            }
            auto md = Exiv2::isoSpeed(exifData);
            if (md != exifData.end()) {
                if (strcmp(md->key().c_str(), "Exif.Photo.ISOSpeedRatings") == 0) {
                    if (Params::instance().verbose_) {
                        std::cout << _("Standard Exif ISO tag exists; not modified\n");
                    }
                    return 0;
                }
                // Copy the proprietary tag to the standard place
                std::ostringstream os;
                md->write(os, &exifData);
                if (Params::instance().verbose_) {
                    std::cout << _("Setting Exif ISO value to") << " " << os.str() << "\n";
                }
                exifData["Exif.Photo.ISOSpeedRatings"] = os.str();
            }
            image->writeMetadata();
            if (Params::instance().preserve_)
                ts.touch(path);

            return 0;
        } catch (const Exiv2::AnyError& e) {
            std::cerr << "Exiv2 exception in fixiso action for file " << path << ":\n" << e << "\n";
            return 1;
        }
    }

Project: exiv2
File: types.cpp

    long s2Data(byte* buf, int16_t s, ByteOrder byteOrder)
    {
        if (byteOrder == littleEndian) {
            buf[0] =  (byte)(s & 0x00ff);
            buf[1] = (byte)((s & 0xff00) >> 8);
        }
        else {
            buf[0] = (byte)((s & 0xff00) >> 8);
            buf[1] =  (byte)(s & 0x00ff);
        }
        return 2;
    }

Project: exiv2
File: tiffcomposite_int.cpp

    uint32_t TiffEntryBase::doSize() const
    {
        return size_;
    } // TiffEntryBase::doSize

Project: exiv2
File: tiffvisitor_int.cpp

    void TiffEncoder::visitDirectoryNext(TiffDirectory* object)
    {
        // Update type and count in IFD entries, in case they changed
        assert(object != 0);

        byte* p = object->start() + 2;
        for (TiffDirectory::Components::iterator i = object->components_.begin();
             i != object->components_.end(); ++i) {
            p += updateDirEntry(p, byteOrder(), *i);
        }
    }

Project: exiv2
File: tiffcomposite_int.cpp

    uint32_t TiffDirectory::doSizeData() const
    {
        assert(false);
        return 0;
    } // TiffDirectory::doSizeData

Project: exiv2
File: tiffimage.cpp

    uint32_t TiffHeaderBase::offset() const
    {
        return offset_;
    }

Project: exiv2
File: tiffcomposite_int.cpp

    TiffSubIfd::~TiffSubIfd()
    {
        for (Ifds::iterator i = ifds_.begin(); i != ifds_.end(); ++i) {
            delete *i;
        }
    }

Project: exiv2
File: makernote_int.cpp

    PentaxDngMnHeader::~PentaxDngMnHeader()
    {
    }

Project: exiv2
File: pngchunk_int.cpp

        DataBuf PngChunk::decodeTXTChunk(const DataBuf& data, TxtChunkType type)
        {
            DataBuf key = keyTXTChunk(data);

#ifdef DEBUG
            std::cout << "Exiv2::PngChunk::decodeTXTChunk: TXT chunk key: "
                      << std::string((const char*)key.pData_, key.size_) << std::endl;
#endif
            return parseTXTChunk(data, key.size_, type);

        }  // PngChunk::decodeTXTChunk

Project: exiv2
File: tiffvisitor_int.cpp

    uint32_t TiffReader::baseOffset() const
    {
        assert(pState_);
        return pState_->baseOffset();
    }

Project: exiv2
File: tiffcomposite_int.cpp

    bool cmpGroupLt(TiffComponent const* lhs, TiffComponent const* rhs)
    {
        assert(lhs != 0);
        assert(rhs != 0);
        return lhs->group() < rhs->group();
    }

Project: exiv2
File: tiffcomposite_int.cpp

    void IoWrapper::setTarget(int id, uint32_t target)
    {
        if (pow_) pow_->setTarget(OffsetWriter::OffsetId(id), target);
    }

Project: exiv2
File: actions.cpp

    int Extract::writeIccProfile(const std::string& target) const
    {
        int rc = 0;
        if (!Exiv2::fileExists(path_, true)) {
            std::cerr << path_ << ": " << _("Failed to open the file\n");
            rc = -1;
        }

        bool bStdout = target == "-";

        if (rc == 0) {
            Exiv2::Image::UniquePtr image = Exiv2::ImageFactory::open(path_);
            image->readMetadata();
            if (!image->iccProfileDefined()) {
                std::cerr << _("No embedded iccProfile: ") << path_ << std::endl;
                rc = -2;
            } else {
                if (bStdout) {  // -eC-
                    std::cout.write((const char*)image->iccProfile()->pData_, image->iccProfile()->size_);
                } else {
                    if (Params::instance().verbose_) {
                        std::cout << _("Writing iccProfile: ") << target << std::endl;
                    }
                    Exiv2::FileIo iccFile(target);
                    iccFile.open("wb");
                    iccFile.write(image->iccProfile()->pData_, image->iccProfile()->size_);
                    iccFile.close();
                }
            }
        }
        return rc;
    }

Project: exiv2
File: basicio.cpp

    long MemIo::tell() const
    {
        return (long)p_->idx_;
    }

Project: exiv2
File: jpgimage.cpp

    Image::UniquePtr newJpegInstance(BasicIo::UniquePtr io, bool create)
    {
        Image::UniquePtr image(new JpegImage(std::move(io), create));
        if (!image->good()) {
            image.reset();
        }
        return image;
    }

Project: exiv2
File: makernote_int.cpp

    ByteOrder Casio2MnHeader::byteOrder() const
    {
        return byteOrder_;
    }

Project: exiv2
File: actions.cpp

    int Print::printList()
    {
        if (!Exiv2::fileExists(path_, true)) {
            std::cerr << path_ << ": " << _("Failed to open the file\n");
            return -1;
        }
        Exiv2::Image::UniquePtr image = Exiv2::ImageFactory::open(path_);
        assert(image.get() != 0);
        image->readMetadata();
        // Set defaults for metadata types and data columns
        if (Params::instance().printTags_ == Exiv2::mdNone) {
            Params::instance().printTags_ = Exiv2::mdExif | Exiv2::mdIptc | Exiv2::mdXmp;
        }
        if (Params::instance().printItems_ == 0) {
            Params::instance().printItems_ = Params::prKey | Params::prType | Params::prCount | Params::prTrans;
        }
        return printMetadata(image.get());
    }

Project: exiv2
File: tiffcomposite_int.cpp

    int TiffEntryBase::idx() const
    {
        return idx_;
    }

Project: exiv2
File: tiffvisitor_int.cpp

    void TiffReader::visitIfdMakernote(TiffIfdMakernote* object)
    {
        assert(object != 0);

        object->setImageByteOrder(byteOrder()); // set the byte order for the image

        if (!object->readHeader(object->start(),
                                static_cast<uint32_t>(pLast_ - object->start()),
                                byteOrder())) {
#ifndef SUPPRESS_WARNINGS
            EXV_ERROR << "Failed to read "
                      << groupName(object->ifd_.group())
                      << " IFD Makernote header.\n";
#ifdef DEBUG
            if (static_cast<uint32_t>(pLast_ - object->start()) >= 16) {
                hexdump(std::cerr, object->start(), 16);
            }
#endif // DEBUG
#endif // SUPPRESS_WARNINGS
            setGo(geKnownMakernote, false);
            return;
        }

        object->ifd_.setStart(object->start() + object->ifdOffset());

        // Modify reader for Makernote peculiarities, byte order and offset
        object->mnOffset_ = static_cast<uint32_t>(object->start() - pData_);
        TiffRwState state(object->byteOrder(), object->baseOffset());
        setMnState(&state);

    } // TiffReader::visitIfdMakernote

Project: exiv2
File: crwimage_int.cpp

    void CiffEntry::doAddComponent(UniquePtr /*component*/)
    {
        throw Error(kerFunctionNotSupported, "CiffEntry::add");
    }

Project: exiv2
File: value.cpp

    float LangAltValue::toFloat(long /*n*/) const
    {
        ok_ = false;
        return 0.0f;
    }

Project: exiv2
File: bigtiffimage.cpp

                virtual ~BigTiffImage() {}

Project: exiv2
File: makernote_int.cpp

    TiffComponent* newSony2Mn2(uint16_t tag,
                               IfdId    group,
                               IfdId    mnGroup)
    {
        return new TiffIfdMakernote(tag, group, mnGroup, 0, true);
    }

Project: exiv2
File: types.cpp

    float getFloat(const byte* buf, ByteOrder byteOrder)
    {
        // This algorithm assumes that the internal representation of the float
        // type is the 4-byte IEEE 754 binary32 format, which is common but not
        // required by the C++ standard.
        static_assert(sizeof(float) == 4, "float type requires 4-byte IEEE 754 binary32 format");
        union {
            uint32_t ul_;
            float    f_;
        } u;
        u.ul_ = getULong(buf, byteOrder);
        return u.f_;
    }

Project: exiv2
File: image.cpp

    void Image::setMetadata(const Image& image)
    {
        if (checkMode(mdExif) & amWrite) {
            setExifData(image.exifData());
        }
        if (checkMode(mdIptc) & amWrite) {
            setIptcData(image.iptcData());
        }
        if (checkMode(mdIccProfile) & amWrite && iccProfile()) {
            setIccProfile(*iccProfile());
        }
        if (checkMode(mdXmp) & amWrite) {
            setXmpPacket(image.xmpPacket());
            setXmpData(image.xmpData());
        }
        if (checkMode(mdComment) & amWrite) {
            setComment(image.comment());
        }
    }

Project: exiv2
File: tiffcomposite_int.cpp

    TiffType toTiffType(TypeId typeId)
    {
        if (static_cast<uint32_t>(typeId) > 0xffff) {
#ifndef SUPPRESS_WARNINGS
            EXV_ERROR << "'" << TypeInfo::typeName(typeId)
                      << "' is not a valid Exif (TIFF) type; using type '"
                      << TypeInfo::typeName(undefined) << "'.\n";
#endif
            return undefined;
        }
        return static_cast<uint16_t>(typeId);
    }

Project: exiv2
File: tiffcomposite_int.cpp

    uint32_t TiffImageEntry::doSizeData() const
    {
        uint32_t len = 0;
        // For makernotes, TIFF image data is written to the data area
        if (group() > mnId) { // Todo: Fix this hack!!
            len = sizeImage();
        }
        return len;
    } // TiffImageEntry::doSizeData

Project: exiv2
File: makernote_int.cpp

    PentaxMnHeader::PentaxMnHeader()
    {
        read(signature_, sizeOfSignature(), invalidByteOrder);
    }

Project: exiv2
File: image.cpp

    ImageType ImageFactory::getType(const std::wstring& wpath)
    {
        FileIo fileIo(wpath);
        return getType(fileIo);
    }

Project: exiv2
File: value.cpp

    Value::~Value()
    {
    }

Project: exiv2
File: actions.cpp

    int Erase::run(const std::string& path) try {
        path_ = path;

        if (!Exiv2::fileExists(path_, true)) {
            std::cerr << path_ << ": " << _("Failed to open the file\n");
            return -1;
        }
        Timestamp ts;
        if (Params::instance().preserve_)
            ts.read(path);

        Exiv2::Image::UniquePtr image = Exiv2::ImageFactory::open(path_);
        image->readMetadata();
        // Thumbnail must be before Exif
        int rc = 0;
        if (Params::instance().target_ & Params::ctThumb) {
            rc = eraseThumbnail(image.get());
        }
        if (0 == rc && Params::instance().target_ & Params::ctExif) {
            rc = eraseExifData(image.get());
        }
        if (0 == rc && Params::instance().target_ & Params::ctIptc) {
            rc = eraseIptcData(image.get());
        }
        if (0 == rc && Params::instance().target_ & Params::ctComment) {
            rc = eraseComment(image.get());
        }
        if (0 == rc && Params::instance().target_ & Params::ctXmp) {
            rc = eraseXmpData(image.get());
        }
        if (0 == rc && Params::instance().target_ & Params::ctIccProfile) {
            rc = eraseIccProfile(image.get());
        }
        if (0 == rc && Params::instance().target_ & Params::ctIptcRaw) {
            rc = printStructure(std::cout, Exiv2::kpsIptcErase, path_);
        }

        if (0 == rc) {
            image->writeMetadata();
            if (Params::instance().preserve_)
                ts.touch(path);
        }

        return rc;
    } catch (const Exiv2::AnyError& e) {

Project: exiv2
File: bigtiffimage.cpp

        Header readHeader(BasicIo& io)
        {
            byte header[2] = {0, 0};
            io.read(header, 2);

            ByteOrder byteOrder = invalidByteOrder;
            if (header[0] == 'I' && header[1] == 'I')
                byteOrder = littleEndian;
            else if (header[0] == 'M' && header[1] == 'M')
                byteOrder = bigEndian;

            if (byteOrder == invalidByteOrder)
                return Header();

            byte version[2] = {0, 0};
            io.read(version, 2);

            const uint16_t magic = getUShort(version, byteOrder);

            if (magic != 0x2A && magic != 0x2B)
                return Header();

            Header result;

            if (magic == 0x2A)
            {
                byte buffer[4];
                const size_t read = io.read(buffer, 4);

                if (read < 4)
                    throw Exiv2::Error(kerCorruptedMetadata);

                const uint32_t offset = getULong(buffer, byteOrder);
                result = Header(byteOrder, magic, 4, offset);
            }
            else
            {
                byte buffer[8] = {0, 0, 0, 0, 0, 0, 0, 0};
                size_t read = io.read(buffer, 2);
                if (read < 2)
                    throw Exiv2::Error(kerCorruptedMetadata);

                const int size = getUShort(buffer, byteOrder);

                if (size == 8)
                {
                    read = io.read(buffer, 2); // null
                    if (read < 2)
                        throw Exiv2::Error(kerCorruptedMetadata);

                    read = io.read(buffer, 8);
                    if (read < 8)
                        throw Exiv2::Error(kerCorruptedMetadata);

                    const uint64_t offset = getULongLong(buffer, byteOrder);

                    if (offset >= io.size())
                        throw Exiv2::Error(kerCorruptedMetadata);

                    result = Header(byteOrder, magic, size, offset);
                }
                else
                    throw Exiv2::Error(kerCorruptedMetadata);
            }

            return result;
        }

Project: exiv2
File: exif.cpp

    const wchar_t* TiffThumbnail::wextension() const
    {
        return EXV_WIDEN(".tif");
    }

Project: exiv2
File: makernote_int.cpp

    size_t PentaxMnHeader::write(IoWrapper& ioWrapper,
                                   ByteOrder /*byteOrder*/) const
    {
        ioWrapper.write(signature_, sizeOfSignature());
        return sizeOfSignature();
    } // PentaxMnHeader::write

Project: exiv2
File: jpgimage.cpp

    bool Photoshop::valid(const byte* pPsData,
                          size_t sizePsData)
    {
        const byte *record = 0;
        uint32_t sizeIptc = 0;
        uint32_t sizeHdr = 0;
        const byte* pCur = pPsData;
        const byte* pEnd = pPsData + sizePsData;
        int ret = 0;
        while (pCur < pEnd
               && 0 == (ret = Photoshop::locateIptcIrb(pCur, static_cast<long>(pEnd - pCur),
                                                       &record, &sizeHdr, &sizeIptc))) {
            pCur = record + sizeHdr + sizeIptc + (sizeIptc & 1);
        }
        return ret >= 0;
    }

Project: exiv2
File: preview.cpp

    DataBuf LoaderExifDataJpeg::getData() const
    {
        if (!valid()) return DataBuf();

        ExifData::const_iterator pos = image_.exifData().findKey(dataKey_);
        if (pos != image_.exifData().end()) {
            DataBuf buf = pos->dataArea(); // indirect data

            if (buf.size_ == 0) { // direct data
                buf = DataBuf(pos->size());
                pos->copy(buf.pData_, invalidByteOrder);
            }

            buf.pData_[0] = 0xff; // fix Minolta thumbnails with invalid jpeg header
            return buf;
        }

        return DataBuf();
    }

Project: exiv2
File: exif.cpp

    const char* TiffThumbnail::mimeType() const
    {
        return "image/tiff";
    }

Project: exiv2
File: image.cpp

    ImageType ImageFactory::getType(const byte* data, long size)
    {
        MemIo memIo(data, size);
        return getType(memIo);
    }

Project: exiv2
File: iptc.cpp

    IptcData::iterator IptcData::findKey(const IptcKey& key)
    {
        return std::find_if(iptcMetadata_.begin(), iptcMetadata_.end(),
                            FindIptcdatum(key.tag(), key.record()));
    }

Project: exiv2
File: value.cpp

    float XmpTextValue::toFloat(long /*n*/) const
    {
        return parseFloat(value_, ok_);
    }

Project: exiv2
File: jpgimage.cpp

    bool ExvImage::isThisType(BasicIo& iIo, bool advance) const
    {
        return isExvType(iIo, advance);
    }

Project: exiv2
File: tiffcomposite_int.cpp

    bool TiffBinaryArray::updOrigDataBuf(const byte* pData, uint32_t size)
    {
        assert(pData != 0);

        if (origSize_ != size) return false;
        if (origData_ == pData) return true;
        memcpy(origData_, pData, origSize_);
        return true;
    }

Project: exiv2
File: makernote_int.cpp

    constexpr uint32_t PanasonicMnHeader::sizeOfSignature()
    {
        return sizeof(signature_);
    }

Project: exiv2
File: types.cpp

    int exifTime(const char* buf, struct tm* tm)
    {
        assert(buf != 0);
        assert(tm != 0);
        int rc = 1;
        int year, mon, mday, hour, min, sec;
        int scanned = std::sscanf(buf, "%4d:%2d:%2d %2d:%2d:%2d",
                                  &year, &mon, &mday, &hour, &min, &sec);
        if (scanned == 6) {
            tm->tm_year = year - 1900;
            tm->tm_mon  = mon - 1;
            tm->tm_mday = mday;
            tm->tm_hour = hour;
            tm->tm_min  = min;
            tm->tm_sec  = sec;
            rc = 0;
        }
        return rc;
    } // exifTime

Project: exiv2
File: actions.cpp

    int Extract::writePreviews() const
    {
        if (!Exiv2::fileExists(path_, true)) {
            std::cerr << path_ << ": " << _("Failed to open the file\n");
            return -1;
        }
        Exiv2::Image::UniquePtr image = Exiv2::ImageFactory::open(path_);
        image->readMetadata();

        Exiv2::PreviewManager pvMgr(*image);
        Exiv2::PreviewPropertiesList pvList = pvMgr.getPreviewProperties();

        const Params::PreviewNumbers& numbers = Params::instance().previewNumbers_;
        for (auto n = numbers.cbegin(); n != numbers.cend(); ++n) {
            if (*n == 0) {
                // Write all previews
                for (int num = 0; num < static_cast<int>(pvList.size()); ++num) {
                    writePreviewFile(pvMgr.getPreviewImage(pvList[num]), num + 1);
                }
                break;
            }
            if (*n > static_cast<int>(pvList.size())) {
                std::cerr << path_ << ": " << _("Image does not have preview") << " " << *n << "\n";
                continue;
            }
            writePreviewFile(pvMgr.getPreviewImage(pvList[*n - 1]), *n);
        }
        return 0;
    }

Project: exiv2
File: tiffcomposite_int.cpp

    void TiffEntry::doEncode(TiffEncoder& encoder, const Exifdatum* datum)
    {
        encoder.encodeTiffEntry(this, datum);
    } // TiffEntry::doEncode

Project: exiv2
File: tiffimage_int.cpp

    bool TiffHeaderBase::read(const byte* pData, uint32_t size)
    {
        if (!pData || size < 8) return false;

        if (pData[0] == 'I' && pData[0] == pData[1]) {
            byteOrder_ = littleEndian;
        }
        else if (pData[0] == 'M' && pData[0] == pData[1]) {
            byteOrder_ = bigEndian;
        }
        else {
            return false;
        }
        if (tag_ != getUShort(pData + 2, byteOrder_)) return false;
        offset_ = getULong(pData + 4, byteOrder_);

        return true;
    } // TiffHeaderBase::read

Project: exiv2
File: tiffvisitor_int.cpp

    void TiffFinder::visitSubIfd(TiffSubIfd* object)
    {
        findObject(object);
    }

Project: exiv2
File: iptc.cpp

    const char* Iptcdatum::typeName() const
    {
        return TypeInfo::typeName(typeId());
    }

Project: exiv2
File: tiffvisitor_int.cpp

    TiffEncoder::TiffEncoder(
            const ExifData&      exifData,
            const IptcData&      iptcData,
            const XmpData&       xmpData,
                  TiffComponent* pRoot,
            const bool           isNewImage,
            const PrimaryGroups* pPrimaryGroups,
            const TiffHeaderBase* pHeader,
                  FindEncoderFct findEncoderFct
    )
        : exifData_(exifData),
          iptcData_(iptcData),
          xmpData_(xmpData),
          del_(true),
          pHeader_(pHeader),
          pRoot_(pRoot),
          isNewImage_(isNewImage),
          pPrimaryGroups_(pPrimaryGroups),
          pSourceTree_(0),
          findEncoderFct_(findEncoderFct),
          dirty_(false),
          writeMethod_(wmNonIntrusive)
    {
        assert(pRoot != 0);
        assert(pPrimaryGroups != 0);
        assert(pHeader != 0);

        byteOrder_ = pHeader->byteOrder();
        origByteOrder_ = byteOrder_;

        encodeIptc();
        encodeXmp();

        // Find camera make
        ExifKey key("Exif.Image.Make");
        ExifData::const_iterator pos = exifData_.findKey(key);
        if (pos != exifData_.end()) {
            make_ = pos->toString();
        }
        if (make_.empty() && pRoot_) {
            TiffFinder finder(0x010f, ifd0Id);
            pRoot_->accept(finder);
            TiffEntryBase* te = dynamic_cast<TiffEntryBase*>(finder.result());
            if (te && te->pValue()) {
                make_ = te->pValue()->toString();
            }
        }
    }

Project: exiv2
File: iptc.cpp

    int readData(
              Exiv2::IptcData& iptcData,
              uint16_t         dataSet,
              uint16_t         record,
        const Exiv2::byte*     data,
              uint32_t         sizeData
    )
    {
        Exiv2::Value::UniquePtr value;
        Exiv2::TypeId type = Exiv2::IptcDataSets::dataSetType(dataSet, record);
        value = Exiv2::Value::create(type);
        int rc = value->read(data, sizeData, Exiv2::bigEndian);
        if (0 == rc) {
            Exiv2::IptcKey key(dataSet, record);
            iptcData.add(key, value.get());
        }
        else if (1 == rc) {
            // If the first attempt failed, try with a string value
            value = Exiv2::Value::create(Exiv2::string);
            rc = value->read(data, sizeData, Exiv2::bigEndian);
            if (0 == rc) {
                Exiv2::IptcKey key(dataSet, record);
                iptcData.add(key, value.get());
            }
        }
        return rc;
    }

Project: exiv2
File: value.cpp

    StringValue::StringValue()
        : StringValueBase(string)
    {
    }

Project: exiv2
File: preview.cpp

    PreviewId Loader::getNumLoaders()
    {
        return (PreviewId)EXV_COUNTOF(loaderList_);
    }

Project: exiv2
File: exif.cpp

    void ExifThumb::setJpegThumbnail(const std::string& path)
    {
        DataBuf thumb = readFile(path); // may throw
        setJpegThumbnail(thumb.pData_, (long)thumb.size_);
    }

Project: exiv2
File: mrwimage.cpp

    void MrwImage::setIptcData(const IptcData& /*iptcData*/)
    {
        // Todo: implement me!
        throw(Error(kerInvalidSettingForImage, "IPTC metadata", "MRW"));
    }

Project: exiv2
File: exif.cpp

    uint16_t Exifdatum::tag() const
    {
        return key_.get() == 0 ? 0xffff : key_->tag();
    }

Project: exiv2
File: actions.cpp

    std::ostream& operator<<(std::ostream& os, std::pair<std::string, int> strAndWidth)
    {
        const std::string& str(strAndWidth.first);
        size_t minChCount = static_cast<size_t>(strAndWidth.second);
        size_t count = mbstowcs(nullptr, str.c_str(), 0);  // returns 0xFFFFFFFF on error
        if (count < minChCount) {
            minChCount += str.size() - count;
        }
        return os << std::setw(static_cast<int>(minChCount)) << str;
    }

Project: exiv2
File: bigtiffimage.cpp

            int dataSize() const
            {
                assert(isValid());
                return data_size_;
            }

Project: exiv2
File: xmpsidecar.cpp

    static std::string toLowerCase(std::string a)
    {
        for(size_t i=0 ; i < a.length() ; i++)
        {
            a[i]=tolower(a[i]);
        }
        return a;
    }

Project: exiv2
File: tiffvisitor_int.cpp

    void TiffEncoder::encodeMnEntry(TiffMnEntry* object, const Exifdatum* datum)
    {
        // Test is required here as well as in the visit function
        if (!object->mn_) encodeTiffEntryBase(object, datum);
    } // TiffEncoder::encodeMnEntry

Project: exiv2
File: tiffvisitor_int.cpp

    bool TiffEncoder::dirty() const
    {
        if (dirty_ || exifData_.count() > 0) return true;
        return false;
    }

Project: exiv2
File: convert.cpp

    bool convertStringCharsetIconv(std::string& str, const char* from, const char* to)
    {
        if (0 == strcmp(from, to)) return true; // nothing to do

        bool ret = true;
        iconv_t cd;
        cd = iconv_open(to, from);
        if (cd == (iconv_t)(-1)) {
#ifndef SUPPRESS_WARNINGS
            EXV_WARNING << "iconv_open: " << strError() << "\n";
#endif
            return false;
        }
        std::string outstr;
        EXV_ICONV_CONST char* inptr = const_cast<char*>(str.c_str());
        size_t inbytesleft = str.length();
        while (inbytesleft) {
            char outbuf[256];
            char* outptr = outbuf;
            size_t outbytesleft = sizeof(outbuf);
            size_t rc = iconv(cd,
                              &inptr,
                              &inbytesleft,
                              &outptr,
                              &outbytesleft);
            const size_t outbytesProduced = sizeof(outbuf) - outbytesleft;
            if (rc == size_t(-1) && errno != E2BIG) {
#ifndef SUPPRESS_WARNINGS
                EXV_WARNING << "iconv: " << strError()
                            << " inbytesleft = " << inbytesleft << "\n";
#endif
                ret = false;
                break;
            }
            outstr.append(std::string(outbuf, outbytesProduced));
        }
        if (cd != (iconv_t)(-1)) {
            iconv_close(cd);
        }

        if (ret) str = outstr;
        return ret;
    }

Project: exiv2
File: iptc.cpp

    std::string Iptcdatum::recordName() const
    {
        return key_.get() == 0 ? "" : key_->recordName();
    }

Project: exiv2
File: preview.cpp

    LoaderXmpJpeg::LoaderXmpJpeg(PreviewId id, const Image &image, int parIdx)
        : Loader(id, image)
    {
        (void)parIdx;

        const XmpData &xmpData = image_.xmpData();

        std::string prefix = "xmpGImg";
        if (xmpData.findKey(XmpKey("Xmp.xmp.Thumbnails[1]/xapGImg:image")) != xmpData.end()) {
            prefix = "xapGImg";
        }

        XmpData::const_iterator imageDatum = xmpData.findKey(XmpKey("Xmp.xmp.Thumbnails[1]/" + prefix + ":image"));
        if (imageDatum == xmpData.end()) return;
        XmpData::const_iterator formatDatum = xmpData.findKey(XmpKey("Xmp.xmp.Thumbnails[1]/" + prefix + ":format"));
        if (formatDatum == xmpData.end()) return;
        XmpData::const_iterator widthDatum = xmpData.findKey(XmpKey("Xmp.xmp.Thumbnails[1]/" + prefix + ":width"));
        if (widthDatum == xmpData.end()) return;
        XmpData::const_iterator heightDatum = xmpData.findKey(XmpKey("Xmp.xmp.Thumbnails[1]/" + prefix + ":height"));
        if (heightDatum == xmpData.end()) return;

        if (formatDatum->toString() != "JPEG") return;

        width_ = widthDatum->toLong();
        height_ = heightDatum->toLong();
        preview_ = decodeBase64(imageDatum->toString());
        size_ = static_cast<uint32_t>(preview_.size_);
        valid_ = true;
    }

Project: exiv2
File: jpgimage.cpp

    static inline bool inRange(int lo,int value, int hi)
    {
        return lo<=value && value <= hi;
    }

Project: exiv2
File: image.cpp

    bool Image::isRationalType(uint16_t type) {
         return type == Exiv2::unsignedRational
             || type == Exiv2::signedRational
             ;
    }

Project: exiv2
File: exif.cpp

    Exiv2::DataBuf JpegThumbnail::copy(const Exiv2::ExifData& exifData) const
    {
        Exiv2::ExifKey key("Exif.Thumbnail.JPEGInterchangeFormat");
        Exiv2::ExifData::const_iterator format = exifData.findKey(key);
        if (format == exifData.end()) return Exiv2::DataBuf();
        return format->dataArea();
    }

Project: exiv2
File: tiffcomposite_int.cpp

    uint32_t TiffBinaryArray::addElement(uint32_t idx, const ArrayDef& def)
    {
        uint16_t tag = static_cast<uint16_t>(idx / cfg()->tagStep());
        int32_t sz = EXV_MIN(def.size(tag, cfg()->group_), TiffEntryBase::doSize() - idx);
        TiffComponent::UniquePtr tc = TiffCreator::create(tag, cfg()->group_);
        TiffBinaryElement* tp = dynamic_cast<TiffBinaryElement*>(tc.get());
        // The assertion typically fails if a component is not configured in
        // the TIFF structure table (TiffCreator::tiffTreeStruct_)
        assert(tp);
        tp->setStart(pData() + idx);
        tp->setData(const_cast<byte*>(pData() + idx), sz);
        tp->setElDef(def);
        tp->setElByteOrder(cfg()->byteOrder_);
        addChild(std::move(tc));
        return sz;
    } // TiffBinaryArray::addElement

Project: exiv2
File: value.cpp

    XmpTextValue::UniquePtr XmpTextValue::clone() const
    {
        return UniquePtr(clone_());
    }

Project: exiv2
File: preview.cpp

    DataBuf decodeBase64(const std::string& src)
    {
        const size_t srcSize = src.size();

        // create decoding table
        unsigned long invalid = 64;
        unsigned long decodeBase64Table[256] = {};
        for (unsigned long i = 0; i < 256; i++)
            decodeBase64Table[i] = invalid;
        for (unsigned long i = 0; i < 64; i++)
            decodeBase64Table[(unsigned char)encodeBase64Table[i]] = i;

        // calculate dest size
        unsigned long validSrcSize = 0;
        for (unsigned long srcPos = 0; srcPos < srcSize; srcPos++) {
            if (decodeBase64Table[(unsigned char)src[srcPos]] != invalid) validSrcSize++;
        }
        if (validSrcSize > ULONG_MAX / 3) return DataBuf(); // avoid integer overflow
        const unsigned long destSize = (validSrcSize * 3) / 4;

        // allocate dest buffer
        if (destSize > LONG_MAX) return DataBuf(); // avoid integer overflow
        DataBuf dest(static_cast<long>(destSize));

        // decode
        for (unsigned long srcPos = 0, destPos = 0; destPos < destSize;) {
            unsigned long buffer = 0;
            for (int bufferPos = 3; bufferPos >= 0 && srcPos < srcSize; srcPos++) {
                unsigned long srcValue = decodeBase64Table[(unsigned char)src[srcPos]];
                if (srcValue == invalid) continue;
                buffer |= srcValue << (bufferPos * 6);
                bufferPos--;
            }
            for (int bufferPos = 2; bufferPos >= 0 && destPos < destSize; bufferPos--, destPos++) {
                dest.pData_[destPos] = static_cast<byte>((buffer >> (bufferPos * 8)) & 0xFF);
            }
        }
        return dest;
    }

Project: exiv2
File: makernote_int.cpp

    TiffComponent* newCasio2Mn2(uint16_t tag,
                               IfdId    group,
                               IfdId    mnGroup)
    {
        return new TiffIfdMakernote(tag, group, mnGroup, new Casio2MnHeader);
    }

Project: exiv2
File: convert.cpp

    void Converter::cnvXmpComment(const char* from, const char* to)
    {
        if (!prepareExifTarget(to)) return;
        Exiv2::XmpData::iterator pos = xmpData_->findKey(XmpKey(from));
        if (pos == xmpData_->end()) return;
        std::string value;
        if (!getTextValue(value, pos)) {
#ifndef SUPPRESS_WARNINGS
            EXV_WARNING << "Failed to convert " << from << " to " << to << "\n";
#endif
            return;
        }
        // Assumes the XMP value is encoded in UTF-8, as it should be
        (*exifData_)[to] = "charset=Unicode " + value;
        if (erase_) xmpData_->erase(pos);
    }

Project: exiv2
File: value.cpp

    std::ostream& XmpArrayValue::write(std::ostream& os) const
    {
        for (std::vector<std::string>::const_iterator i = value_.begin();
             i != value_.end(); ++i) {
            if (i != value_.begin()) os << ", ";
            os << *i;
        }
        return os;
    }

Project: exiv2
File: exif.cpp

    void ExifThumb::setJpegThumbnail(const std::wstring& wpath)
    {
        DataBuf thumb = readFile(wpath); // may throw
        setJpegThumbnail(thumb.pData_, thumb.size_);
    }

Project: exiv2
File: tiffvisitor_int.cpp

    void TiffEncoder::encodeTiffEntryBase(TiffEntryBase* object, const Exifdatum* datum)
    {
        assert(object != 0);
        assert(datum != 0);

#ifdef DEBUG
        bool tooLarge = false;
#endif
        size_t newSize = datum->size();
        if (newSize > object->size_) { // value doesn't fit, encode for intrusive writing
            setDirty();
#ifdef DEBUG
            tooLarge = true;
#endif
        }
        object->updateValue(datum->getValue(), byteOrder()); // clones the value
#ifdef DEBUG
        ExifKey key(object->tag(), groupName(object->group()));
        std::cerr << "UPDATING DATA     " << key;
        if (tooLarge) {
            std::cerr << "\t\t\t ALLOCATED " << std::dec << object->size_ << " BYTES";
        }
#endif
    } // TiffEncoder::encodeTiffEntryBase

Project: exiv2
File: value.cpp

    long Value::sizeDataArea() const
    {
        return 0;
    }

Project: exiv2
File: actions.cpp

    int str2Tm(const std::string& timeStr, struct tm* tm)
    {
        if (timeStr.length() == 0 || timeStr[0] == ' ')
            return 1;
        if (timeStr.length() < 19)
            return 2;
        if (timeStr[4] != ':' || timeStr[7] != ':' || timeStr[10] != ' ' || timeStr[13] != ':' || timeStr[16] != ':')
            return 3;
        if (0 == tm)
            return 4;
        std::memset(tm, 0x0, sizeof(struct tm));
        tm->tm_isdst = -1;

        long tmp;
        if (!Util::strtol(timeStr.substr(0, 4).c_str(), tmp))
            return 5;
        tm->tm_year = tmp - 1900;
        if (!Util::strtol(timeStr.substr(5, 2).c_str(), tmp))
            return 6;
        tm->tm_mon = tmp - 1;
        if (!Util::strtol(timeStr.substr(8, 2).c_str(), tmp))
            return 7;
        tm->tm_mday = tmp;
        if (!Util::strtol(timeStr.substr(11, 2).c_str(), tmp))
            return 8;
        tm->tm_hour = tmp;
        if (!Util::strtol(timeStr.substr(14, 2).c_str(), tmp))
            return 9;
        tm->tm_min = tmp;
        if (!Util::strtol(timeStr.substr(17, 2).c_str(), tmp))
            return 10;
        tm->tm_sec = tmp;

        // Conversions to set remaining fields of the tm structure
        if (mktime(tm) == (time_t)-1)
            return 11;

        return 0;
    }

Project: exiv2
File: makernote_int.cpp

    TiffComponent* newFujiMn(uint16_t    tag,
                             IfdId       group,
                             IfdId       mnGroup,
                             const byte* /*pData*/,
                             uint32_t    size,
                             ByteOrder   /*byteOrder*/)
    {
        // Require at least the header and an IFD with 1 entry
        if (size < FujiMnHeader::sizeOfSignature() + 18) return 0;
        return newFujiMn2(tag, group, mnGroup);
    }

Project: exiv2
File: makernote_int.cpp

    TiffComponent* newFujiMn2(uint16_t tag,
                              IfdId    group,
                              IfdId    mnGroup)
    {
        return new TiffIfdMakernote(tag, group, mnGroup, new FujiMnHeader);
    }

Project: exiv2
File: makernote_int.cpp

    TiffComponent* newSony1Mn2(uint16_t tag,
                               IfdId    group,
                               IfdId    mnGroup)
    {
        return new TiffIfdMakernote(tag, group, mnGroup, new SonyMnHeader, false);
    }

Project: exiv2
File: tiffcomposite_int.cpp

    TiffComponent::TiffComponent(uint16_t tag, IfdId group)
        : tag_(tag), group_(group), pStart_(0)
    {
    }

Project: exiv2
File: xmp.cpp

    int XmpParser::decode(      XmpData&     xmpData,
                          const std::string& xmpPacket)
    { try {
        xmpData.clear();
        xmpData.setPacket(xmpPacket);
        if (xmpPacket.empty()) return 0;

        if (!initialize()) {
#ifndef SUPPRESS_WARNINGS
            EXV_ERROR << "XMP toolkit initialization failed.\n";
#endif
            return 2;
        }

        SXMPMeta meta(xmpPacket.data(), static_cast<XMP_StringLen>(xmpPacket.size()));
        SXMPIterator iter(meta);
        std::string schemaNs, propPath, propValue;
        XMP_OptionBits opt;
        while (iter.Next(&schemaNs, &propPath, &propValue, &opt)) {
            printNode(schemaNs, propPath, propValue, opt);
            if (XMP_PropIsAlias(opt)) {
                throw Error(kerAliasesNotSupported, schemaNs, propPath, propValue);
                continue;
            }
            if (XMP_NodeIsSchema(opt)) {
                // Register unknown namespaces with Exiv2
                // (Namespaces are automatically registered with the XMP Toolkit)
                if (XmpProperties::prefix(schemaNs).empty()) {
                    std::string prefix;
                    bool ret = meta.GetNamespacePrefix(schemaNs.c_str(), &prefix);
                    if (!ret) throw Error(kerSchemaNamespaceNotRegistered, schemaNs);
                    prefix = prefix.substr(0, prefix.size() - 1);
                    XmpProperties::registerNs(schemaNs, prefix);
                }
                continue;
            }
            XmpKey::UniquePtr key = makeXmpKey(schemaNs, propPath);
            if (XMP_ArrayIsAltText(opt)) {
                // Read Lang Alt property
                LangAltValue::UniquePtr val(new LangAltValue);
                XMP_Index count = meta.CountArrayItems(schemaNs.c_str(), propPath.c_str());
                while (count-- > 0) {
                    // Get the text
                    bool haveNext = iter.Next(&schemaNs, &propPath, &propValue, &opt);
                    printNode(schemaNs, propPath, propValue, opt);
                    if (   !haveNext
                        || !XMP_PropIsSimple(opt)
                        || !XMP_PropHasLang(opt)) {
                        throw Error(kerDecodeLangAltPropertyFailed, propPath, opt);
                    }
                    const std::string text = propValue;
                    // Get the language qualifier
                    haveNext = iter.Next(&schemaNs, &propPath, &propValue, &opt);
                    printNode(schemaNs, propPath, propValue, opt);
                    if (   !haveNext
                        || !XMP_PropIsSimple(opt)
                        || !XMP_PropIsQualifier(opt)
                        || propPath.substr(propPath.size() - 8, 8) != "xml:lang") {
                        throw Error(kerDecodeLangAltQualifierFailed, propPath, opt);
                    }
                    val->value_[propValue] = text;
                }
                xmpData.add(*key.get(), val.get());
                continue;
            }
            if (    XMP_PropIsArray(opt)
                && !XMP_PropHasQualifiers(opt)
                && !XMP_ArrayIsAltText(opt)) {
                // Check if all elements are simple
                bool simpleArray = true;
                SXMPIterator aIter(meta, schemaNs.c_str(), propPath.c_str());
                std::string aSchemaNs, aPropPath, aPropValue;
                XMP_OptionBits aOpt;
                while (aIter.Next(&aSchemaNs, &aPropPath, &aPropValue, &aOpt)) {
                    if (propPath == aPropPath) continue;
                    if (   !XMP_PropIsSimple(aOpt)
                        ||  XMP_PropHasQualifiers(aOpt)
                        ||  XMP_PropIsQualifier(aOpt)
                        ||  XMP_NodeIsSchema(aOpt)
                        ||  XMP_PropIsAlias(aOpt)) {
                        simpleArray = false;
                        break;
                    }
                }
                if (simpleArray) {
                    // Read the array into an XmpArrayValue
                    XmpArrayValue::UniquePtr val(new XmpArrayValue(arrayValueTypeId(opt)));
                    XMP_Index count = meta.CountArrayItems(schemaNs.c_str(), propPath.c_str());
                    while (count-- > 0) {
                        iter.Next(&schemaNs, &propPath, &propValue, &opt);
                        printNode(schemaNs, propPath, propValue, opt);
                        val->read(propValue);
                    }
                    xmpData.add(*key.get(), val.get());
                    continue;
                }
            }
            XmpTextValue::UniquePtr val(new XmpTextValue);
            if (   XMP_PropIsStruct(opt)
                || XMP_PropIsArray(opt)) {
                // Create a metadatum with only XMP options
                val->setXmpArrayType(xmpArrayType(opt));
                val->setXmpStruct(xmpStruct(opt));
                xmpData.add(*key.get(), val.get());
                continue;
            }
            if (   XMP_PropIsSimple(opt)
                || XMP_PropIsQualifier(opt)) {
                val->read(propValue);
                xmpData.add(*key.get(), val.get());
                continue;
            }
            // Don't let any node go by unnoticed
            throw Error(kerUnhandledXmpNode, key->key(), opt);
        } // iterate through all XMP nodes

        return 0;
    }
#ifndef SUPPRESS_WARNINGS
    catch (const XMP_Error& e) {
        EXV_ERROR << Error(kerXMPToolkitError, e.GetID(), e.GetErrMsg()) << "\n";
        xmpData.clear();
        return 3;
    }
#else
    catch (const XMP_Error&) {
        xmpData.clear();
        return 3;
    }
#endif // SUPPRESS_WARNINGS
    } // XmpParser::decode

Project: exiv2
File: mrwimage.cpp

    int MrwImage::pixelHeight() const
    {
        ExifData::const_iterator imageHeight = exifData_.findKey(Exiv2::ExifKey("Exif.Image.ImageLength"));
        if (imageHeight != exifData_.end() && imageHeight->count() > 0) {
            return imageHeight->toLong();
        }
        return 0;
    }

Project: exiv2
File: iptc.cpp

    void IptcData::printStructure(std::ostream& out, const Slice<byte*>& bytes, uint32_t depth)
    {
        uint32_t i = 0;
        while (i < bytes.size() - 3 && bytes.at(i) != 0x1c)
            i++;
        depth++;
        out << Internal::indent(depth) << "Record | DataSet | Name                     | Length | Data" << std::endl;
        while (i < bytes.size() - 3) {
            if (bytes.at(i) != 0x1c) {
                break;
            }
            char buff[100];
            uint16_t record = bytes.at(i + 1);
            uint16_t dataset = bytes.at(i + 2);
            uint16_t len = getUShort(bytes.subSlice(i + 3, bytes.size()), bigEndian);
            sprintf(buff, "  %6d | %7d | %-24s | %6d | ", record, dataset,
                    Exiv2::IptcDataSets::dataSetName(dataset, record).c_str(), len);

            out << buff << Internal::binaryToString(makeSlice(bytes, i + 5, i + 5 + (len > 40 ? 40 : len)))
                << (len > 40 ? "..." : "")
                << std::endl;
            i += 5 + len;
        }
        depth--;
    }

Project: exiv2
File: convert.cpp

    std::string Converter::computeExifDigest(bool tiff)
    {
        std::ostringstream res;
        MD5_CTX    context;
        unsigned char digest[16];

        MD5Init ( &context );
        for (unsigned int i = 0; i < EXV_COUNTOF(conversion_); ++i) {
            const Conversion& c = conversion_[i];
            if (c.metadataId_ == mdExif) {
                Exiv2::ExifKey key(c.key1_);
                if (tiff && key.groupName() != "Image") continue;
                if (!tiff && key.groupName() == "Image") continue;

                if (!res.str().empty()) res << ',';
                res << key.tag();
                Exiv2::ExifData::iterator pos = exifData_->findKey(key);
                if (pos == exifData_->end()) continue;
                DataBuf data(pos->size());
                pos->copy(data.pData_, littleEndian /* FIXME ? */);
                MD5Update ( &context, data.pData_, (uint32_t)data.size_);
            }
        }
        MD5Final(digest, &context);
        res << ';';
        res << std::setw(2) << std::setfill('0') << std::hex << std::uppercase;
        for (int i = 0; i < 16; ++i) {
            res << static_cast<int>(digest[i]);
        }
        return res.str();
    }

Project: exiv2
File: basicio.cpp

    int RemoteIo::close()
    {
        if (p_->isMalloced_) {
            p_->eof_ = false;
            p_->idx_ = 0;
        }
#ifdef DEBUG
        std::cerr << "RemoteIo::close totalRead_ = " << p_->totalRead_ << std::endl;
#endif
        if ( bigBlock_ ) {
            delete [] bigBlock_;
            bigBlock_=nullptr;
        }
        return 0;
    }

Project: exiv2
File: preview.cpp

    bool LoaderExifJpeg::readDimensions()
    {
        if (!valid()) return false;
        if (width_ || height_) return true;

        BasicIo &io = image_.io();

        if (io.open() != 0) {
            throw Error(kerDataSourceOpenFailed, io.path(), strError());
        }
        IoCloser closer(io);
        const Exiv2::byte* base = io.mmap();

        try {
            Image::UniquePtr image = ImageFactory::open(base + offset_, size_);
            if (image.get() == 0) return false;
            image->readMetadata();

            width_ = image->pixelWidth();
            height_ = image->pixelHeight();
        }
        catch (const AnyError& /* error */ ) {
#ifndef SUPPRESS_WARNINGS
            EXV_WARNING << "Invalid JPEG preview image.\n";
#endif
            return false;
        }

        return true;
    }

Project: exiv2
File: actions.cpp

    std::unique_ptr<Rename> Rename::clone() const
    {
        return std::unique_ptr<Rename>(clone_());
    }

Project: exiv2
File: tiffvisitor_int.cpp

    void TiffReader::visitEntry(TiffEntry* object)
    {
        readTiffEntry(object);
    }

Project: exiv2
File: value.cpp

    int DataValue::read(const byte* buf, size_t len, ByteOrder /*byteOrder*/)
    {
        // byteOrder not needed
        value_.assign(buf, buf + len);
        return 0;
    }

Project: exiv2
File: xmp.cpp

    void XmpParser::terminate()
    {
        XmpProperties::unregisterNs();
        if (initialized_) {
#ifdef EXV_HAVE_XMP_TOOLKIT
            SXMPMeta::Terminate();
#endif
            initialized_ = false;
        }
    }

Project: exiv2
File: tiffcomposite_int.cpp

    TiffComponent* TiffSubIfd::doAddChild(TiffComponent::UniquePtr tiffComponent)
    {
        TiffDirectory* d = dynamic_cast<TiffDirectory*>(tiffComponent.release());
        assert(d);
        ifds_.push_back(d);
        return d;
    } // TiffSubIfd::doAddChild

Project: exiv2
File: value.cpp

    int CommentValue::read(const std::string& comment)
    {
        std::string c = comment;
        CharsetId charsetId = undefined;
        if (comment.length() > 8 && comment.substr(0, 8) == "charset=") {
            std::string::size_type pos = comment.find_first_of(' ');
            std::string name = comment.substr(8, pos-8);
            // Strip quotes (so you can also specify the charset without quotes)
            if (name[0] == '"') name = name.substr(1);
            if (name[name.length()-1] == '"') name = name.substr(0, name.length()-1);
            charsetId = CharsetInfo::charsetIdByName(name);
            if (charsetId == invalidCharsetId) {
#ifndef SUPPRESS_WARNINGS
                EXV_WARNING << Error(kerInvalidCharset, name) << "\n";
#endif
                return 1;
            }
            c.clear();
            if (pos != std::string::npos) c = comment.substr(pos+1);
        }
        if (charsetId == unicode) {
            const char* to = byteOrder_ == littleEndian ? "UCS-2LE" : "UCS-2BE";
            convertStringCharset(c, "UTF-8", to);
        }
        const std::string code(CharsetInfo::code(charsetId), 8);
        return StringValueBase::read(code + c);
    }

Project: exiv2
File: types.cpp

    uint64_t getULongLong(const byte* buf, ByteOrder byteOrder)
    {
        if (byteOrder == littleEndian) {
            return   (uint64_t)buf[7] << 56 | (uint64_t)buf[6] << 48
                   | (uint64_t)buf[5] << 40 | (uint64_t)buf[4] << 32
                   | (uint64_t)buf[3] << 24 | (uint64_t)buf[2] << 16
                   | (uint64_t)buf[1] <<  8 | (uint64_t)buf[0];
        }
        else {
            return   (uint64_t)buf[0] << 56 | (uint64_t)buf[1] << 48
                   | (uint64_t)buf[2] << 40 | (uint64_t)buf[3] << 32
                   | (uint64_t)buf[4] << 24 | (uint64_t)buf[5] << 16
                   | (uint64_t)buf[6] <<  8 | (uint64_t)buf[7];
        }
    }

Project: exiv2
File: tiffcomposite_int.cpp

    uint32_t TiffIfdMakernote::doWrite(IoWrapper& ioWrapper,
                                       ByteOrder byteOrder,
                                       int32_t   offset,
                                       uint32_t  /*valueIdx*/,
                                       uint32_t  /*dataIdx*/,
                                       uint32_t& imageIdx)
    {
        mnOffset_ = offset;
        setImageByteOrder(byteOrder);
        uint32_t len = writeHeader(ioWrapper, this->byteOrder());
        len += ifd_.write(ioWrapper, this->byteOrder(),
                          offset - baseOffset() + len,
                          uint32_t(-1), uint32_t(-1),
                          imageIdx);
        return len;
    } // TiffIfdMakernote::doWrite

Project: exiv2
File: exif.cpp

    Exifdatum& Exifdatum::operator=(const URational& value)
    {
        return Exiv2::setValue(*this, value);
    }

Project: exiv2
File: value.cpp

    float DateValue::toFloat(long n) const
    {
        return static_cast<float>(toLong(n));
    }

Project: exiv2
File: exif.cpp

    const char* Exifdatum::familyName() const
    {
        return key_.get() == 0 ? "" : key_->familyName();
    }

Project: exiv2
File: makernote_int.cpp

        std::string getExiv2ConfigPath()
        {
            std::string homedir;
            std::string inifile;
#if defined(_MSC_VER) || defined(__MINGW__)
            char path[MAX_PATH];
            if (SUCCEEDED(SHGetFolderPathA(nullptr, CSIDL_PROFILE, nullptr, 0, path))) {
                homedir = std::string(path);
                inifile = "exiv2.ini"      ;
            }
#else
            struct passwd* pw = getpwuid(getuid());
            homedir = std::string(pw?pw->pw_dir:"");
            inifile = std::string(".exiv2");
#endif
            return homedir + EXV_SEPARATOR_CHR + inifile;
        }

Project: exiv2
File: exif.cpp

    void ExifThumb::setJpegThumbnail(
        const std::string& path,
              URational    xres,
              URational    yres,
              uint16_t     unit
    )
    {
        DataBuf thumb = readFile(path); // may throw
        setJpegThumbnail(thumb.pData_, thumb.size_, xres, yres, unit);
    }

Project: exiv2
File: makernote_int.cpp

    ByteOrder MnHeader::byteOrder() const
    {
        return invalidByteOrder;
    }

Project: exiv2
File: xmp.cpp

    std::string Xmpdatum::tagLabel() const
    {
        return p_->key_.get() == 0 ? "" : p_->key_->tagLabel();
    }

Project: exiv2
File: tiffvisitor_int.cpp

    void TiffEncoder::encodeIptc()
    {
        // Update IPTCNAA Exif tag, if it exists. Delete the tag if there
        // is no IPTC data anymore.
        // If there is new IPTC data and Exif.Image.ImageResources does
        // not exist, create a new IPTCNAA Exif tag.
        bool del = false;
        ExifKey iptcNaaKey("Exif.Image.IPTCNAA");
        ExifData::iterator pos = exifData_.findKey(iptcNaaKey);
        if (pos != exifData_.end()) {
            iptcNaaKey.setIdx(pos->idx());
            exifData_.erase(pos);
            del = true;
        }
        DataBuf rawIptc = IptcParser::encode(iptcData_);
        ExifKey irbKey("Exif.Image.ImageResources");
        pos = exifData_.findKey(irbKey);
        if (pos != exifData_.end()) {
            irbKey.setIdx(pos->idx());
        }
        if (rawIptc.size_ != 0 && (del || pos == exifData_.end())) {
            Value::UniquePtr value = Value::create(unsignedLong);
            DataBuf buf;
            if (rawIptc.size_ % 4 != 0) {
                // Pad the last unsignedLong value with 0s
                buf.alloc((rawIptc.size_ / 4) * 4 + 4);
                memset(buf.pData_, 0x0, buf.size_);
                memcpy(buf.pData_, rawIptc.pData_, rawIptc.size_);
            }
            else {
                buf = rawIptc; // Note: This resets rawIptc
            }
            value->read(buf.pData_, buf.size_, byteOrder_);
            Exifdatum iptcDatum(iptcNaaKey, value.get());
            exifData_.add(iptcDatum);
            pos = exifData_.findKey(irbKey); // needed after add()
        }
        // Also update IPTC IRB in Exif.Image.ImageResources if it exists,
        // but don't create it if not.
        if (pos != exifData_.end()) {
            DataBuf irbBuf(pos->value().size());
            pos->value().copy(irbBuf.pData_, invalidByteOrder);
            irbBuf = Photoshop::setIptcIrb(irbBuf.pData_, irbBuf.size_, iptcData_);
            exifData_.erase(pos);
            if (irbBuf.size_ != 0) {
                Value::UniquePtr value = Value::create(unsignedByte);
                value->read(irbBuf.pData_, irbBuf.size_, invalidByteOrder);
                Exifdatum iptcDatum(irbKey, value.get());
                exifData_.add(iptcDatum);
            }
        }
    } // TiffEncoder::encodeIptc

Project: exiv2
File: exif.cpp

    Exifdatum& ExifData::operator[](const std::string& key)
    {
        ExifKey exifKey(key);
        iterator pos = findKey(exifKey);
        if (pos == end()) {
            add(Exifdatum(exifKey));
            pos = findKey(exifKey);
        }
        return *pos;
    }

Project: exiv2
File: exif.cpp

    std::string Exifdatum::key() const
    {
        return key_.get() == 0 ? "" : key_->key();
    }

Project: exiv2
File: crwimage.cpp

    void CrwImage::readMetadata()
    {
#ifdef DEBUG
        std::cerr << "Reading CRW file " << io_->path() << "\n";
#endif
        if (io_->open() != 0) {
            throw Error(kerDataSourceOpenFailed, io_->path(), strError());
        }
        IoCloser closer(*io_);
        // Ensure that this is the correct image type
        if (!isCrwType(*io_, false)) {
            if (io_->error() || io_->eof()) throw Error(kerFailedToReadImageData);
            throw Error(kerNotACrwImage);
        }
        clearMetadata();
        DataBuf file( (long) io().size());
        io_->read(file.pData_,file.size_);

        CrwParser::decode(this, io_->mmap(), (uint32_t) io_->size());

    } // CrwImage::readMetadata

Project: exiv2
File: actions.cpp

    int Print::run(const std::string& path)
    {
        try {
            path_ = path;
            int rc = 0;
            Exiv2::PrintStructureOption option = Exiv2::kpsNone;
            switch (Params::instance().printMode_) {
                case Params::pmSummary:
                    rc = Params::instance().greps_.empty() ? printSummary() : printList();
                    break;
                case Params::pmList:
                    rc = printList();
                    break;
                case Params::pmComment:
                    rc = printComment();
                    break;
                case Params::pmPreview:
                    rc = printPreviewList();
                    break;
                case Params::pmStructure:
                    rc = printStructure(std::cout, Exiv2::kpsBasic, path_);
                    break;
                case Params::pmRecursive:
                    rc = printStructure(std::cout, Exiv2::kpsRecursive, path_);
                    break;
                case Params::pmXMP:
                    if (option == Exiv2::kpsNone)
                        option = Exiv2::kpsXMP;
                    rc = setModeAndPrintStructure(option, path_);
                    break;
                case Params::pmIccProfile:
                    if (option == Exiv2::kpsNone)
                        option = Exiv2::kpsIccProfile;
                    rc = setModeAndPrintStructure(option, path_);
                    break;
            }
            return rc;
        } catch (const Exiv2::AnyError& e) {
            std::cerr << "Exiv2 exception in print action for file " << path << ":\n" << e << "\n";
            return 1;
        } catch (const std::overflow_error& e) {
            std::cerr << "std::overflow_error exception in print action for file " << path << ":\n" << e.what() << "\n";
            return 1;
        }
    }

Project: exiv2
File: convert.cpp

    void Converter::cnvExifVersion(const char* from, const char* to)
    {
        Exiv2::ExifData::iterator pos = exifData_->findKey(ExifKey(from));
        if (pos == exifData_->end()) return;
        if (!prepareXmpTarget(to)) return;
        std::ostringstream value;
        for (int i = 0; i < pos->count(); ++i) {
            value << static_cast<char>(pos->toLong(i));
        }
        (*xmpData_)[to] = value.str();
        if (erase_) exifData_->erase(pos);
    }

Project: exiv2
File: image.cpp

    Image::UniquePtr ImageFactory::create(ImageType type,
                                        const std::wstring& wpath)
    {
        std::unique_ptr<FileIo> fileIo(new FileIo(wpath));
        // Create or overwrite the file, then close it
        if (fileIo->open("w+b") != 0) {
            throw WError(kerFileOpenFailed, wpath, "w+b", strError().c_str());
        }
        fileIo->close();
        BasicIo::UniquePtr io(std::move(fileIo));
        Image::UniquePtr image = create(type, std::move(io));
        if (image.get() == 0) throw Error(kerUnsupportedImageType, static_cast<int>(type));
        return image;
    }

Project: exiv2
File: value.cpp

    long XmpValue::copy(byte* buf,
                        ByteOrder /*byteOrder*/) const
    {
        std::ostringstream os;
        write(os);
        std::string s = os.str();
        if (s.size() > 0) std::memcpy(buf, &s[0], s.size());
        return static_cast<long>(s.size());
    }

Project: exiv2
File: value.cpp

    std::string XmpArrayValue::toString(long n) const
    {
        ok_ = true;
        return value_[n];
    }

Project: exiv2
File: convert.cpp

    bool ucs2leToUtf8(std::string& str)
    {
        return wc2mb(CP_UTF8, str);
    }

Project: exiv2
File: types.cpp

    uint32_t getULong(const byte* buf, ByteOrder byteOrder)
    {
        if (byteOrder == littleEndian) {
            return   (byte)buf[3] << 24 | (byte)buf[2] << 16
                   | (byte)buf[1] <<  8 | (byte)buf[0];
        }
        else {
            return   (byte)buf[0] << 24 | (byte)buf[1] << 16
                   | (byte)buf[2] <<  8 | (byte)buf[3];
        }
    }

Project: exiv2
File: convert.cpp

    void Converter::cnvXmpVersion(const char* from, const char* to)
    {
        Exiv2::XmpData::iterator pos = xmpData_->findKey(XmpKey(from));
        if (pos == xmpData_->end()) return;
        if (!prepareExifTarget(to)) return;
        std::string value = pos->toString();
        if (!pos->value().ok() || value.length() < 4) {
#ifndef SUPPRESS_WARNINGS
            EXV_WARNING << "Failed to convert " << from << " to " << to << "\n";
#endif
            return;
        }
        std::ostringstream array;

        array << static_cast<int>(value[0]) << " "
              << static_cast<int>(value[1]) << " "
              << static_cast<int>(value[2]) << " "
              << static_cast<int>(value[3]);

        (*exifData_)[to] = array.str();
        if (erase_) xmpData_->erase(pos);
    }

Project: exiv2
File: tiffcomposite_int.cpp

    TiffComponent* TiffBinaryArray::doAddChild(TiffComponent::UniquePtr tiffComponent)
    {
        TiffComponent* tc = tiffComponent.release();
        elements_.push_back(tc);
        setDecoded(true);
        return tc;
    } // TiffBinaryArray::doAddChild

Project: exiv2
File: basicio.cpp

    void FileIo::Impl::copyXattrFrom(const FileIo&)
#endif
    {
#if defined(__APPLE__)
# if defined(EXV_UNICODE_PATH)
#  error No xattr API for MacOS X with unicode support
# endif
        ssize_t namebufSize = ::listxattr(src.p_->path_.c_str(), 0, 0, 0);
        if (namebufSize < 0) {
            throw Error(kerCallFailed, src.p_->path_, strError(), "listxattr");
        }
        if (namebufSize == 0) {
            // No extended attributes in source file
            return;
        }
        char* namebuf = new char[namebufSize];
        if (::listxattr(src.p_->path_.c_str(), namebuf, namebufSize, 0) != namebufSize) {
            throw Error(kerCallFailed, src.p_->path_, strError(), "listxattr");
        }
        for (ssize_t namebufPos = 0; namebufPos < namebufSize;) {
            const char *name = namebuf + namebufPos;
            namebufPos += strlen(name) + 1;
            const ssize_t valueSize = ::getxattr(src.p_->path_.c_str(), name, 0, 0, 0, 0);
            if (valueSize < 0) {
                throw Error(kerCallFailed, src.p_->path_, strError(), "getxattr");
            }
            char* value = new char[valueSize];
            if (::getxattr(src.p_->path_.c_str(), name, value, valueSize, 0, 0) != valueSize) {
                throw Error(kerCallFailed, src.p_->path_, strError(), "getxattr");
            }
// #906.  Mountain Lion 'sandbox' terminates the app when we call setxattr
#ifndef __APPLE__
#ifdef  DEBUG
            EXV_DEBUG << "Copying xattr \"" << name << "\" with value size " << valueSize << "\n";
#endif
            if (::setxattr(path_.c_str(), name, value, valueSize, 0, 0) != 0) {
                throw Error(kerCallFailed, path_, strError(), "setxattr");
            }
            delete [] value;
#endif
        }
        delete [] namebuf;
#else
        // No xattr support for this platform.
#endif
    } // FileIo::Impl::copyXattrFrom

Project: exiv2
File: tiffcomposite_int.cpp

    uint32_t TiffSubIfd::doWriteData(IoWrapper& ioWrapper,
                                     ByteOrder byteOrder,
                                     int32_t   offset,
                                     uint32_t  dataIdx,
                                     uint32_t& imageIdx) const
    {
        uint32_t len = 0;
        for (Ifds::const_iterator i = ifds_.begin(); i != ifds_.end(); ++i) {
            len  += (*i)->write(ioWrapper, byteOrder, offset + dataIdx + len, uint32_t(-1), uint32_t(-1), imageIdx);
        }
        // Align data to word boundary
        uint32_t align = (len & 1);
        if (align) ioWrapper.putb(0x0);

        return len + align;
    } // TiffSubIfd::doWriteData

Project: exiv2
File: xmp.cpp

    const Value& Xmpdatum::value() const
    {
        if (p_->value_.get() == 0) throw Error(kerValueNotSet);
        return *p_->value_;
    }

Project: exiv2
File: pngchunk_int.cpp

        DataBuf PngChunk::parseTXTChunk(const DataBuf& data, size_t keysize, TxtChunkType type)
        {
            DataBuf arr;

            if (type == zTXt_Chunk) {
                enforce(data.size_ >= Safe::add(keysize, 2_z), Exiv2::kerCorruptedMetadata);

                // Extract a deflate compressed Latin-1 text chunk

                // we get the compression method after the key
                const byte* compressionMethod = data.pData_ + keysize + 1;
                if (*compressionMethod != 0x00) {
                    // then it isn't zlib compressed and we are sunk
#ifdef DEBUG
                    std::cerr << "Exiv2::PngChunk::parseTXTChunk: Non-standard zTXt compression method.\n";
#endif
                    throw Error(kerFailedToReadImageData);
                }

                // compressed string after the compression technique spec
                const byte* compressedText = data.pData_ + keysize + 2;
                size_t compressedTextSize = data.size_ - keysize - 2;
                enforce(compressedTextSize < data.size_, kerCorruptedMetadata);

                zlibUncompress(compressedText, (uint32_t)compressedTextSize, arr);
            } else if (type == tEXt_Chunk) {
                enforce(data.size_ >= Safe::add(keysize, 1_z), Exiv2::kerCorruptedMetadata);
                // Extract a non-compressed Latin-1 text chunk

                // the text comes after the key, but isn't null terminated
                const byte* text = data.pData_ + keysize + 1;
                const size_t textsize = data.size_ - keysize - 1;

                arr = DataBuf(text, textsize);
            } else if (type == iTXt_Chunk) {
                enforce(data.size_ >= Safe::add(keysize, 3_z), Exiv2::kerCorruptedMetadata);
                const size_t nullSeparators = std::count(&data.pData_[keysize + 3], &data.pData_[data.size_], '\0');
                enforce(nullSeparators >= 2, Exiv2::kerCorruptedMetadata);

                // Extract a deflate compressed or uncompressed UTF-8 text chunk

                // we get the compression flag after the key
                const byte compressionFlag = data.pData_[keysize + 1];
                // we get the compression method after the compression flag
                const byte compressionMethod = data.pData_[keysize + 2];

                enforce(compressionFlag == 0x00 || compressionFlag == 0x01, Exiv2::kerCorruptedMetadata);
                enforce(compressionMethod == 0x00, Exiv2::kerCorruptedMetadata);

                // language description string after the compression technique spec
                const size_t languageTextMaxSize = data.size_ - keysize - 3;
                std::string languageText =
                    string_from_unterminated((const char*)(data.pData_ + Safe::add(keysize, 3_z)), languageTextMaxSize);
                const size_t languageTextSize = languageText.size();

                enforce(static_cast<unsigned long>(data.size_) >= Safe::add(Safe::add(keysize, 4_z), languageTextSize),
                        Exiv2::kerCorruptedMetadata);
                // translated keyword string after the language description
                std::string translatedKeyText =
                    string_from_unterminated((const char*)(data.pData_ + keysize + 3 + languageTextSize + 1),
                                             data.size_ - (keysize + 3 + languageTextSize + 1));
                const unsigned int translatedKeyTextSize = static_cast<unsigned int>(translatedKeyText.size());

                if ((compressionFlag == 0x00) || (compressionFlag == 0x01 && compressionMethod == 0x00)) {
                    enforce(Safe::add(static_cast<unsigned int>(keysize + 3 + languageTextSize + 1),
                                      Safe::add(translatedKeyTextSize, 1u)) <= static_cast<unsigned int>(data.size_),
                            Exiv2::kerCorruptedMetadata);

                    const byte* text = data.pData_ + keysize + 3 + languageTextSize + 1 + translatedKeyTextSize + 1;
                    const long textsize = static_cast<long>(
                        data.size_ - (keysize + 3 + languageTextSize + 1 + translatedKeyTextSize + 1));

                    if (compressionFlag == 0x00) {
                        // then it's an uncompressed iTXt chunk
#ifdef DEBUG
                        std::cout << "Exiv2::PngChunk::parseTXTChunk: We found an uncompressed iTXt field\n";
#endif

                        arr.alloc(textsize);
                        arr = DataBuf(text, textsize);
                    } else if (compressionFlag == 0x01 && compressionMethod == 0x00) {
                        // then it's a zlib compressed iTXt chunk
#ifdef DEBUG
                        std::cout << "Exiv2::PngChunk::parseTXTChunk: We found a zlib compressed iTXt field\n";
#endif

                        // the compressed text comes after the translated keyword, but isn't null terminated
                        zlibUncompress(text, textsize, arr);
                    }
                } else {
                    // then it isn't zlib compressed and we are sunk
#ifdef DEBUG
                    std::cerr << "Exiv2::PngChunk::parseTXTChunk: Non-standard iTXt compression method.\n";
#endif
                    throw Error(kerFailedToReadImageData);
                }
            } else {
#ifdef DEBUG
                std::cerr << "Exiv2::PngChunk::parseTXTChunk: We found a field, not expected though\n";
#endif
                throw Error(kerFailedToReadImageData);
            }

            return arr;

        }  // PngChunk::parsePngChunk

Project: exiv2
File: convert.cpp

    bool convertStringCharsetWindows(std::string& str, const char* from, const char* to)
    {
        bool ret = false;
        const ConvFctList* p = find(convFctList, std::make_pair(from, to));
        std::string tmpstr = str;
        if (p) ret = p->convFct_(tmpstr);
#ifndef SUPPRESS_WARNINGS
        else {
            EXV_WARNING << "No Windows function to map character string from " << from << " to " << to << " available.\n";
        }
#endif
        if (ret) str = tmpstr;
        return ret;
    }

Project: exiv2
File: basicio.cpp

    SshIo::SshImpl::SshImpl(const std::string& url, size_t blockSize):Impl(url, blockSize)
    {
        hostInfo_ = Exiv2::Uri::Parse(url);
        Exiv2::Uri::Decode(hostInfo_);

        // remove / at the beginning of the path
        if (hostInfo_.Path[0] == '/') {
            hostInfo_.Path = hostInfo_.Path.substr(1);
        }
        ssh_ = new SSH(hostInfo_.Host, hostInfo_.Username, hostInfo_.Password, hostInfo_.Port);

        if (protocol_ == pSftp) {
            ssh_->getFileSftp(hostInfo_.Path, fileHandler_);
            if (fileHandler_ == nullptr) throw Error(kerErrorMessage, "Unable to open the file");
        } else {
            fileHandler_ = nullptr;
        }
    }

Project: exiv2
File: psdimage.cpp

    bool isPsdType(BasicIo& iIo, bool advance)
    {
        const int32_t len = 6;
        const unsigned char PsdHeader[6] = { '8', 'B', 'P', 'S', 0, 1 };
        byte buf[len];
        iIo.read(buf, len);
        if (iIo.error() || iIo.eof())
        {
            return false;
        }
        bool matched = (memcmp(buf, PsdHeader, len) == 0);
        if (!advance || !matched)
        {
            iIo.seek(-len, BasicIo::cur);
        }

        return matched;
    }

Project: exiv2
File: value.cpp

    long XmpTextValue::toLong(long /*n*/) const
    {
        return parseLong(value_, ok_);
    }

Project: exiv2
File: convert.cpp

    void moveIptcToXmp(IptcData& iptcData, XmpData& xmpData, const char *iptcCharset)
    {
        if (!iptcCharset) iptcCharset = iptcData.detectCharset();
        if (!iptcCharset) iptcCharset = "ISO-8859-1";
        Converter converter(iptcData, xmpData, iptcCharset);
        converter.setErase();
        converter.cnvToXmp();
    }

Project: exiv2
File: tiffimage.cpp

    int TiffImage::pixelHeight() const
    {
        if (pixelHeight_ != 0) return pixelHeight_;

        ExifKey key(std::string("Exif.") + primaryGroup() + std::string(".ImageLength"));
        ExifData::const_iterator imageHeight = exifData_.findKey(key);
        if (imageHeight != exifData_.end() && imageHeight->count() > 0) {
            pixelHeight_ = imageHeight->toLong();
        }
        return pixelHeight_;
    }

Project: exiv2
File: value.cpp

    void XmpValue::setXmpStruct(XmpStruct xmpStruct)
    {
        xmpStruct_ = xmpStruct;
    }

Project: exiv2
File: tiffvisitor_int.cpp

    void TiffFinder::visitImageEntry(TiffImageEntry* object)
    {
        findObject(object);
    }

Project: exiv2
File: value.cpp

    DataValue::DataValue(const byte* buf,
              long len, ByteOrder byteOrder,TypeId typeId)
        : Value(typeId)
    {
        read(buf, len, byteOrder);
    }

Project: exiv2
File: tiffcomposite_int.cpp

    TiffComponent* TiffComponent::addPath(uint16_t tag,
                                          TiffPath& tiffPath,
                                          TiffComponent* const pRoot,
                                          TiffComponent::UniquePtr object)
    {
        return doAddPath(tag, tiffPath, pRoot, std::move(object));
    } // TiffComponent::addPath

Project: exiv2
File: exif.cpp

    void ExifThumb::setJpegThumbnail(const byte* buf, long size)
    {
        exifData_["Exif.Thumbnail.Compression"] = uint16_t(6);
        Exifdatum& format = exifData_["Exif.Thumbnail.JPEGInterchangeFormat"];
        format = uint32_t(0);
        format.setDataArea(buf, size);
        exifData_["Exif.Thumbnail.JPEGInterchangeFormatLength"] = uint32_t(size);
    }

Project: exiv2
File: makernote_int.cpp

    constexpr uint32_t SonyMnHeader::sizeOfSignature()
    {
        return sizeof(signature_);
    }

Project: exiv2
File: convert.cpp

    void Converter::cnvToXmp()
    {
        for (unsigned int i = 0; i < EXV_COUNTOF(conversion_); ++i) {
            const Conversion& c = conversion_[i];
            if (   (c.metadataId_ == mdExif && exifData_)
                || (c.metadataId_ == mdIptc && iptcData_)) {
                EXV_CALL_MEMBER_FN(*this, c.key1ToKey2_)(c.key1_, c.key2_);
            }
        }
    }

Project: exiv2
File: tiffcomposite_int.cpp

    uint32_t TiffDirectory::doSizeImage() const
    {
        uint32_t len = 0;
        for (Components::const_iterator i = components_.begin(); i != components_.end(); ++i) {
            len += (*i)->sizeImage();
        }
        if (pNext_) {
            len += pNext_->sizeImage();
        }
        return len;
    } // TiffDirectory::doSizeImage

Project: exiv2
File: xmpsidecar.cpp

    void XmpSidecar::writeMetadata()
    {
        if (io_->open() != 0) {
            throw Error(kerDataSourceOpenFailed, io_->path(), strError());
        }
        IoCloser closer(*io_);


        if (writeXmpFromPacket() == false) {
            // #589 copy XMP tags
            Exiv2::XmpData  copy   ;
            for (Exiv2::XmpData::const_iterator it = xmpData_.begin(); it != xmpData_.end(); ++it) {
                if ( !matchi(it->key(),"exif") && !matchi(it->key(),"iptc") ) {
                    copy[it->key()] = it->value();
                }
            }

            // run the convertors
            copyExifToXmp(exifData_, xmpData_);
            copyIptcToXmp(iptcData_, xmpData_);

            // #589 - restore tags which were modified by the convertors
            for (Exiv2::XmpData::const_iterator it = copy.begin(); it != copy.end(); ++it) {
                xmpData_[it->key()] = it->value() ;
            }

            // #1112 - restore dates if they lost their TZ info
            for ( Exiv2::Dictionary_i it = dates_.begin() ; it != dates_.end() ; ++it ) {
                std::string   sKey = it->first;
                Exiv2::XmpKey key(sKey);
                if ( xmpData_.findKey(key) != xmpData_.end() ) {
                    std::string value_orig(it->second);
                    std::string value_now(xmpData_[sKey].value().toString());
                    // std::cout << key << " -> " << value_now << " => " << value_orig << std::endl;
                    if ( value_orig.find(value_now.substr(0,10)) != std::string::npos ) {
                        xmpData_[sKey] = value_orig ;
                    }
                }
            }

            if (XmpParser::encode(xmpPacket_, xmpData_,
                                  XmpParser::omitPacketWrapper|XmpParser::useCompactFormat) > 1) {
#ifndef SUPPRESS_WARNINGS
                EXV_ERROR << "Failed to encode XMP metadata.\n";
#endif
            }
        }
        if (xmpPacket_.size() > 0) {
            if (xmpPacket_.substr(0, 5)  != "<?xml") {
                xmpPacket_ = xmlHeader + xmpPacket_ + xmlFooter;
            }
            BasicIo::UniquePtr tempIo(new MemIo);
            assert(tempIo.get() != 0);
            // Write XMP packet
            if (tempIo->write(reinterpret_cast<const byte*>(xmpPacket_.data()), xmpPacket_.size()) != xmpPacket_.size())
                throw Error(kerImageWriteFailed);
            if (tempIo->error()) throw Error(kerImageWriteFailed);
            io_->close();
            io_->transfer(*tempIo); // may throw
        }
    } // XmpSidecar::writeMetadata

Project: exiv2
File: tiffimage.cpp

    void TiffImage::setComment(const std::string& /*comment*/)
    {
        // not supported
        throw(Error(kerInvalidSettingForImage, "Image comment", "TIFF"));
    }

Project: exiv2
File: tiffvisitor_int.cpp

    void TiffReader::visitIfdMakernoteEnd(TiffIfdMakernote* /*object*/)
    {
        // Reset state (byte order, create function, offset) back to that for the image
        setOrigState();
    } // TiffReader::visitIfdMakernoteEnd

Project: exiv2
File: value.cpp

    std::ostream& AsciiValue::write(std::ostream& os) const
    {
        // Write only up to the first '\0' (if any)
        std::string::size_type pos = value_.find_first_of('\0');
        if (pos == std::string::npos) pos = value_.size();
        return os << value_.substr(0, pos);
    }

Project: exiv2
File: exif.cpp

    const wchar_t* JpegThumbnail::wextension() const
    {
        return EXV_WIDEN(".jpg");
    }

Project: exiv2
File: preview.cpp

    Loader::UniquePtr createLoaderNative(PreviewId id, const Image &image, int parIdx)
    {
        return Loader::UniquePtr(new LoaderNative(id, image, parIdx));
    }

Project: exiv2
File: value.cpp

    XmpTextValue::XmpTextValue(const std::string& buf)
        : XmpValue(xmpText)
    {
        read(buf);
    }

Project: exiv2
File: image.cpp

    bool Image::supportsMetadata(MetadataId metadataId) const
    {
        return (supportedMetadata_ & metadataId) != 0;
    }

Project: exiv2
File: convert.cpp

    bool utf8ToUcs2be(std::string& str)
    {
        bool ret = mb2wc(CP_UTF8, str);
        if (ret) ret = swapBytes(str);
        return ret;
    }

Project: exiv2
File: image.cpp

    Image::UniquePtr ImageFactory::create(ImageType type, const std::string& path)
    {
        std::unique_ptr<FileIo> fileIo(new FileIo(path));
        // Create or overwrite the file, then close it
        if (fileIo->open("w+b") != 0) {
            throw Error(kerFileOpenFailed, path, "w+b", strError());
        }
        fileIo->close();
        BasicIo::UniquePtr io(std::move(fileIo));
        Image::UniquePtr image = create(type, std::move(io));
        if (!image)
            throw Error(kerUnsupportedImageType, static_cast<int>(type));
        return image;
    }

Project: exiv2
File: jpgimage.cpp

    static inline bool inRange2(int value,int lo1,int hi1, int lo2,int hi2)
    {
        return inRange(lo1,value,hi1) || inRange(lo2,value,hi2);
    }

Project: exiv2
File: tiffvisitor_int.cpp

    void TiffCopier::copyObject(TiffComponent* object)
    {
        assert(object != 0);

        if (pHeader_->isImageTag(object->tag(), object->group(), pPrimaryGroups_)) {
            TiffComponent::UniquePtr clone = object->clone();
            // Assumption is that the corresponding TIFF entry doesn't exist
            TiffPath tiffPath;
            TiffCreator::getPath(tiffPath, object->tag(), object->group(), root_);
            pRoot_->addPath(object->tag(), tiffPath, pRoot_, std::move(clone));
#ifdef DEBUG
            ExifKey key(object->tag(), groupName(object->group()));
            std::cerr << "Copied " << key << "\n";
#endif
        }
    }

Project: exiv2
File: preview.cpp

    PreviewImage::PreviewImage(const PreviewImage& rhs)
    {
        properties_ = rhs.properties_;
        pData_ = new byte[rhs.size_];
        memcpy(pData_, rhs.pData_, rhs.size_);
        size_ = rhs.size_;
    }

Project: exiv2
File: value.cpp

    StringValue* StringValue::clone_() const
    {
        return new StringValue(*this);
    }

Project: exiv2
File: makernote_int.cpp

    FujiMnHeader::~FujiMnHeader()
    {
    }

Project: exiv2
File: iptc.cpp

    std::string Iptcdatum::tagName() const
    {
        return key_.get() == 0 ? "" : key_->tagName();
    }

Project: exiv2
File: actions.cpp

    int Timestamp::read(const std::string& path)
    {
        struct stat buf;
        int rc = stat(path.c_str(), &buf);
        if (0 == rc) {
            actime_ = buf.st_atime;
            modtime_ = buf.st_mtime;
        }
        return rc;
    }

Project: exiv2
File: tiffvisitor_int.cpp

    void TiffCopier::visitDirectory(TiffDirectory* /*object*/)
    {
        // Do not copy directories (avoids problems with SubIfds)
    }

Project: exiv2
File: tiffimage.cpp

    ByteOrder TiffParser::decode(
              ExifData& exifData,
              IptcData& iptcData,
              XmpData&  xmpData,
        const byte*     pData,
              uint32_t  size
    )
    {
        return TiffParserWorker::decode(exifData,
                                        iptcData,
                                        xmpData,
                                        pData,
                                        size,
                                        Tag::root,
                                        TiffMapping::findDecoder);
    } // TiffParser::decode

Project: exiv2
File: value.cpp

    XmpValue::XmpArrayType XmpValue::xmpArrayType() const
    {
        return xmpArrayType_;
    }

Project: exiv2
File: tiffimage.cpp

    TiffHeader::TiffHeader(ByteOrder byteOrder, uint32_t offset, bool hasImageTags)
        : TiffHeaderBase(42, 8, byteOrder, offset),
          hasImageTags_(hasImageTags)
    {
    }

Project: exiv2
File: exif.cpp

    std::string Exifdatum::tagName() const
    {
        return key_.get() == 0 ? "" : key_->tagName();
    }

Project: exiv2
File: iptc.cpp

    IptcData::iterator IptcData::erase(IptcData::iterator pos)
    {
        return iptcMetadata_.erase(pos);
    }

Project: exiv2
File: xmpsidecar.cpp

    XmpSidecar::XmpSidecar(BasicIo::UniquePtr io, bool create)
        : Image(ImageType::xmp, mdXmp, std::move(io))
    {
        if (create) {
            if (io_->open() == 0) {
                IoCloser closer(*io_);
                io_->write(reinterpret_cast<const byte*>(xmlHeader), xmlHdrCnt);
            }
        }
    } // XmpSidecar::XmpSidecar

Project: exiv2
File: exif.cpp

    const char* ExifThumbC::extension() const
    {
        Thumbnail::UniquePtr thumbnail = Thumbnail::create(exifData_);
        if (thumbnail.get() == 0) return "";
        return thumbnail->extension();
    }

Project: exiv2
File: xmp.cpp

    bool XmpParser::initialize(XmpParser::XmpLockFct, void* )
    {
        initialized_ = true;
        return initialized_;
    }

Project: exiv2
File: actions.cpp

        Timestamp() : actime_(0), modtime_(0)
        {
        }

Project: exiv2
File: basicio.cpp

    size_t curlWriter(char* data, size_t size, size_t nmemb,
                      std::string* writerData)
    {
        if (writerData == nullptr) return 0;
        writerData->append(data, size*nmemb);
        return size * nmemb;
    }

Project: exiv2
File: pgfimage.cpp

    void PgfImage::writeMetadata()
    {
        if (io_->open() != 0)
        {
            throw Error(kerDataSourceOpenFailed, io_->path(), strError());
        }
        IoCloser closer(*io_);
        BasicIo::UniquePtr tempIo(new MemIo);
        assert (tempIo.get() != 0);

        doWriteMetadata(*tempIo); // may throw
        io_->close();
        io_->transfer(*tempIo); // may throw

    } // PgfImage::writeMetadata

Project: exiv2
File: webpimage.cpp

    void WebPImage::printStructure(std::ostream& out, PrintStructureOption option,int depth)
    {
        if (io_->open() != 0) {
            throw Error(kerDataSourceOpenFailed, io_->path(), strError());
        }
        // Ensure this is the correct image type
        if (!isWebPType(*io_, true)) {
            if (io_->error() || io_->eof()) throw Error(kerFailedToReadImageData);
            throw Error(kerNotAnImage, "WEBP");
        }

        bool bPrint  = option==kpsBasic || option==kpsRecursive;
        if ( bPrint || option == kpsXMP || option == kpsIccProfile || option == kpsIptcErase ) {
            byte      data [WEBP_TAG_SIZE * 2];
            io_->read(data, WEBP_TAG_SIZE * 2);
            uint64_t filesize = Exiv2::getULong(data + WEBP_TAG_SIZE, littleEndian);
            DataBuf  chunkId(5)      ;
            chunkId.pData_[4] = '\0' ;

            if ( bPrint ) {
                out << Internal::indent(depth)
                << "STRUCTURE OF WEBP FILE: "
                << io().path()
                << std::endl;
                out << Internal::indent(depth)
                << Internal::stringFormat(" Chunk |   Length |   Offset | Payload")
                << std::endl;
            }

            io_->seek(0,BasicIo::beg); // rewind
            while ( !io_->eof() && (uint64_t) io_->tell() < filesize) {
                uint64_t offset = (uint64_t) io_->tell();
                byte     size_buff[WEBP_TAG_SIZE];
                io_->read(chunkId.pData_, WEBP_TAG_SIZE);
                io_->read(size_buff, WEBP_TAG_SIZE);
                long size = Exiv2::getULong(size_buff, littleEndian);
                DataBuf payload(offset?size:WEBP_TAG_SIZE); // header is different from chunks
                io_->read(payload.pData_, payload.size_);

                if ( bPrint ) {
                    out << Internal::indent(depth)
                    << Internal::stringFormat("  %s | %8u | %8u | ", (const char*)chunkId.pData_,(uint32_t)size,(uint32_t)offset)
                    << Internal::binaryToString(makeSlice(payload, 0, payload.size_ > 32 ? 32 : payload.size_))
                    << std::endl;
                }

                if ( equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_EXIF) && option==kpsRecursive ) {
                    // create memio object with the payload, then print the structure
                    BasicIo::UniquePtr p = BasicIo::UniquePtr(new MemIo(payload.pData_,payload.size_));
                    printTiffStructure(*p,out,option,depth);
                }

                bool bPrintPayload = (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_XMP) && option==kpsXMP)
                                  || (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_ICCP) && option==kpsIccProfile)
                                   ;
                if ( bPrintPayload ) {
                    out.write((const char*) payload.pData_,payload.size_);
                }

                if ( offset && io_->tell() % 2 ) io_->seek(+1, BasicIo::cur); // skip padding byte on sub-chunks
            }
        }
    }

Project: exiv2
File: basicio.cpp

    MemIo::Impl::Impl(const byte* data, size_t size)
        : data_(const_cast<byte*>(data)),
          idx_(0),
          size_(size),
          sizeAlloced_(0),
          isMalloced_(false),
          eof_(false)
    {
    }

Project: exiv2
File: rafimage.cpp

    Image::UniquePtr newRafInstance(BasicIo::UniquePtr io, bool create)
    {
        Image::UniquePtr image(new RafImage(std::move(io), create));
        if (!image->good()) {
            image.reset();
        }
        return image;
    }

Project: exiv2
File: pngimage.cpp

    void PngImage::readMetadata()
    {
#ifdef DEBUG
        std::cerr << "Exiv2::PngImage::readMetadata: Reading PNG file " << io_->path() << std::endl;
#endif
        if (io_->open() != 0) {
            throw Error(kerDataSourceOpenFailed, io_->path(), strError());
        }
        IoCloser closer(*io_);
        if (!isPngType(*io_, true)) {
            throw Error(kerNotAnImage, "PNG");
        }
        clearMetadata();

        const long imgSize = (long)io_->size();
        DataBuf cheaderBuf(8);  // Chunk header: 4 bytes (data size) + 4 bytes (chunk type).

        while (!io_->eof()) {
            std::memset(cheaderBuf.pData_, 0x0, cheaderBuf.size_);
            readChunk(cheaderBuf, *io_);  // Read chunk header.

            // Decode chunk data length.
            uint32_t chunkLength = Exiv2::getULong(cheaderBuf.pData_, Exiv2::bigEndian);
            long pos = io_->tell();
            if (pos == -1 || chunkLength > uint32_t(0x7FFFFFFF) || static_cast<long>(chunkLength) > imgSize - pos) {
                throw Exiv2::Error(kerFailedToReadImageData);
            }

            std::string chunkType(reinterpret_cast<char*>(cheaderBuf.pData_) + 4, 4);
#ifdef DEBUG
            std::cout << "Exiv2::PngImage::readMetadata: chunk type: " << chunkType << " length: " << chunkLength
                      << std::endl;
#endif

            /// \todo analyse remaining chunks of the standard
            // Perform a chunk triage for item that we need.
            if (chunkType == "IEND" || chunkType == "IHDR" || chunkType == "tEXt" || chunkType == "zTXt" ||
                chunkType == "iTXt" || chunkType == "iCCP") {
                DataBuf chunkData(chunkLength);
                readChunk(chunkData, *io_);  // Extract chunk data.

                if (chunkType == "IEND") {
                    return;  // Last chunk found: we stop parsing.
                } else if (chunkType == "IHDR" && chunkData.size_ >= 8) {
                    Internal::PngImageHeader header;
                    PngChunk::decodeIHDRChunk(chunkData, header);
                    pixelWidth_ = header.width;
                    pixelHeight_ = header.height;
                    /// \todo handle rest of data
                } else if (chunkType == "tEXt") {
                    PngChunk::decodeTXTChunk(this, chunkData, PngChunk::tEXt_Chunk);
                } else if (chunkType == "zTXt") {
                    PngChunk::decodeTXTChunk(this, chunkData, PngChunk::zTXt_Chunk);
                } else if (chunkType == "iTXt") {
                    PngChunk::decodeTXTChunk(this, chunkData, PngChunk::iTXt_Chunk);
                } else if (chunkType == "iCCP") {
                    // The ICC profile name can vary from 1-79 characters.
                    uint32_t iccOffset = 0;
                    do {
                      enforce(iccOffset < 80 && iccOffset < chunkLength, Exiv2::kerCorruptedMetadata);
                    } while(chunkData.pData_[iccOffset++] != 0x00);

                    profileName_ = std::string(reinterpret_cast<char *>(chunkData.pData_), iccOffset-1);
                    ++iccOffset; // +1 = 'compressed' flag
                    enforce(iccOffset <= chunkLength, Exiv2::kerCorruptedMetadata);

                    zlibToDataBuf(chunkData.pData_ + iccOffset, chunkLength - iccOffset, iccProfile_);
#ifdef DEBUG
                    std::cout << "Exiv2::PngImage::readMetadata: profile name: " << profileName_ << std::endl;
                    std::cout << "Exiv2::PngImage::readMetadata: iccProfile.size_ (uncompressed) : "
                              << iccProfile_.size_ << std::endl;
#endif
                }

                // Set chunkLength to 0 in case we have read a supported chunk type. Otherwise, we need to seek the
                // file to the next chunk position.
                chunkLength = 0;
            }

            // Move to the next chunk: chunk data size + 4 CRC bytes.
#ifdef DEBUG
            std::cout << "Exiv2::PngImage::readMetadata: Seek to offset: " << chunkLength + 4 << std::endl;
#endif
            io_->seek(chunkLength + 4, BasicIo::cur);
            if (io_->error() || io_->eof()) {
                throw Error(kerFailedToReadImageData);
            }
        }
    }  // PngImage::readMetadata

Project: exiv2
File: xmp.cpp

    Exiv2::XmpValue::XmpArrayType xmpArrayType(const XMP_OptionBits& opt)
    {
        return Exiv2::XmpValue::xmpArrayType(arrayValueTypeId(opt));
    }

Project: exiv2
File: rafimage.cpp

    void RafImage::setExifData(const ExifData& /*exifData*/)
    {
        // Todo: implement me!
        throw(Error(kerInvalidSettingForImage, "Exif metadata", "RAF"));
    }

Project: exiv2
File: value.cpp

    DataValue::~DataValue()
    {
    }

Project: exiv2
File: types.cpp

    const char* exvGettext(const char* str)
    {
#ifdef EXV_ENABLE_NLS
        return _exvGettext(str);
#else
        return str;
#endif
    }

Project: exiv2
File: value.cpp

    CommentValue::CharsetId CommentValue::charsetId() const
    {
        CharsetId charsetId = undefined;
        if (value_.length() >= 8) {
            const std::string code = value_.substr(0, 8);
            charsetId = CharsetInfo::charsetIdByCode(code);
        }
        return charsetId;
    }

Project: exiv2
File: preview.cpp

    long PreviewImage::writeFile(const std::string& path) const
    {
        std::string name = path + extension();
        // Todo: Creating a DataBuf here unnecessarily copies the memory
        DataBuf buf(pData_, size_);
        return Exiv2::writeFile(buf, name);
    }

Project: exiv2
File: mrwimage.cpp

    void MrwImage::setComment(const std::string& /*comment*/)
    {
        // not supported
        throw(Error(kerInvalidSettingForImage, "Image comment", "MRW"));
    }

Project: exiv2
File: tiffcomposite_int.cpp

    TiffComponent* TiffDirectory::doAddPath(uint16_t tag,
                                            TiffPath& tiffPath,
                                            TiffComponent* const pRoot,
                                            TiffComponent::UniquePtr object)
    {
        assert(tiffPath.size() > 1);
        tiffPath.pop();
        const TiffPathItem tpi = tiffPath.top();

        TiffComponent* tc = 0;
        // Try to use an existing component if there is still at least one
        // composite tag on the stack or the tag to add is the MakerNote tag.
        // This is used to prevent duplicate entries. Sub-IFDs also, but the > 1
        // condition takes care of them, see below.
        if (   tiffPath.size() > 1
            || (tpi.extendedTag() == 0x927c && tpi.group() == exifId)) {
            if (tpi.extendedTag() == Tag::next) {
                tc = pNext_;
            }
            else {
                for (Components::iterator i = components_.begin(); i != components_.end(); ++i) {
                    if ((*i)->tag() == tpi.tag() && (*i)->group() == tpi.group()) {
                        tc = *i;
                        break;
                    }
                }
            }
        }
        if (tc == 0) {
            TiffComponent::UniquePtr atc;
            if (tiffPath.size() == 1 && object.get() != 0) {
                atc = std::move(object);
            }
            else {
                atc = TiffCreator::create(tpi.extendedTag(), tpi.group());
            }
            assert(atc.get() != 0);

            // Prevent dangling sub-IFD tags: Do not add a sub-IFD component without children.
            // Todo: How to check before creating the component?
            if (tiffPath.size() == 1 && dynamic_cast<TiffSubIfd*>(atc.get()) != 0) return 0;

            if (tpi.extendedTag() == Tag::next) {
                tc = this->addNext(std::move(atc));
            }
            else {
                tc = this->addChild(std::move(atc));
            }
        }
        return tc->addPath(tag, tiffPath, pRoot, std::move(object));
    } // TiffDirectory::doAddPath

Project: exiv2
File: makernote_int.cpp

    Nikon2MnHeader::Nikon2MnHeader() : start_(0)
    {
        read(signature_, sizeOfSignature(), invalidByteOrder);
    }

Project: exiv2
File: tiff-test.cpp

void print(const ExifData& exifData)
{
    if (exifData.empty()) {
        std::string error("No Exif data found in the file");
        throw Exiv2::Error(kerErrorMessage, error);
    }
    Exiv2::ExifData::const_iterator end = exifData.end();
    for (Exiv2::ExifData::const_iterator i = exifData.begin(); i != end; ++i) {
        std::cout << std::setw(44) << std::setfill(' ') << std::left
                  << i->key() << " "
                  << "0x" << std::setw(4) << std::setfill('0') << std::right
                  << std::hex << i->tag() << " "
                  << std::setw(9) << std::setfill(' ') << std::left
                  << i->typeName() << " "
                  << std::dec << std::setw(3)
                  << std::setfill(' ') << std::right
                  << i->count() << "  "
                  << std::dec << i->value()
                  << "\n";
    }
}

Project: exiv2
File: value.cpp

    TimeValue* TimeValue::clone_() const
    {
        return new TimeValue(*this);
    }

Project: exiv2
File: mrwimage.cpp

    void MrwImage::setExifData(const ExifData& /*exifData*/)
    {
        // Todo: implement me!
        throw(Error(kerInvalidSettingForImage, "Exif metadata", "MRW"));
    }

Project: exiv2
File: value.cpp

    int XmpValue::read(const byte* buf,
                       size_t len,
                       ByteOrder /*byteOrder*/)
    {
        std::string s(reinterpret_cast<const char*>(buf), len);
        return read(s);
    }

Project: exiv2
File: image.cpp

    void Image::setIptcData(const IptcData& iptcData)
    {
        iptcData_ = iptcData;
    }

Project: exiv2
File: tiffvisitor_int.cpp

    void TiffCopier::visitBinaryElement(TiffBinaryElement* object)
    {
        copyObject(object);
    }

Project: exiv2
File: tiffvisitor_int.cpp

    void TiffCopier::visitIfdMakernote(TiffIfdMakernote* object)
    {
        copyObject(object);
    }

Project: exiv2
File: xmp.cpp

    std::string Xmpdatum::key() const
    {
        return p_->key_.get() == 0 ? "" : p_->key_->key();
    }

Project: exiv2
File: xmp.cpp

    const char* Xmpdatum::typeName() const
    {
        return TypeInfo::typeName(typeId());
    }

Project: exiv2
File: actions.cpp

    std::unique_ptr<Extract> Extract::clone() const
    {
        return std::unique_ptr<Extract>(clone_());
    }

Project: exiv2
File: bigtiffimage.cpp

                void printStructure(std::ostream& os, PrintStructureOption option, int depth)
                {
                    printIFD(os, option, header_.dirOffset(), depth - 1);
                }

Project: exiv2
File: value.cpp

    DataBuf Value::dataArea() const
    {
        return DataBuf(0, 0);
    }

Project: exiv2
File: tiffcomposite_int.cpp

    TiffComponent* TiffMnEntry::doAddNext(TiffComponent::UniquePtr tiffComponent)
    {
        TiffComponent* tc = 0;
        if (mn_) {
            tc = mn_->addNext(std::move(tiffComponent));
        }
        return tc;
    } // TiffMnEntry::doAddNext

Project: exiv2
File: xmp.cpp

    void XmpParser::registerNs(const std::string& ns,
                               const std::string& prefix)
    {
        try {
            initialize();
            AutoLock autoLock(xmpLockFct_, pLockData_);
            SXMPMeta::DeleteNamespace(ns.c_str());
#ifdef EXV_ADOBE_XMPSDK
            SXMPMeta::RegisterNamespace(ns.c_str(), prefix.c_str(),nullptr);
#else
            SXMPMeta::RegisterNamespace(ns.c_str(), prefix.c_str());
#endif
        }
        catch (const XMP_Error& /* e */) {
            // throw Error(kerXMPToolkitError, e.GetID(), e.GetErrMsg());
        }
    } // XmpParser::registerNs

Project: exiv2
File: image.cpp

    uint64_t Image::byteSwap8(const DataBuf& buf,size_t offset,bool bSwap) const
    {
        uint64_t v;
        byte*    p = reinterpret_cast<byte *>(&v);

        for(int i = 0; i < 8; i++)
            p[i] = buf.pData_[offset + i];

        return Image::byteSwap(v,bSwap);
    }

Project: exiv2
File: tiffimage.cpp

    WriteMethod TiffParser::encode(
              BasicIo&  io,
        const byte*     pData,
              uint32_t  size,
              ByteOrder byteOrder,
        const ExifData& exifData,
        const IptcData& iptcData,
        const XmpData&  xmpData
    )
    {
        // Copy to be able to modify the Exif data
        ExifData ed = exifData;

        // Delete IFDs which do not occur in TIFF images
        static const IfdId filteredIfds[] = {
            panaRawId
        };
        for (unsigned int i = 0; i < EXV_COUNTOF(filteredIfds); ++i) {
#ifdef DEBUG
            std::cerr << "Warning: Exif IFD " << filteredIfds[i] << " not encoded\n";
#endif
            ed.erase(std::remove_if(ed.begin(),
                                    ed.end(),
                                    FindExifdatum(filteredIfds[i])),
                     ed.end());
        }

        std::unique_ptr<TiffHeaderBase> header(new TiffHeader(byteOrder));
        return TiffParserWorker::encode(io,
                                        pData,
                                        size,
                                        ed,
                                        iptcData,
                                        xmpData,
                                        Tag::root,
                                        TiffMapping::findEncoder,
                                        header.get(),
                                        0);
    } // TiffParser::encode

Project: exiv2
File: actions.cpp

    TaskFactory::~TaskFactory()
    {
        for (auto it = registry_.begin(); it != registry_.end(); ++it) {
            delete it->second;
        }
    }

Project: exiv2
File: exif.cpp

    long ExifData::count() const { return static_cast<long>(exifMetadata_.size()); }

Project: exiv2
File: tiffcomposite_int.cpp

    uint32_t TiffEntryBase::doWriteImage(IoWrapper&/*ioWrapper*/,
                                         ByteOrder /*byteOrder*/) const
    {
        return 0;
    } // TiffEntryBase::doWriteImage

Project: exiv2
File: types.cpp

    std::istream& operator>>(std::istream& is, URational& r)
    {
        // http://dev.exiv2.org/boards/3/topics/1912?r=1915
        /// \todo This implementation seems to be duplicated for the Rational type. Try to remove duplication
        if ( std::tolower(is.peek()) == 'f' ) {
            char  F = 0;
            float f = 0.f;
            is >> F >> f ;
            f  = 2.0f * std::log(f) / std::log(2.0f) ;
            r  = Exiv2::floatToRationalCast(f);
        } else {
            uint32_t nominator = 0;
            uint32_t denominator = 0;
            char c('\0');
            is >> nominator >> c >> denominator;
            if (c != '/')
                is.setstate(std::ios::failbit);
            if (is)
                r = std::make_pair(nominator, denominator);
        }
        return is;
    }

Project: exiv2
File: makernote_int.cpp

    TiffComponent* newOlympusMn2(uint16_t tag,
                                 IfdId    group,
                                 IfdId    mnGroup)
    {
        return new TiffIfdMakernote(tag, group, mnGroup, new OlympusMnHeader);
    }

Project: exiv2
File: tiffvisitor_int.cpp

    void TiffFinder::visitEntry(TiffEntry* object)
    {
        findObject(object);
    }