com.facebook.common.internal.Preconditions Java Examples
The following examples show how to use
com.facebook.common.internal.Preconditions.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: StreamUtil.java From FanXin-based-HuanXin with GNU General Public License v2.0 | 6 votes |
/** * Skips exactly bytesCount bytes in inputStream unless end of stream is reached first. * * @param inputStream input stream to skip bytes from * @param bytesCount number of bytes to skip * @return number of skipped bytes * @throws IOException */ public static long skip(final InputStream inputStream, final long bytesCount) throws IOException { Preconditions.checkNotNull(inputStream); Preconditions.checkArgument(bytesCount >= 0); long toSkip = bytesCount; while (toSkip > 0) { final long skipped = inputStream.skip(toSkip); if (skipped > 0) { toSkip -= skipped; continue; } if (inputStream.read() != -1) { toSkip--; continue; } return bytesCount - toSkip; } return bytesCount; }
Example #2
Source File: BitmapUtil.java From fresco with MIT License | 6 votes |
/** * Decodes the bounds of an image and returns its width and height or null if the size can't be * determined * * @param is the InputStream containing the image data * @return dimensions of the image */ public static @Nullable Pair<Integer, Integer> decodeDimensions(InputStream is) { Preconditions.checkNotNull(is); ByteBuffer byteBuffer = DECODE_BUFFERS.acquire(); if (byteBuffer == null) { byteBuffer = ByteBuffer.allocate(DECODE_BUFFER_SIZE); } BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; try { options.inTempStorage = byteBuffer.array(); BitmapFactory.decodeStream(is, null, options); return (options.outWidth == -1 || options.outHeight == -1) ? null : new Pair<>(options.outWidth, options.outHeight); } finally { DECODE_BUFFERS.release(byteBuffer); } }
Example #3
Source File: PoolParams.java From fresco with MIT License | 6 votes |
/** * Set up pool params * * @param maxSizeSoftCap soft cap on max size of the pool * @param maxSizeHardCap hard cap on max size of the pool * @param bucketSizes (optional) bucket sizes and lengths for the pool * @param minBucketSize min bucket size for the pool * @param maxBucketSize max bucket size for the pool * @param maxNumThreads the maximum number of threads in the pool, or -1 if the pool doesn't care */ public PoolParams( int maxSizeSoftCap, int maxSizeHardCap, @Nullable SparseIntArray bucketSizes, int minBucketSize, int maxBucketSize, int maxNumThreads) { Preconditions.checkState(maxSizeSoftCap >= 0 && maxSizeHardCap >= maxSizeSoftCap); this.maxSizeSoftCap = maxSizeSoftCap; this.maxSizeHardCap = maxSizeHardCap; this.bucketSizes = bucketSizes; this.minBucketSize = minBucketSize; this.maxBucketSize = maxBucketSize; this.maxNumThreads = maxNumThreads; }
Example #4
Source File: CountingMemoryCache.java From fresco with MIT License | 6 votes |
/** * Gets the value with the given key to be reused, or null if there is no such value. * * <p>The item can be reused only if it is exclusively owned by the cache. */ @Nullable public CloseableReference<V> reuse(K key) { Preconditions.checkNotNull(key); CloseableReference<V> clientRef = null; boolean removed = false; Entry<K, V> oldExclusive = null; synchronized (this) { oldExclusive = mExclusiveEntries.remove(key); if (oldExclusive != null) { Entry<K, V> entry = mCachedEntries.remove(key); Preconditions.checkNotNull(entry); Preconditions.checkState(entry.clientCount == 0); // optimization: instead of cloning and then closing the original reference, // we just do a move clientRef = entry.valueRef; removed = true; } } if (removed) { maybeNotifyExclusiveEntryRemoval(oldExclusive); } return clientRef; }
Example #5
Source File: AbstractDraweeController.java From fresco with MIT License | 6 votes |
/** Adds controller listener. */ public void addControllerListener(ControllerListener<? super INFO> controllerListener) { Preconditions.checkNotNull(controllerListener); if (mControllerListener instanceof InternalForwardingListener) { ((InternalForwardingListener<INFO>) mControllerListener).addListener(controllerListener); return; } if (mControllerListener != null) { mControllerListener = InternalForwardingListener.createInternal(mControllerListener, controllerListener); return; } // Listener only receives <INFO>, it never produces one. // That means if it can accept <? super INFO>, it can very well accept <INFO>. mControllerListener = (ControllerListener<INFO>) controllerListener; }
Example #6
Source File: ArrayDrawable.java From fresco with MIT License | 6 votes |
/** Sets a new drawable at the specified index, and return the previous drawable, if any. */ @Nullable public Drawable setDrawable(int index, @Nullable Drawable drawable) { Preconditions.checkArgument(index >= 0); Preconditions.checkArgument(index < mLayers.length); final Drawable oldDrawable = mLayers[index]; if (drawable != oldDrawable) { if (drawable != null && mIsMutated) { drawable.mutate(); } DrawableUtils.setCallbacks(mLayers[index], null, null); DrawableUtils.setCallbacks(drawable, null, null); DrawableUtils.setDrawableProperties(drawable, mDrawableProperties); DrawableUtils.copyProperties(drawable, this); DrawableUtils.setCallbacks(drawable, this, this); mIsStatefulCalculated = false; mLayers[index] = drawable; invalidateSelf(); } return oldDrawable; }
Example #7
Source File: GingerbreadPurgeableDecoder.java From fresco with MIT License | 6 votes |
private Bitmap decodeFileDescriptorAsPurgeable( CloseableReference<PooledByteBuffer> bytesRef, int inputLength, byte[] suffix, BitmapFactory.Options options) { MemoryFile memoryFile = null; try { memoryFile = copyToMemoryFile(bytesRef, inputLength, suffix); FileDescriptor fd = getMemoryFileDescriptor(memoryFile); if (mWebpBitmapFactory != null) { Bitmap bitmap = mWebpBitmapFactory.decodeFileDescriptor(fd, null, options); return Preconditions.checkNotNull(bitmap, "BitmapFactory returned null"); } else { throw new IllegalStateException("WebpBitmapFactory is null"); } } catch (IOException e) { throw Throwables.propagate(e); } finally { if (memoryFile != null) { memoryFile.close(); } } }
Example #8
Source File: Bucket.java From fresco with MIT License | 6 votes |
/** * Releases a value to this bucket and decrements the inUse count * * @param value the value to release */ public void release(V value) { Preconditions.checkNotNull(value); if (mFixBucketsReinitialization) { // Proper way Preconditions.checkState(mInUseLength > 0); mInUseLength--; addToFreeList(value); } else { // Keep using previous adhoc if (mInUseLength > 0) { mInUseLength--; addToFreeList(value); } else { FLog.e(TAG, "Tried to release value %s from an empty bucket!", value); } } }
Example #9
Source File: ImageFormatChecker.java From FanXin-based-HuanXin with GNU General Public License v2.0 | 6 votes |
/** * Reads up to MAX_HEADER_LENGTH bytes from is InputStream. If mark is supported by is, it is * used to restore content of the stream after appropriate amount of data is read. * Read bytes are stored in imageHeaderBytes, which should be capable of storing * MAX_HEADER_LENGTH bytes. * @param is * @param imageHeaderBytes * @return number of bytes read from is * @throws IOException */ private static int readHeaderFromStream( final InputStream is, final byte[] imageHeaderBytes) throws IOException { Preconditions.checkNotNull(is); Preconditions.checkNotNull(imageHeaderBytes); Preconditions.checkArgument(imageHeaderBytes.length >= MAX_HEADER_LENGTH); // If mark is supported by the stream, use it to let the owner of the stream re-read the same // data. Otherwise, just consume some data. if (is.markSupported()) { try { is.mark(MAX_HEADER_LENGTH); return ByteStreams.read(is, imageHeaderBytes, 0, MAX_HEADER_LENGTH); } finally { is.reset(); } } else { return ByteStreams.read(is, imageHeaderBytes, 0, MAX_HEADER_LENGTH); } }
Example #10
Source File: AshmemMemoryChunk.java From fresco with MIT License | 6 votes |
/** * This does actual copy. It should be called only when we hold locks on both this and other * objects */ private void doCopy( final int offset, final MemoryChunk other, final int otherOffset, final int count) { if (!(other instanceof AshmemMemoryChunk)) { throw new IllegalArgumentException("Cannot copy two incompatible MemoryChunks"); } Preconditions.checkState(!isClosed()); Preconditions.checkState(!other.isClosed()); MemoryChunkUtil.checkBounds(offset, other.getSize(), otherOffset, count, getSize()); mByteBuffer.position(offset); // ByteBuffer can't be null at this point other.getByteBuffer().position(otherOffset); // Recover the necessary part to be copied as a byte array. // This requires a copy, for now there is not a more efficient alternative. byte[] b = new byte[count]; mByteBuffer.get(b, 0, count); other.getByteBuffer().put(b, 0, count); }
Example #11
Source File: StreamUtil.java From fresco with MIT License | 6 votes |
/** * Skips exactly bytesCount bytes in inputStream unless end of stream is reached first. * * @param inputStream input stream to skip bytes from * @param bytesCount number of bytes to skip * @return number of skipped bytes * @throws IOException */ public static long skip(final InputStream inputStream, final long bytesCount) throws IOException { Preconditions.checkNotNull(inputStream); Preconditions.checkArgument(bytesCount >= 0); long toSkip = bytesCount; while (toSkip > 0) { final long skipped = inputStream.skip(toSkip); if (skipped > 0) { toSkip -= skipped; continue; } if (inputStream.read() != -1) { toSkip--; continue; } return bytesCount - toSkip; } return bytesCount; }
Example #12
Source File: AbstractDraweeController.java From FanXin-based-HuanXin with GNU General Public License v2.0 | 6 votes |
@Override public void onAttach() { if (FLog.isLoggable(FLog.VERBOSE)) { FLog.v( TAG, "controller %x %s: onAttach: %s", System.identityHashCode(this), mId, mIsRequestSubmitted ? "request already submitted" : "request needs submit"); } mEventTracker.recordEvent(Event.ON_ATTACH_CONTROLLER); Preconditions.checkNotNull(mSettableDraweeHierarchy); mDeferredReleaser.cancelDeferredRelease(this); mIsAttached = true; if (!mIsRequestSubmitted) { submitRequest(); } }
Example #13
Source File: RoundedColorDrawable.java From fresco with MIT License | 5 votes |
/** * Sets the rounding radii. * * @param radii Each corner receive two radius values [X, Y]. The corners are ordered top-left, * top-right, bottom-right, bottom-left */ @Override public void setRadii(float[] radii) { if (radii == null) { Arrays.fill(mRadii, 0); } else { Preconditions.checkArgument(radii.length == 8, "radii should have exactly 8 values"); System.arraycopy(radii, 0, mRadii, 0, 8); } updatePath(); invalidateSelf(); }
Example #14
Source File: PooledByteArrayBufferedInputStream.java From FanXin-based-HuanXin with GNU General Public License v2.0 | 5 votes |
public PooledByteArrayBufferedInputStream( InputStream inputStream, byte[] byteArray, ResourceReleaser<byte[]> resourceReleaser) { mInputStream = Preconditions.checkNotNull(inputStream); mByteArray = Preconditions.checkNotNull(byteArray); mResourceReleaser = Preconditions.checkNotNull(resourceReleaser); mBufferedSize = 0; mBufferOffset = 0; mClosed = false; }
Example #15
Source File: NativePooledByteBufferFactory.java From FanXin-based-HuanXin with GNU General Public License v2.0 | 5 votes |
@Override public NativePooledByteBuffer newByteBuffer(int size) { Preconditions.checkArgument(size > 0); CloseableReference<NativeMemoryChunk> chunkRef = CloseableReference.of(mPool.get(size), mPool); try { return new NativePooledByteBuffer(chunkRef, size); } finally { chunkRef.close(); } }
Example #16
Source File: CloseableReference.java From fresco with MIT License | 5 votes |
protected CloseableReference( SharedReference<T> sharedReference, LeakHandler leakHandler, @Nullable Throwable stacktrace) { mSharedReference = Preconditions.checkNotNull(sharedReference); sharedReference.addReference(); mLeakHandler = leakHandler; mStacktrace = stacktrace; }
Example #17
Source File: NativePooledByteBufferOutputStream.java From FanXin-based-HuanXin with GNU General Public License v2.0 | 5 votes |
/** * Construct a new instance of this output stream with this initial capacity * It is not an error to have this initial capacity be inaccurate. If the actual contents * end up being larger than the initialCapacity, then we will reallocate memory * if needed. If the actual contents are smaller, then we'll end up wasting some memory * @param pool the pool to use * @param initialCapacity initial capacity to allocate for this stream */ public NativePooledByteBufferOutputStream(NativeMemoryChunkPool pool, int initialCapacity) { super(); Preconditions.checkArgument(initialCapacity > 0); mPool = Preconditions.checkNotNull(pool); mCount = 0; mBufRef = CloseableReference.of(mPool.get(initialCapacity), mPool); }
Example #18
Source File: CloseableStaticBitmap.java From FanXin-based-HuanXin with GNU General Public License v2.0 | 5 votes |
/** * Creates a new instance of a CloseableStaticBitmap from an existing CloseableReference. The * CloseableStaticBitmap will hold a reference to the Bitmap until it's closed. * * @param bitmapReference the bitmap reference. */ public CloseableStaticBitmap( CloseableReference<Bitmap> bitmapReference, QualityInfo qualityInfo) { mBitmapReference = Preconditions.checkNotNull(bitmapReference.cloneOrNull()); mBitmap = mBitmapReference.get(); mQualityInfo = qualityInfo; }
Example #19
Source File: DefaultImageFormatChecker.java From fresco with MIT License | 5 votes |
/** * Tries to match imageHeaderByte and headerSize against every known image format. If any match * succeeds, corresponding ImageFormat is returned. * * @param headerBytes the header bytes to check * @param headerSize the available header size * @return ImageFormat for given imageHeaderBytes or UNKNOWN if no such type could be recognized */ @Nullable @Override public final ImageFormat determineFormat(byte[] headerBytes, int headerSize) { Preconditions.checkNotNull(headerBytes); if (WebpSupportStatus.isWebpHeader(headerBytes, 0, headerSize)) { return getWebpFormat(headerBytes, headerSize); } if (isJpegHeader(headerBytes, headerSize)) { return DefaultImageFormats.JPEG; } if (isPngHeader(headerBytes, headerSize)) { return DefaultImageFormats.PNG; } if (isGifHeader(headerBytes, headerSize)) { return DefaultImageFormats.GIF; } if (isBmpHeader(headerBytes, headerSize)) { return DefaultImageFormats.BMP; } if (isIcoHeader(headerBytes, headerSize)) { return DefaultImageFormats.ICO; } if (isHeifHeader(headerBytes, headerSize)) { return DefaultImageFormats.HEIF; } if (isDngHeader(headerBytes, headerSize)) { return DefaultImageFormats.DNG; } return ImageFormat.UNKNOWN; }
Example #20
Source File: ResizeAndRotateProducer.java From fresco with MIT License | 5 votes |
@Override protected void onNewResultImpl(@Nullable EncodedImage newResult, @Status int status) { if (mIsCancelled) { return; } boolean isLast = isLast(status); if (newResult == null) { if (isLast) { getConsumer().onNewResult(null, Consumer.IS_LAST); } return; } ImageFormat imageFormat = newResult.getImageFormat(); TriState shouldTransform = shouldTransform( mProducerContext.getImageRequest(), newResult, Preconditions.checkNotNull( mImageTranscoderFactory.createImageTranscoder(imageFormat, mIsResizingEnabled))); // ignore the intermediate result if we don't know what to do with it if (!isLast && shouldTransform == TriState.UNSET) { return; } // just forward the result if we know that it shouldn't be transformed if (shouldTransform != TriState.YES) { forwardNewResult(newResult, status, imageFormat); return; } // we know that the result should be transformed, hence schedule it if (!mJobScheduler.updateJob(newResult, status)) { return; } if (isLast || mProducerContext.isIntermediateResultExpected()) { mJobScheduler.scheduleJob(); } }
Example #21
Source File: PostprocessorProducer.java From fresco with MIT License | 5 votes |
public PostprocessorProducer( Producer<CloseableReference<CloseableImage>> inputProducer, PlatformBitmapFactory platformBitmapFactory, Executor executor) { mInputProducer = Preconditions.checkNotNull(inputProducer); mBitmapFactory = platformBitmapFactory; mExecutor = Preconditions.checkNotNull(executor); }
Example #22
Source File: PooledByteBufferInputStream.java From fresco with MIT License | 5 votes |
/** * Creates a new inputstream instance over the specific buffer. * * @param pooledByteBuffer the buffer to read from */ public PooledByteBufferInputStream(PooledByteBuffer pooledByteBuffer) { super(); Preconditions.checkArgument(!pooledByteBuffer.isClosed()); mPooledByteBuffer = Preconditions.checkNotNull(pooledByteBuffer); mOffset = 0; mMark = 0; }
Example #23
Source File: PooledByteArrayBufferedInputStream.java From FanXin-based-HuanXin with GNU General Public License v2.0 | 5 votes |
@Override public int read(byte[] buffer, int offset, int length) throws IOException { Preconditions.checkState(mBufferOffset <= mBufferedSize); ensureNotClosed(); if (!ensureDataInBuffer()) { return -1; } final int bytesToRead = Math.min(mBufferedSize - mBufferOffset, length); System.arraycopy(mByteArray, mBufferOffset, buffer, offset, bytesToRead); mBufferOffset += bytesToRead; return bytesToRead; }
Example #24
Source File: PooledByteArrayBufferedInputStream.java From FanXin-based-HuanXin with GNU General Public License v2.0 | 5 votes |
@Override public int read() throws IOException { Preconditions.checkState(mBufferOffset <= mBufferedSize); ensureNotClosed(); if (!ensureDataInBuffer()) { return -1; } return mByteArray[mBufferOffset++] & 0xFF; }
Example #25
Source File: RenderScriptBlurFilter.java From fresco with MIT License | 5 votes |
/** * Not-in-place intrinsic Gaussian blur filter using {@link ScriptIntrinsicBlur} and {@link * RenderScript}. This require an Android versions >= 4.2. * * @param dest The {@link Bitmap} where the blurred image is written to. * @param src The {@link Bitmap} containing the original image. * @param context The {@link Context} necessary to use {@link RenderScript} * @param radius The radius of the blur with a supported range 0 < radius <= {@link * #BLUR_MAX_RADIUS} */ @RequiresApi(Build.VERSION_CODES.JELLY_BEAN_MR1) public static void blurBitmap( final Bitmap dest, final Bitmap src, final Context context, final int radius) { Preconditions.checkNotNull(dest); Preconditions.checkNotNull(src); Preconditions.checkNotNull(context); Preconditions.checkArgument(radius > 0 && radius <= BLUR_MAX_RADIUS); RenderScript rs = null; try { rs = RenderScript.create(context); // Create an Intrinsic Blur Script using the Renderscript ScriptIntrinsicBlur blurScript = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs)); // Create the input/output allocations with Renderscript and the src/dest bitmaps Allocation allIn = Allocation.createFromBitmap(rs, src); Allocation allOut = Allocation.createFromBitmap(rs, dest); // Set the radius of the blur blurScript.setRadius(radius); blurScript.setInput(allIn); blurScript.forEach(allOut); allOut.copyTo(dest); blurScript.destroy(); allIn.destroy(); allOut.destroy(); } finally { if (rs != null) { rs.destroy(); } } }
Example #26
Source File: MultiDraweeHolder.java From FanXin-based-HuanXin with GNU General Public License v2.0 | 5 votes |
public void add(int index, DraweeHolder<DH> holder) { Preconditions.checkNotNull(holder); Preconditions.checkElementIndex(index, mHolders.size() + 1); mHolders.add(index, holder); if (mIsAttached) { holder.onAttach(); } }
Example #27
Source File: ArrayDrawable.java From FanXin-based-HuanXin with GNU General Public License v2.0 | 5 votes |
/** * Constructs a new layer drawable. * @param layers the layers that this drawable displays */ public ArrayDrawable(Drawable[] layers) { Preconditions.checkNotNull(layers); mLayers = layers; for (int i = 0; i < mLayers.length; i++) { DrawableUtils.setCallbacks(mLayers[i], this, this); } }
Example #28
Source File: NativeMemoryChunk.java From FanXin-based-HuanXin with GNU General Public License v2.0 | 5 votes |
/** * Copy bytes from native memory to byte array. * @param nativeMemoryOffset number of first byte to copy * @param byteArray byte array to copy to * @param byteArrayOffset number of first byte in byte array to be written * @param count number of bytes to copy * @return number of bytes read */ public synchronized int read( final int nativeMemoryOffset, final byte[] byteArray, final int byteArrayOffset, final int count) { Preconditions.checkNotNull(byteArray); Preconditions.checkState(!isClosed()); final int actualCount = adjustByteCount(nativeMemoryOffset, count); checkBounds(nativeMemoryOffset, byteArray.length, byteArrayOffset, actualCount); nativeCopyToByteArray(mNativePtr + nativeMemoryOffset, byteArray, byteArrayOffset, actualCount); return actualCount; }
Example #29
Source File: CountingMemoryCache.java From FanXin-based-HuanXin with GNU General Public License v2.0 | 5 votes |
/** * Caches given key value pair. After this method returns, caller should use returned instance * of CloseableReference, which depending on implementation might or might not be the same as * the one provided by caller. Caller is responsible for calling release method to notify * cache that cached value won't be used anymore. This allows the cache to maintain value's * in-use count. */ public CloseableReference<V> cache(final K key, final CloseableReference<V> value) { Preconditions.checkNotNull(key); Preconditions.checkNotNull(value); maybeUpdateCacheParams(); /** * We might be required to remove old entry associated with the same key. */ CloseableReference<V> removedValue = null; CacheEntry<K, V> newCacheEntry = null; synchronized (this) { if (!canCacheNewValue(value)) { return null; } newCacheEntry = CacheEntry.of(key, value.clone()); removedValue = handleIndexRegistration(key, newCacheEntry.value); putInCachedEntries(newCacheEntry); increaseUsageCount(newCacheEntry); } if (removedValue != null) { removedValue.close(); } maybeEvictEntries(); return newCacheEntry.value; }
Example #30
Source File: ArrayDrawable.java From fresco with MIT License | 5 votes |
/** Gets the {@code DrawableParent} for index. */ public DrawableParent getDrawableParentForIndex(int index) { Preconditions.checkArgument(index >= 0); Preconditions.checkArgument(index < mDrawableParents.length); if (mDrawableParents[index] == null) { mDrawableParents[index] = createDrawableParentForIndex(index); } return mDrawableParents[index]; }