| // Copyright (C) 2016 The Android Open Source Project |
| // |
| // Licensed under the Apache License, Version 2.0 (the "License"); |
| // you may not use this file except in compliance with the License. |
| // You may obtain a copy of the License at |
| // |
| // http://www.apache.org/licenses/LICENSE-2.0 |
| // |
| // Unless required by applicable law or agreed to in writing, software |
| // distributed under the License is distributed on an "AS IS" BASIS, |
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| // See the License for the specific language governing permissions and |
| // limitations under the License. |
| |
| package stash |
| |
| import ( |
| "bytes" |
| "io" |
| "time" |
| |
| "android.googlesource.com/platform/tools/gpu/framework/file" |
| "android.googlesource.com/platform/tools/gpu/framework/log" |
| "github.com/golang/protobuf/ptypes" |
| ) |
| |
| type memoryStore struct { |
| entityIndex |
| data map[string][]byte |
| } |
| |
| // NewMemoryStore returns a purly in memory implementation of Store. |
| func NewMemoryStore() Store { |
| store := &memoryStore{data: map[string][]byte{}} |
| store.entityIndex.init() |
| return store |
| } |
| |
| func (s *memoryStore) Close() {} |
| |
| func (s *memoryStore) Open(ctx log.Context, id string) (io.Reader, error) { |
| s.mu.Lock() |
| defer s.mu.Unlock() |
| if data, found := s.data[id]; found { |
| return bytes.NewReader(data), nil |
| } |
| return nil, nil |
| } |
| |
| func (s *memoryStore) Read(ctx log.Context, id string) ([]byte, error) { |
| s.mu.Lock() |
| defer s.mu.Unlock() |
| return s.data[id], nil |
| } |
| |
| func (s *memoryStore) Create(ctx log.Context, info *Upload) (io.WriteCloser, error) { |
| s.mu.Lock() |
| defer s.mu.Unlock() |
| if _, found := s.byID[info.Id]; found { |
| return nil, ctx.AsError("Stash entity already exists") |
| } |
| now, _ := ptypes.TimestampProto(time.Now()) |
| w := &memoryStoreWriter{ |
| store: s, |
| entity: &Entity{ |
| Upload: info, |
| Status: Uploading, |
| Length: 0, |
| Timestamp: now, |
| }, |
| } |
| s.lockedAddEntry(ctx, w.entity) |
| return w, nil |
| } |
| |
| func (s *memoryStore) GetFile(ctx log.Context, id string, filename file.Path) error { |
| return ctx.AsError("Memory stash does not support file access") |
| } |
| |
| type memoryStoreWriter struct { |
| store *memoryStore |
| entity *Entity |
| buf bytes.Buffer |
| } |
| |
| func (w *memoryStoreWriter) Write(b []byte) (int, error) { |
| return w.buf.Write(b) |
| } |
| |
| func (w *memoryStoreWriter) Close() error { |
| data := w.buf.Bytes() |
| w.entity.Status = Present |
| w.entity.Length = int64(len(data)) |
| w.store.data[w.entity.Upload.Id] = data |
| return nil |
| } |