001/**
002 *
003 * Copyright © 2014 Florian Schmaus
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 *     http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.jivesoftware.smack.sm;
018
019import java.math.BigInteger;
020
021public class SMUtils {
022
023    private static long MASK_32_BIT = BigInteger.ONE.shiftLeft(32).subtract(BigInteger.ONE).longValue();
024
025    /**
026     * Increment the Stream Management height counter.
027     *
028     * Quoting XEP-198 4.:
029     * "In the unlikely case that the number of stanzas handled during a stream management session exceeds the number
030     * of digits that can be represented by the unsignedInt datatype as specified in XML Schema Part 2 [10]
031     * (i.e., 2^32), the value of 'h' SHALL be reset from 2^32-1 back to zero (rather than being incremented to 2^32)."
032     *
033     * @param height TODO javadoc me please
034     * @return the incremented height
035     */
036    public static long incrementHeight(long height) {
037        return ++height & MASK_32_BIT;
038    }
039
040    /**
041     * Calculates the delta of the last known stanza handled count and the new
042     * reported stanza handled count while considering that the new value may be
043     * wrapped after 2^32-1.
044     *
045     * @param reportedHandledCount TODO javadoc me please
046     * @param lastKnownHandledCount TODO javadoc me please
047     * @return the delta
048     */
049    public static long calculateDelta(long reportedHandledCount, long lastKnownHandledCount) {
050        if (lastKnownHandledCount > reportedHandledCount) {
051            throw new IllegalStateException("Illegal Stream Management State: Last known handled count (" + lastKnownHandledCount + ") is greater than reported handled count (" + reportedHandledCount + ')');
052        }
053        return (reportedHandledCount - lastKnownHandledCount) & MASK_32_BIT;
054    }
055}