1// Copyright 2014 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "components/enhanced_bookmarks/image_store_util.h"
6
7#import <UIKit/UIKit.h>
8
9#include "base/mac/scoped_cftyperef.h"
10#include "base/mac/scoped_nsobject.h"
11
12namespace {
13// An implementation of RefCountedMemory, where the bytes are stored in a
14// NSData. This class assumes the NSData is non mutable to avoid a copy.
15class RefCountedNSDataMemory : public base::RefCountedMemory {
16 public:
17  explicit RefCountedNSDataMemory(NSData* memory) : data_([memory retain]) {}
18
19  virtual const unsigned char* front() const OVERRIDE {
20    return reinterpret_cast<const unsigned char*>([data_ bytes]);
21  }
22
23  virtual size_t size() const OVERRIDE {
24    return [data_ length];
25  }
26
27private:
28  virtual ~RefCountedNSDataMemory() {}
29
30  base::scoped_nsobject<NSData> data_;
31  DISALLOW_COPY_AND_ASSIGN(RefCountedNSDataMemory);
32};
33}  // namespace
34
35namespace enhanced_bookmarks {
36
37// Encodes the UIImage representation of a gfx::Image.
38scoped_refptr<base::RefCountedMemory> BytesForImage(const gfx::Image& image) {
39  DCHECK(image.HasRepresentation(gfx::Image::kImageRepCocoaTouch));
40  return scoped_refptr<RefCountedNSDataMemory>(new RefCountedNSDataMemory(
41      [NSKeyedArchiver archivedDataWithRootObject:image.ToUIImage()]));
42}
43
44// Decodes the UIImage in the bytes and returns a gfx::Image.
45gfx::Image ImageForBytes(const scoped_refptr<base::RefCountedMemory>& data) {
46  return gfx::Image([[NSKeyedUnarchiver unarchiveObjectWithData:
47      [NSData dataWithBytes:data->front() length:data->size()]] retain]);
48}
49
50}  // namespace enhanced_bookmarks
51