idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
150,700
public final static String process ( final File file , final boolean safeMode ) throws IOException { return process ( file , Configuration . builder ( ) . setSafeMode ( safeMode ) . build ( ) ) ; }
Transforms an input file into HTML .
44
8
150,701
public static void main ( final String [ ] args ) throws IOException { // This is just a _hack_ ... BufferedReader reader = null ; if ( args . length == 0 ) { System . err . println ( "No input file specified." ) ; System . exit ( - 1 ) ; } if ( args . length > 1 ) { reader = new BufferedReader ( new InputStreamReader ( new FileInputStream ( args [ 1 ] ) , "UTF-8" ) ) ; String line = reader . readLine ( ) ; while ( line != null && ! line . startsWith ( "<!-- ###" ) ) { System . out . println ( line ) ; line = reader . readLine ( ) ; } } System . out . println ( Processor . process ( new File ( args [ 0 ] ) ) ) ; if ( args . length > 1 && reader != null ) { String line = reader . readLine ( ) ; while ( line != null ) { System . out . println ( line ) ; line = reader . readLine ( ) ; } reader . close ( ) ; } }
Static main .
230
3
150,702
public static List < String > parse ( final String [ ] args , final Object ... objs ) throws IOException { final List < String > ret = Colls . list ( ) ; final List < Arg > allArgs = Colls . list ( ) ; final HashMap < String , Arg > shortArgs = new HashMap < String , Arg > ( ) ; final HashMap < String , Arg > longArgs = new HashMap < String , Arg > ( ) ; parseArgs ( objs , allArgs , shortArgs , longArgs ) ; for ( int i = 0 ; i < args . length ; i ++ ) { final String s = args [ i ] ; final Arg a ; if ( s . startsWith ( "--" ) ) { a = longArgs . get ( s . substring ( 2 ) ) ; if ( a == null ) { throw new IOException ( "Unknown switch: " + s ) ; } } else if ( s . startsWith ( "-" ) ) { a = shortArgs . get ( s . substring ( 1 ) ) ; if ( a == null ) { throw new IOException ( "Unknown switch: " + s ) ; } } else { a = null ; ret . add ( s ) ; } if ( a != null ) { if ( a . isSwitch ) { a . setField ( "true" ) ; } else { if ( i + 1 >= args . length ) { System . out . println ( "Missing parameter for: " + s ) ; } if ( a . isCatchAll ( ) ) { final List < String > ca = Colls . list ( ) ; for ( ++ i ; i < args . length ; ++ i ) { ca . add ( args [ i ] ) ; } a . setCatchAll ( ca ) ; } else { ++ i ; a . setField ( args [ i ] ) ; } } a . setPresent ( ) ; } } for ( final Arg a : allArgs ) { if ( ! a . isOk ( ) ) { throw new IOException ( "Missing mandatory argument: " + a ) ; } } return ret ; }
Parses command line arguments .
449
7
150,703
public final static int readUntil ( final StringBuilder out , final String in , final int start , final char end ) { int pos = start ; while ( pos < in . length ( ) ) { final char ch = in . charAt ( pos ) ; if ( ch == ' ' && pos + 1 < in . length ( ) ) { pos = escape ( out , in . charAt ( pos + 1 ) , pos ) ; } else { if ( ch == end ) { break ; } out . append ( ch ) ; } pos ++ ; } return ( pos == in . length ( ) ) ? - 1 : pos ; }
Reads characters until the end character is encountered .
132
10
150,704
public final static int readMdLink ( final StringBuilder out , final String in , final int start ) { int pos = start ; int counter = 1 ; while ( pos < in . length ( ) ) { final char ch = in . charAt ( pos ) ; if ( ch == ' ' && pos + 1 < in . length ( ) ) { pos = escape ( out , in . charAt ( pos + 1 ) , pos ) ; } else { boolean endReached = false ; switch ( ch ) { case ' ' : counter ++ ; break ; case ' ' : if ( counter == 1 ) { endReached = true ; } break ; case ' ' : counter -- ; if ( counter == 0 ) { endReached = true ; } break ; } if ( endReached ) { break ; } out . append ( ch ) ; } pos ++ ; } return ( pos == in . length ( ) ) ? - 1 : pos ; }
Reads a markdown link .
200
7
150,705
public final static int readMdLinkId ( final StringBuilder out , final String in , final int start ) { int pos = start ; int counter = 1 ; while ( pos < in . length ( ) ) { final char ch = in . charAt ( pos ) ; boolean endReached = false ; switch ( ch ) { case ' ' : out . append ( ' ' ) ; break ; case ' ' : counter ++ ; out . append ( ch ) ; break ; case ' ' : counter -- ; if ( counter == 0 ) { endReached = true ; } else { out . append ( ch ) ; } break ; default : out . append ( ch ) ; break ; } if ( endReached ) { break ; } pos ++ ; } return ( pos == in . length ( ) ) ? - 1 : pos ; }
Reads a markdown link ID .
175
8
150,706
public final static int readXMLUntil ( final StringBuilder out , final String in , final int start , final char ... end ) { int pos = start ; boolean inString = false ; char stringChar = 0 ; while ( pos < in . length ( ) ) { final char ch = in . charAt ( pos ) ; if ( inString ) { if ( ch == ' ' ) { out . append ( ch ) ; pos ++ ; if ( pos < in . length ( ) ) { out . append ( ch ) ; pos ++ ; } continue ; } if ( ch == stringChar ) { inString = false ; out . append ( ch ) ; pos ++ ; continue ; } } switch ( ch ) { case ' ' : case ' ' : inString = true ; stringChar = ch ; break ; } if ( ! inString ) { boolean endReached = false ; for ( int n = 0 ; n < end . length ; n ++ ) { if ( ch == end [ n ] ) { endReached = true ; break ; } } if ( endReached ) { break ; } } out . append ( ch ) ; pos ++ ; } return ( pos == in . length ( ) ) ? - 1 : pos ; }
Reads characters until any end character is encountered ignoring escape sequences .
260
13
150,707
public final static void appendCode ( final StringBuilder out , final String in , final int start , final int end ) { for ( int i = start ; i < end ; i ++ ) { final char c ; switch ( c = in . charAt ( i ) ) { case ' ' : out . append ( "&amp;" ) ; break ; case ' ' : out . append ( "&lt;" ) ; break ; case ' ' : out . append ( "&gt;" ) ; break ; default : out . append ( c ) ; break ; } } }
Appends the given string encoding special HTML characters .
119
10
150,708
public final static void appendDecEntity ( final StringBuilder out , final char value ) { out . append ( "&#" ) ; out . append ( ( int ) value ) ; out . append ( ' ' ) ; }
Append the given char as a decimal HTML entity .
47
11
150,709
public final static void codeEncode ( final StringBuilder out , final String value , final int offset ) { for ( int i = offset ; i < value . length ( ) ; i ++ ) { final char c = value . charAt ( i ) ; switch ( c ) { case ' ' : out . append ( "&amp;" ) ; break ; case ' ' : out . append ( "&lt;" ) ; break ; case ' ' : out . append ( "&gt;" ) ; break ; default : out . append ( c ) ; } } }
Appends the given string to the given StringBuilder replacing &amp ; &lt ; and &gt ; by their respective HTML entities .
118
27
150,710
private int countCharsStart ( final char ch , final boolean allowSpaces ) { int count = 0 ; for ( int i = 0 ; i < this . value . length ( ) ; i ++ ) { final char c = this . value . charAt ( i ) ; if ( c == ' ' && allowSpaces ) { continue ; } if ( c == ch ) { count ++ ; } else { break ; } } return count ; }
Counts the amount of ch at the start of this line optionally ignoring spaces .
94
16
150,711
public SimplifySpanBuild append ( String text ) { if ( TextUtils . isEmpty ( text ) ) return this ; mNormalSizeText . append ( text ) ; mStringBuilder . append ( text ) ; return this ; }
append normal text
50
3
150,712
public SimplifySpanBuild appendMultiClickable ( SpecialClickableUnit specialClickableUnit , Object ... specialUnitOrStrings ) { processMultiClickableSpecialUnit ( false , specialClickableUnit , specialUnitOrStrings ) ; return this ; }
append multi clickable SpecialUnit or String
54
8
150,713
@ Override public void Invoke ( final String method , JSONArray args , HubInvokeCallback callback ) { if ( method == null ) { throw new IllegalArgumentException ( "method" ) ; } if ( args == null ) { throw new IllegalArgumentException ( "args" ) ; } final String callbackId = mConnection . RegisterCallback ( callback ) ; HubInvocation hubData = new HubInvocation ( mHubName , method , args , callbackId ) ; String value = hubData . Serialize ( ) ; mConnection . Send ( value , new SendCallback ( ) { @ Override public void OnSent ( CharSequence messageSent ) { Log . v ( TAG , "Invoke of " + method + "sent to " + mHubName ) ; // callback.OnSent() ??!?!? } @ Override public void OnError ( Exception ex ) { // TODO Cancel the callback Log . e ( TAG , "Failed to invoke " + method + "on " + mHubName ) ; mConnection . RemoveCallback ( callbackId ) ; // callback.OnError() ?!?!? } } ) ; }
Executes a method on the server asynchronously
241
10
150,714
@ IntRange ( from = 0 , to = OPAQUE ) private static int resolveLineAlpha ( @ IntRange ( from = 0 , to = OPAQUE ) final int sceneAlpha , final float maxDistance , final float distance ) { final float alphaPercent = 1f - distance / maxDistance ; final int alpha = ( int ) ( ( float ) OPAQUE * alphaPercent ) ; return alpha * sceneAlpha / OPAQUE ; }
Resolves line alpha based on distance comparing to max distance . Where alpha is close to 0 for maxDistance and close to 1 to 0 distance .
97
29
150,715
void applyFreshParticleOnScreen ( @ NonNull final Scene scene , final int position ) { final int w = scene . getWidth ( ) ; final int h = scene . getHeight ( ) ; if ( w == 0 || h == 0 ) { throw new IllegalStateException ( "Cannot generate particles if scene width or height is 0" ) ; } final double direction = Math . toRadians ( random . nextInt ( 360 ) ) ; final float dCos = ( float ) Math . cos ( direction ) ; final float dSin = ( float ) Math . sin ( direction ) ; final float x = random . nextInt ( w ) ; final float y = random . nextInt ( h ) ; final float speedFactor = newRandomIndividualParticleSpeedFactor ( ) ; final float radius = newRandomIndividualParticleRadius ( scene ) ; scene . setParticleData ( position , x , y , dCos , dSin , radius , speedFactor ) ; }
Set new point coordinates somewhere on screen and apply new direction
204
11
150,716
void applyFreshParticleOffScreen ( @ NonNull final Scene scene , final int position ) { final int w = scene . getWidth ( ) ; final int h = scene . getHeight ( ) ; if ( w == 0 || h == 0 ) { throw new IllegalStateException ( "Cannot generate particles if scene width or height is 0" ) ; } float x = random . nextInt ( w ) ; float y = random . nextInt ( h ) ; // The offset to make when creating point of out bounds final short offset = ( short ) ( scene . getParticleRadiusMin ( ) + scene . getLineLength ( ) ) ; // Point angle range final float startAngle ; float endAngle ; // Make random offset and calulate angles so that the direction of travel will always be // towards our View switch ( random . nextInt ( 4 ) ) { case 0 : // offset to left x = ( short ) - offset ; startAngle = angleDeg ( pcc , pcc , x , y ) ; endAngle = angleDeg ( pcc , h - pcc , x , y ) ; break ; case 1 : // offset to top y = ( short ) - offset ; startAngle = angleDeg ( w - pcc , pcc , x , y ) ; endAngle = angleDeg ( pcc , pcc , x , y ) ; break ; case 2 : // offset to right x = ( short ) ( w + offset ) ; startAngle = angleDeg ( w - pcc , h - pcc , x , y ) ; endAngle = angleDeg ( w - pcc , pcc , x , y ) ; break ; case 3 : // offset to bottom y = ( short ) ( h + offset ) ; startAngle = angleDeg ( pcc , h - pcc , x , y ) ; endAngle = angleDeg ( w - pcc , h - pcc , x , y ) ; break ; default : throw new IllegalArgumentException ( "Supplied value out of range" ) ; } if ( endAngle < startAngle ) { endAngle += 360 ; } // Get random angle from angle range final float randomAngleInRange = startAngle + ( random . nextInt ( ( int ) Math . abs ( endAngle - startAngle ) ) ) ; final double direction = Math . toRadians ( randomAngleInRange ) ; final float dCos = ( float ) Math . cos ( direction ) ; final float dSin = ( float ) Math . sin ( direction ) ; final float speedFactor = newRandomIndividualParticleSpeedFactor ( ) ; final float radius = newRandomIndividualParticleRadius ( scene ) ; scene . setParticleData ( position , x , y , dCos , dSin , radius , speedFactor ) ; }
Set new particle coordinates somewhere off screen and apply new direction towards the screen
609
14
150,717
private static float angleDeg ( final float ax , final float ay , final float bx , final float by ) { final double angleRad = Math . atan2 ( ay - by , ax - bx ) ; double angle = Math . toDegrees ( angleRad ) ; if ( angleRad < 0 ) { angle += 360 ; } return ( float ) angle ; }
Returns angle in degrees between two points
80
7
150,718
private float newRandomIndividualParticleRadius ( @ NonNull final SceneConfiguration scene ) { return scene . getParticleRadiusMin ( ) == scene . getParticleRadiusMax ( ) ? scene . getParticleRadiusMin ( ) : scene . getParticleRadiusMin ( ) + ( random . nextInt ( ( int ) ( ( scene . getParticleRadiusMax ( ) - scene . getParticleRadiusMin ( ) ) * 100f ) ) ) / 100f ; }
Generates new individual particle radius based on min and max radius setting .
108
14
150,719
public static float distance ( final float ax , final float ay , final float bx , final float by ) { return ( float ) Math . sqrt ( ( ax - bx ) * ( ax - bx ) + ( ay - by ) * ( ay - by ) ) ; }
Calculates the distance between two points
60
8
150,720
public Credentials toGrgit ( ) { if ( username != null && password != null ) { return new Credentials ( username , password ) ; } else { return null ; } }
Converts to credentials for use in Grgit .
40
10
150,721
@ OnClick ( R . id . navigateToSampleActivity ) public void onSampleActivityCTAClick ( ) { StringParcel parcel1 = new StringParcel ( "Andy" ) ; StringParcel parcel2 = new StringParcel ( "Tony" ) ; List < StringParcel > parcelList = new ArrayList <> ( ) ; parcelList . add ( parcel1 ) ; parcelList . add ( parcel2 ) ; SparseArray < StringParcel > parcelSparseArray = new SparseArray <> ( ) ; parcelSparseArray . put ( 0 , parcel1 ) ; parcelSparseArray . put ( 2 , parcel2 ) ; Intent intent = HensonNavigator . gotoSampleActivity ( this ) . defaultKeyExtra ( "defaultKeyExtra" ) . extraInt ( 4 ) . extraListParcelable ( parcelList ) . extraParcel ( parcel1 ) . extraParcelable ( ComplexParcelable . random ( ) ) . extraSparseArrayParcelable ( parcelSparseArray ) . extraString ( "a string" ) . build ( ) ; startActivity ( intent ) ; }
Launch Sample Activity residing in the same module
240
8
150,722
@ OnClick ( R . id . navigateToModule1Service ) public void onNavigationServiceCTAClick ( ) { Intent intentService = HensonNavigator . gotoModule1Service ( this ) . stringExtra ( "foo" ) . build ( ) ; startService ( intentService ) ; }
Launch Navigation Service residing in the navigation module
64
8
150,723
public static boolean isValidFqcn ( String str ) { if ( isNullOrEmpty ( str ) ) { return false ; } final String [ ] parts = str . split ( "\\." ) ; if ( parts . length < 2 ) { return false ; } for ( String part : parts ) { if ( ! isValidJavaIdentifier ( part ) ) { return false ; } } return true ; }
Returns true if the string is a valid Java full qualified class name .
86
14
150,724
public TaskProvider < GenerateHensonNavigatorTask > createHensonNavigatorGenerationTask ( BaseVariant variant , String hensonNavigatorPackageName , File destinationFolder ) { TaskProvider < GenerateHensonNavigatorTask > generateHensonNavigatorTask = project . getTasks ( ) . register ( "generate" + capitalize ( variant . getName ( ) ) + "HensonNavigator" , GenerateHensonNavigatorTask . class , ( Action < GenerateHensonNavigatorTask > ) generateHensonNavigatorTask1 -> { generateHensonNavigatorTask1 . hensonNavigatorPackageName = hensonNavigatorPackageName ; generateHensonNavigatorTask1 . destinationFolder = destinationFolder ; generateHensonNavigatorTask1 . variant = variant ; generateHensonNavigatorTask1 . logger = logger ; generateHensonNavigatorTask1 . project = project ; generateHensonNavigatorTask1 . hensonNavigatorGenerator = hensonNavigatorGenerator ; } ) ; return generateHensonNavigatorTask ; }
A henson navigator is a class that helps a consumer to consume the navigation api that it declares in its dependencies . The henson navigator will wrap the intent builders . Thus a henson navigator is driven by consumption of intent builders whereas the henson classes are driven by the production of an intent builder .
226
63
150,725
public Bundler put ( String key , Bundle value ) { delegate . putBundle ( key , value ) ; return this ; }
Inserts a Bundle value into the mapping of the underlying Bundle replacing any existing value for the given key . Either key or value may be null .
27
29
150,726
public Bundler put ( String key , String value ) { delegate . putString ( key , value ) ; return this ; }
Inserts a String value into the mapping of the underlying Bundle replacing any existing value for the given key . Either key or value may be null .
26
29
150,727
public Bundler put ( String key , String [ ] value ) { delegate . putStringArray ( key , value ) ; return this ; }
Inserts a String array value into the mapping of the underlying Bundle replacing any existing value for the given key . Either key or value may be null .
29
30
150,728
public Bundler put ( String key , CharSequence value ) { delegate . putCharSequence ( key , value ) ; return this ; }
Inserts a CharSequence value into the mapping of the underlying Bundle replacing any existing value for the given key . Either key or value may be null .
30
31
150,729
public Bundler put ( String key , CharSequence [ ] value ) { delegate . putCharSequenceArray ( key , value ) ; return this ; }
Inserts a CharSequence array value into the mapping of the underlying Bundle replacing any existing value for the given key . Either key or value may be null .
33
32
150,730
public Bundler put ( String key , Parcelable value ) { delegate . putParcelable ( key , value ) ; return this ; }
Inserts a Parcelable value into the mapping of the underlying Bundle replacing any existing value for the given key . Either key or value may be null .
30
31
150,731
public Bundler put ( String key , Parcelable [ ] value ) { delegate . putParcelableArray ( key , value ) ; return this ; }
Inserts an array of Parcelable values into the mapping of the underlying Bundle replacing any existing value for the given key . Either key or value may be null .
33
33
150,732
public Bundler put ( String key , Serializable value ) { delegate . putSerializable ( key , value ) ; return this ; }
Inserts a Serializable value into the mapping of the underlying Bundle replacing any existing value for the given key . Either key or value may be null .
28
30
150,733
@ Override public void validate ( ) throws HostNameException { if ( parsedHost != null ) { return ; } if ( validationException != null ) { throw validationException ; } synchronized ( this ) { if ( parsedHost != null ) { return ; } if ( validationException != null ) { throw validationException ; } try { parsedHost = getValidator ( ) . validateHost ( this ) ; } catch ( HostNameException e ) { validationException = e ; throw e ; } } }
Validates that this string is a valid host name or IP address and if not throws an exception with a descriptive message indicating why it is not .
103
29
150,734
public boolean isValid ( ) { if ( parsedHost != null ) { return true ; } if ( validationException != null ) { return false ; } try { validate ( ) ; return true ; } catch ( HostNameException e ) { return false ; } }
Returns whether this represents a valid host name or address format .
54
12
150,735
@ Override public String toNormalizedString ( ) { String result = normalizedString ; if ( result == null ) { normalizedString = result = toNormalizedString ( false ) ; } return result ; }
Provides a normalized string which is lowercase for host strings and which is a normalized string for addresses .
43
21
150,736
public String [ ] getNormalizedLabels ( ) { if ( isValid ( ) ) { return parsedHost . getNormalizedLabels ( ) ; } if ( host . length ( ) == 0 ) { return new String [ 0 ] ; } return new String [ ] { host } ; }
Returns an array of normalized strings for this host name instance .
62
12
150,737
public boolean matches ( HostName host ) { if ( this == host ) { return true ; } if ( isValid ( ) ) { if ( host . isValid ( ) ) { if ( isAddressString ( ) ) { return host . isAddressString ( ) && asAddressString ( ) . equals ( host . asAddressString ( ) ) && Objects . equals ( getPort ( ) , host . getPort ( ) ) && Objects . equals ( getService ( ) , host . getService ( ) ) ; } if ( host . isAddressString ( ) ) { return false ; } String thisHost = parsedHost . getHost ( ) ; String otherHost = host . parsedHost . getHost ( ) ; if ( ! thisHost . equals ( otherHost ) ) { return false ; } return Objects . equals ( parsedHost . getEquivalentPrefixLength ( ) , host . parsedHost . getEquivalentPrefixLength ( ) ) && Objects . equals ( parsedHost . getMask ( ) , host . parsedHost . getMask ( ) ) && Objects . equals ( parsedHost . getPort ( ) , host . parsedHost . getPort ( ) ) && Objects . equals ( parsedHost . getService ( ) , host . parsedHost . getService ( ) ) ; } return false ; } return ! host . isValid ( ) && toString ( ) . equals ( host . toString ( ) ) ; }
Returns whether the given host matches this one . For hosts to match they must represent the same addresses or have the same host names . Hosts are not resolved when matching . Also hosts must have the same port and service . They must have the same masks if they are host names . Even if two hosts are invalid they match if they have the same invalid string .
297
72
150,738
@ Override public IPAddress toAddress ( ) throws UnknownHostException , HostNameException { IPAddress addr = resolvedAddress ; if ( addr == null && ! resolvedIsNull ) { //note that validation handles empty address resolution validate ( ) ; synchronized ( this ) { addr = resolvedAddress ; if ( addr == null && ! resolvedIsNull ) { if ( parsedHost . isAddressString ( ) ) { addr = parsedHost . asAddress ( ) ; resolvedIsNull = ( addr == null ) ; //note there is no need to apply prefix or mask here, it would have been applied to the address already } else { String strHost = parsedHost . getHost ( ) ; if ( strHost . length ( ) == 0 && ! validationOptions . emptyIsLoopback ) { addr = null ; resolvedIsNull = true ; } else { //Note we do not set resolvedIsNull, so we will attempt to resolve again if the previous attempt threw an exception InetAddress inetAddress = InetAddress . getByName ( strHost ) ; byte bytes [ ] = inetAddress . getAddress ( ) ; Integer networkPrefixLength = parsedHost . getNetworkPrefixLength ( ) ; if ( networkPrefixLength == null ) { IPAddress mask = parsedHost . getMask ( ) ; if ( mask != null ) { byte maskBytes [ ] = mask . getBytes ( ) ; if ( maskBytes . length != bytes . length ) { throw new HostNameException ( host , "ipaddress.error.ipMismatch" ) ; } for ( int i = 0 ; i < bytes . length ; i ++ ) { bytes [ i ] &= maskBytes [ i ] ; } networkPrefixLength = mask . getBlockMaskPrefixLength ( true ) ; } } IPAddressStringParameters addressParams = validationOptions . addressOptions ; if ( bytes . length == IPv6Address . BYTE_COUNT ) { IPv6AddressCreator creator = addressParams . getIPv6Parameters ( ) . getNetwork ( ) . getAddressCreator ( ) ; addr = creator . createAddressInternal ( bytes , networkPrefixLength , null , this ) ; /* address creation */ } else { IPv4AddressCreator creator = addressParams . getIPv4Parameters ( ) . getNetwork ( ) . getAddressCreator ( ) ; addr = creator . createAddressInternal ( bytes , networkPrefixLength , this ) ; /* address creation */ } } } resolvedAddress = addr ; } } } return addr ; }
If this represents an ip address returns that address . If this represents a host returns the resolved ip address of that host . Otherwise returns null but only for strings that are considered valid address strings but cannot be converted to address objects .
535
45
150,739
protected Iterator < MACAddress > iterator ( MACAddress original ) { MACAddressCreator creator = getAddressCreator ( ) ; boolean isSingle = ! isMultiple ( ) ; return iterator ( isSingle ? original : null , creator , //using a lambda for this one results in a big performance hit isSingle ? null : segmentsIterator ( ) , getNetwork ( ) . getPrefixConfiguration ( ) . allPrefixedAddressesAreSubnets ( ) ? null : getPrefixLength ( ) ) ; }
these are the iterators used by MACAddress
106
9
150,740
@ Override public String toHexString ( boolean with0xPrefix ) { String result ; if ( hasNoStringCache ( ) || ( result = ( with0xPrefix ? stringCache . hexStringPrefixed : stringCache . hexString ) ) == null ) { result = toHexString ( with0xPrefix , null ) ; if ( with0xPrefix ) { stringCache . hexStringPrefixed = result ; } else { stringCache . hexString = result ; } } return result ; }
Writes this address as a single hexadecimal value with always the exact same number of characters with or without a preceding 0x prefix .
111
29
150,741
@ Override public String toCompressedString ( ) { String result ; if ( hasNoStringCache ( ) || ( result = getStringCache ( ) . compressedString ) == null ) { getStringCache ( ) . compressedString = result = toNormalizedString ( MACStringCache . compressedParams ) ; } return result ; }
This produces a shorter string for the address that uses the canonical representation but not using leading zeroes .
70
21
150,742
public String toDottedString ( ) { String result = null ; if ( hasNoStringCache ( ) || ( result = getStringCache ( ) . dottedString ) == null ) { AddressDivisionGrouping dottedGrouping = getDottedGrouping ( ) ; getStringCache ( ) . dottedString = result = toNormalizedString ( MACStringCache . dottedParams , dottedGrouping ) ; } return result ; }
This produces the dotted hexadecimal format aaaa . bbbb . cccc
90
19
150,743
public < S extends AddressSegment > void getSplitSegments ( S segs [ ] , int index , AddressSegmentCreator < S > creator ) { if ( ! isMultiple ( ) ) { int bitSizeSplit = IPv6Address . BITS_PER_SEGMENT >>> 1 ; Integer myPrefix = getSegmentPrefixLength ( ) ; Integer highPrefixBits = getSplitSegmentPrefix ( bitSizeSplit , myPrefix , 0 ) ; Integer lowPrefixBits = getSplitSegmentPrefix ( bitSizeSplit , myPrefix , 1 ) ; if ( index >= 0 && index < segs . length ) { segs [ index ] = creator . createSegment ( highByte ( ) , highPrefixBits ) ; } if ( ++ index >= 0 && index < segs . length ) { segs [ index ] = creator . createSegment ( lowByte ( ) , lowPrefixBits ) ; } } else { getSplitSegmentsMultiple ( segs , index , creator ) ; } }
Converts this IPv6 address segment into smaller segments copying them into the given array starting at the given index .
225
22
150,744
@ Override public boolean containsPrefixBlock ( int prefixLength ) { checkSubnet ( this , prefixLength ) ; int divisionCount = getDivisionCount ( ) ; int prevBitCount = 0 ; for ( int i = 0 ; i < divisionCount ; i ++ ) { AddressDivision division = getDivision ( i ) ; int bitCount = division . getBitCount ( ) ; int totalBitCount = bitCount + prevBitCount ; if ( prefixLength < totalBitCount ) { int divPrefixLen = Math . max ( 0 , prefixLength - prevBitCount ) ; if ( ! division . isPrefixBlock ( division . getDivisionValue ( ) , division . getUpperDivisionValue ( ) , divPrefixLen ) ) { return false ; } for ( ++ i ; i < divisionCount ; i ++ ) { division = getDivision ( i ) ; if ( ! division . isFullRange ( ) ) { return false ; } } return true ; } prevBitCount = totalBitCount ; } return true ; }
Returns whether the values of this division grouping contain the prefix block for the given prefix length
223
17
150,745
protected static < S extends IPAddressSegment > void normalizePrefixBoundary ( int sectionPrefixBits , S segments [ ] , int segmentBitCount , int segmentByteCount , BiFunction < S , Integer , S > segProducer ) { //we've already verified segment prefixes in super constructor. We simply need to check the case where the prefix is at a segment boundary, //whether the network side has the correct prefix int networkSegmentIndex = getNetworkSegmentIndex ( sectionPrefixBits , segmentByteCount , segmentBitCount ) ; if ( networkSegmentIndex >= 0 ) { S segment = segments [ networkSegmentIndex ] ; if ( ! segment . isPrefixed ( ) ) { segments [ networkSegmentIndex ] = segProducer . apply ( segment , segmentBitCount ) ; } } }
In the case where the prefix sits at a segment boundary and the prefix sequence is null - null - 0 this changes to prefix sequence of null - x - 0 where x is segment bit length .
178
39
150,746
protected static < R extends AddressSection , S extends AddressSegment > R fastIncrement ( R section , long increment , AddressCreator < ? , R , ? , S > addrCreator , Supplier < R > lowerProducer , Supplier < R > upperProducer , Integer prefixLength ) { if ( increment >= 0 ) { BigInteger count = section . getCount ( ) ; if ( count . compareTo ( LONG_MAX ) <= 0 ) { long longCount = count . longValue ( ) ; if ( longCount > increment ) { if ( longCount == increment + 1 ) { return upperProducer . get ( ) ; } return incrementRange ( section , increment , addrCreator , lowerProducer , prefixLength ) ; } BigInteger value = section . getValue ( ) ; BigInteger upperValue ; if ( value . compareTo ( LONG_MAX ) <= 0 && ( upperValue = section . getUpperValue ( ) ) . compareTo ( LONG_MAX ) <= 0 ) { return increment ( section , increment , addrCreator , count . longValue ( ) , value . longValue ( ) , upperValue . longValue ( ) , lowerProducer , upperProducer , prefixLength ) ; } } } else { BigInteger value = section . getValue ( ) ; if ( value . compareTo ( LONG_MAX ) <= 0 ) { return add ( lowerProducer . get ( ) , value . longValue ( ) , increment , addrCreator , prefixLength ) ; } } return null ; }
Handles the cases in which we can use longs rather than BigInteger
322
15
150,747
public StringBuilder getSQLCondition ( StringBuilder builder , String columnName ) { String string = networkString . getString ( ) ; if ( isEntireAddress ) { matchString ( builder , columnName , string ) ; } else { matchSubString ( builder , columnName , networkString . getTrailingSegmentSeparator ( ) , networkString . getTrailingSeparatorCount ( ) + 1 , string ) ; } return builder ; }
Get an SQL condition to match this address section representation
98
10
150,748
protected static BigInteger getRadixPower ( BigInteger radix , int power ) { long key = ( ( ( long ) radix . intValue ( ) ) << 32 ) | power ; BigInteger result = radixPowerMap . get ( key ) ; if ( result == null ) { if ( power == 1 ) { result = radix ; } else if ( ( power & 1 ) == 0 ) { BigInteger halfPower = getRadixPower ( radix , power >> 1 ) ; result = halfPower . multiply ( halfPower ) ; } else { BigInteger halfPower = getRadixPower ( radix , ( power - 1 ) >> 1 ) ; result = halfPower . multiply ( halfPower ) . multiply ( radix ) ; } radixPowerMap . put ( key , result ) ; } return result ; }
Caches the results of radix to the given power .
175
12
150,749
protected byte [ ] getBytesInternal ( ) { byte cached [ ] ; if ( hasNoValueCache ( ) || ( cached = valueCache . lowerBytes ) == null ) { valueCache . lowerBytes = cached = getBytesImpl ( true ) ; } return cached ; }
gets the bytes sharing the cached array and does not clone it
57
12
150,750
protected byte [ ] getUpperBytesInternal ( ) { byte cached [ ] ; if ( hasNoValueCache ( ) ) { ValueCache cache = valueCache ; cache . upperBytes = cached = getBytesImpl ( false ) ; if ( ! isMultiple ( ) ) { cache . lowerBytes = cached ; } } else { ValueCache cache = valueCache ; if ( ( cached = cache . upperBytes ) == null ) { if ( ! isMultiple ( ) ) { if ( ( cached = cache . lowerBytes ) != null ) { cache . upperBytes = cached ; } else { cache . lowerBytes = cache . upperBytes = cached = getBytesImpl ( false ) ; } } else { cache . upperBytes = cached = getBytesImpl ( false ) ; } } } return cached ; }
Gets the bytes for the highest address in the range represented by this address .
166
16
150,751
@ Override public int getMinPrefixLengthForBlock ( ) { int count = getDivisionCount ( ) ; int totalPrefix = getBitCount ( ) ; for ( int i = count - 1 ; i >= 0 ; i -- ) { AddressDivisionBase div = getDivision ( i ) ; int segBitCount = div . getBitCount ( ) ; int segPrefix = div . getMinPrefixLengthForBlock ( ) ; if ( segPrefix == segBitCount ) { break ; } else { totalPrefix -= segBitCount ; if ( segPrefix != 0 ) { totalPrefix += segPrefix ; break ; } } } return totalPrefix ; }
Returns the smallest prefix length possible such that this address division grouping includes the block of addresses for that prefix .
155
21
150,752
@ Override public Integer getPrefixLengthForSingleBlock ( ) { int count = getDivisionCount ( ) ; int totalPrefix = 0 ; for ( int i = 0 ; i < count ; i ++ ) { AddressDivisionBase div = getDivision ( i ) ; Integer divPrefix = div . getPrefixLengthForSingleBlock ( ) ; if ( divPrefix == null ) { return null ; } totalPrefix += divPrefix ; if ( divPrefix < div . getBitCount ( ) ) { //remaining segments must be full range or we return null for ( i ++ ; i < count ; i ++ ) { AddressDivisionBase laterDiv = getDivision ( i ) ; if ( ! laterDiv . isFullRange ( ) ) { return null ; } } } } return cacheBits ( totalPrefix ) ; }
Returns a prefix length for which the range of this segment grouping matches the the block of addresses for that prefix .
183
22
150,753
@ Override public BigInteger getCount ( ) { BigInteger cached = cachedCount ; if ( cached == null ) { cachedCount = cached = getCountImpl ( ) ; } return cached ; }
gets the count of addresses that this address division grouping may represent
41
12
150,754
public static int validateZone ( CharSequence zone ) { for ( int i = 0 ; i < zone . length ( ) ; i ++ ) { char c = zone . charAt ( i ) ; if ( c == IPAddress . PREFIX_LEN_SEPARATOR ) { return i ; } if ( c == IPv6Address . SEGMENT_SEPARATOR ) { return i ; } } return - 1 ; }
Returns the index of the first invalid character of the zone or - 1 if the zone is valid
92
19
150,755
private static long switchValue8 ( long currentHexValue , int digitCount ) { long result = 0x7 & currentHexValue ; int shift = 0 ; while ( -- digitCount > 0 ) { shift += 3 ; currentHexValue >>>= 4 ; result |= ( 0x7 & currentHexValue ) << shift ; } return result ; }
The digits were stored as a hex value thix switches them to an octal value .
77
18
150,756
static ParsedHost validateHostImpl ( HostName fromHost ) throws HostNameException { final String str = fromHost . toString ( ) ; HostNameParameters validationOptions = fromHost . getValidationOptions ( ) ; return validateHost ( fromHost , str , validationOptions ) ; }
So we will follow rfc 1035 and in addition allow the underscore .
60
15
150,757
private static CharSequence convertReverseDNSIPv4 ( String str , int suffixStartIndex ) throws AddressStringException { StringBuilder builder = new StringBuilder ( suffixStartIndex ) ; int segCount = 0 ; int j = suffixStartIndex ; for ( int i = suffixStartIndex - 1 ; i > 0 ; i -- ) { char c1 = str . charAt ( i ) ; if ( c1 == IPv4Address . SEGMENT_SEPARATOR ) { if ( j - i <= 1 ) { throw new AddressStringException ( str , i ) ; } for ( int k = i + 1 ; k < j ; k ++ ) { builder . append ( str . charAt ( k ) ) ; } builder . append ( c1 ) ; j = i ; segCount ++ ; } } for ( int k = 0 ; k < j ; k ++ ) { builder . append ( str . charAt ( k ) ) ; } if ( segCount + 1 != IPv4Address . SEGMENT_COUNT ) { throw new AddressStringException ( str , 0 ) ; } return builder ; }
123 . 2 . 3 . 4 is 4 . 3 . 2 . 123 . in - addr . arpa .
240
23
150,758
protected boolean isPrefixBlock ( long divisionValue , long upperValue , int divisionPrefixLen ) { if ( divisionPrefixLen == 0 ) { return divisionValue == 0 && upperValue == getMaxValue ( ) ; } long ones = ~ 0L ; long divisionBitMask = ~ ( ones << getBitCount ( ) ) ; long divisionPrefixMask = ones << ( getBitCount ( ) - divisionPrefixLen ) ; long divisionNonPrefixMask = ~ divisionPrefixMask ; return testRange ( divisionValue , upperValue , upperValue , divisionPrefixMask & divisionBitMask , divisionNonPrefixMask ) ; }
Returns whether the division range includes the block of values for its prefix length
135
14
150,759
public boolean matchesWithMask ( long lowerValue , long upperValue , long mask ) { if ( lowerValue == upperValue ) { return matchesWithMask ( lowerValue , mask ) ; } if ( ! isMultiple ( ) ) { //we know lowerValue and upperValue are not the same, so impossible to match those two values with a single value return false ; } long thisValue = getDivisionValue ( ) ; long thisUpperValue = getUpperDivisionValue ( ) ; if ( ! isMaskCompatibleWithRange ( thisValue , thisUpperValue , mask , getMaxValue ( ) ) ) { return false ; } return lowerValue == ( thisValue & mask ) && upperValue == ( thisUpperValue & mask ) ; }
returns whether masking with the given mask results in a valid contiguous range for this segment and if it does if it matches the range obtained when masking the given values with the same mask .
158
39
150,760
protected static boolean isMaskCompatibleWithRange ( long value , long upperValue , long maskValue , long maxValue ) { if ( value == upperValue || maskValue == maxValue || maskValue == 0 ) { return true ; } //algorithm: //here we find the highest bit that is part of the range, highestDifferingBitInRange (ie changes from lower to upper) //then we find the highest bit in the mask that is 1 that is the same or below highestDifferingBitInRange (if such a bit exists) //this gives us the highest bit that is part of the masked range (ie changes from lower to upper after applying the mask) //if this latter bit exists, then any bit below it in the mask must be 1 to include the entire range. long differing = value ^ upperValue ; boolean foundDiffering = ( differing != 0 ) ; boolean differingIsLowestBit = ( differing == 1 ) ; if ( foundDiffering && ! differingIsLowestBit ) { int highestDifferingBitInRange = Long . numberOfLeadingZeros ( differing ) ; long maskMask = ~ 0L >>> highestDifferingBitInRange ; long differingMasked = maskValue & maskMask ; foundDiffering = ( differingMasked != 0 ) ; differingIsLowestBit = ( differingMasked == 1 ) ; if ( foundDiffering && ! differingIsLowestBit ) { //anything below highestDifferingBitMasked in the mask must be ones //Also, if we have masked out any 1 bit in the original, then anything that we do not mask out that follows must be all 1s int highestDifferingBitMasked = Long . numberOfLeadingZeros ( differingMasked ) ; long hostMask = ~ 0L >>> ( highestDifferingBitMasked + 1 ) ; //for the first mask bit that is 1, all bits that follow must also be 1 if ( ( maskValue & hostMask ) != hostMask ) { //check if all ones below return false ; } if ( highestDifferingBitMasked > highestDifferingBitInRange ) { //We have masked out a 1 bit, so we need to check that all bits in upper value that we do not mask out are also 1 bits, otherwise we end up missing values in the masked range //This check is unnecessary for prefix-length subnets, only non-standard ranges might fail this check. //For instance, if we have range 0000 to 1010 //and we mask upper and lower with 0111 //we get 0000 to 0010, but 0111 was in original range, and the mask of that value retains that value //so that value needs to be in final range, and it's not. //What went wrong is that we masked out the top bit, and any other bit that is not masked out must be 1. //To work, our original range needed to be 0000 to 1111, with the three 1s following the first masked-out 1 long hostMaskUpper = ~ 0L >>> highestDifferingBitMasked ; if ( ( upperValue & hostMaskUpper ) != hostMaskUpper ) { return false ; } } } } return true ; }
when divisionPrefixLen is null isAutoSubnets has no effect
665
14
150,761
public boolean isEUI64 ( boolean partial ) { int segmentCount = getSegmentCount ( ) ; int endIndex = addressSegmentIndex + segmentCount ; if ( addressSegmentIndex <= 5 ) { if ( endIndex > 6 ) { int index3 = 5 - addressSegmentIndex ; IPv6AddressSegment seg3 = getSegment ( index3 ) ; IPv6AddressSegment seg4 = getSegment ( index3 + 1 ) ; return seg4 . matchesWithMask ( 0xfe00 , 0xff00 ) && seg3 . matchesWithMask ( 0xff , 0xff ) ; } else if ( partial && endIndex == 6 ) { IPv6AddressSegment seg3 = getSegment ( 5 - addressSegmentIndex ) ; return seg3 . matchesWithMask ( 0xff , 0xff ) ; } } else if ( partial && addressSegmentIndex == 6 && endIndex > 6 ) { IPv6AddressSegment seg4 = getSegment ( 6 - addressSegmentIndex ) ; return seg4 . matchesWithMask ( 0xfe00 , 0xff00 ) ; } return partial ; }
Whether this section is consistent with an EUI64 section which means it came from an extended 8 byte address and the corresponding segments in the middle match 0xff and 0xfe
247
35
150,762
public MACAddressSection toEUI ( boolean extended ) { MACAddressSegment [ ] segs = toEUISegments ( extended ) ; if ( segs == null ) { return null ; } MACAddressCreator creator = getMACNetwork ( ) . getAddressCreator ( ) ; return createSectionInternal ( creator , segs , Math . max ( 0 , addressSegmentIndex - 4 ) << 1 , extended ) ; }
Returns the corresponding mac section or null if this address section does not correspond to a mac section . If this address section has a prefix length it is ignored .
91
31
150,763
MACAddressSegment [ ] toEUISegments ( boolean extended ) { IPv6AddressSegment seg0 , seg1 , seg2 , seg3 ; int start = addressSegmentIndex ; int segmentCount = getSegmentCount ( ) ; int segmentIndex ; if ( start < 4 ) { start = 0 ; segmentIndex = 4 - start ; } else { start -= 4 ; segmentIndex = 0 ; } int originalSegmentIndex = segmentIndex ; seg0 = ( start == 0 && segmentIndex < segmentCount ) ? getSegment ( segmentIndex ++ ) : null ; seg1 = ( start <= 1 && segmentIndex < segmentCount ) ? getSegment ( segmentIndex ++ ) : null ; seg2 = ( start <= 2 && segmentIndex < segmentCount ) ? getSegment ( segmentIndex ++ ) : null ; seg3 = ( start <= 3 && segmentIndex < segmentCount ) ? getSegment ( segmentIndex ++ ) : null ; int macSegCount = ( segmentIndex - originalSegmentIndex ) << 1 ; if ( ! extended ) { macSegCount -= 2 ; } if ( ( seg1 != null && ! seg1 . matchesWithMask ( 0xff , 0xff ) ) || ( seg2 != null && ! seg2 . matchesWithMask ( 0xfe00 , 0xff00 ) ) || macSegCount == 0 ) { return null ; } MACAddressCreator creator = getMACNetwork ( ) . getAddressCreator ( ) ; MACAddressSegment ZERO_SEGMENT = creator . createSegment ( 0 ) ; MACAddressSegment newSegs [ ] = creator . createSegmentArray ( macSegCount ) ; int macStartIndex = 0 ; if ( seg0 != null ) { seg0 . getSplitSegments ( newSegs , macStartIndex , creator ) ; //toggle the u/l bit MACAddressSegment macSegment0 = newSegs [ 0 ] ; int lower0 = macSegment0 . getSegmentValue ( ) ; int upper0 = macSegment0 . getUpperSegmentValue ( ) ; int mask2ndBit = 0x2 ; if ( ! macSegment0 . matchesWithMask ( mask2ndBit & lower0 , mask2ndBit ) ) { return null ; } //you can use matches with mask lower0 ^= mask2ndBit ; //flip the universal/local bit upper0 ^= mask2ndBit ; newSegs [ 0 ] = creator . createSegment ( lower0 , upper0 , null ) ; macStartIndex += 2 ; } if ( seg1 != null ) { seg1 . getSplitSegments ( newSegs , macStartIndex , creator ) ; //a ff fe b if ( ! extended ) { newSegs [ macStartIndex + 1 ] = ZERO_SEGMENT ; } macStartIndex += 2 ; } if ( seg2 != null ) { if ( ! extended ) { if ( seg1 != null ) { macStartIndex -= 2 ; MACAddressSegment first = newSegs [ macStartIndex ] ; seg2 . getSplitSegments ( newSegs , macStartIndex , creator ) ; newSegs [ macStartIndex ] = first ; } else { seg2 . getSplitSegments ( newSegs , macStartIndex , creator ) ; newSegs [ macStartIndex ] = ZERO_SEGMENT ; } } else { seg2 . getSplitSegments ( newSegs , macStartIndex , creator ) ; } macStartIndex += 2 ; } if ( seg3 != null ) { seg3 . getSplitSegments ( newSegs , macStartIndex , creator ) ; } return newSegs ; }
prefix length in this section is ignored when converting to MAC
808
11
150,764
public IPv4AddressSection getEmbeddedIPv4AddressSection ( int startIndex , int endIndex ) { if ( startIndex == ( ( IPv6Address . MIXED_ORIGINAL_SEGMENT_COUNT - this . addressSegmentIndex ) << 1 ) && endIndex == ( getSegmentCount ( ) << 1 ) ) { return getEmbeddedIPv4AddressSection ( ) ; } IPv4AddressCreator creator = getIPv4Network ( ) . getAddressCreator ( ) ; IPv4AddressSegment [ ] segments = creator . createSegmentArray ( ( endIndex - startIndex ) >> 1 ) ; int i = startIndex , j = 0 ; if ( i % IPv6Address . BYTES_PER_SEGMENT == 1 ) { IPv6AddressSegment ipv6Segment = getSegment ( i >> 1 ) ; i ++ ; ipv6Segment . getSplitSegments ( segments , j - 1 , creator ) ; j ++ ; } for ( ; i < endIndex ; i <<= 1 , j <<= 1 ) { IPv6AddressSegment ipv6Segment = getSegment ( i >> 1 ) ; ipv6Segment . getSplitSegments ( segments , j , creator ) ; } return createEmbeddedSection ( creator , segments , this ) ; }
Produces an IPv4 address section from any sequence of bytes in this IPv6 address section
287
18
150,765
public boolean hasUppercaseVariations ( int base , boolean lowerOnly ) { if ( base > 10 ) { int count = getSegmentCount ( ) ; for ( int i = 0 ; i < count ; i ++ ) { IPv6AddressSegment seg = getSegment ( i ) ; if ( seg . hasUppercaseVariations ( base , lowerOnly ) ) { return true ; } } } return false ; }
Returns whether this subnet or address has alphabetic digits when printed .
93
15
150,766
public IPv6AddressSection [ ] mergeToSequentialBlocks ( IPv6AddressSection ... sections ) throws SizeMismatchException { List < IPAddressSegmentSeries > blocks = getMergedSequentialBlocks ( this , sections , true , createSeriesCreator ( getAddressCreator ( ) , getMaxSegmentValue ( ) ) ) ; return blocks . toArray ( new IPv6AddressSection [ blocks . size ( ) ] ) ; }
Merges this with the list of sections to produce the smallest array of sequential block subnets going from smallest to largest
94
23
150,767
@ Override public String toCanonicalString ( ) { String result ; if ( hasNoStringCache ( ) || ( result = stringCache . canonicalString ) == null ) { stringCache . canonicalString = result = toNormalizedString ( IPv6StringCache . canonicalParams ) ; } return result ; }
This produces a canonical string .
66
6
150,768
@ Override public String toFullString ( ) { String result ; if ( hasNoStringCache ( ) || ( result = getStringCache ( ) . fullString ) == null ) { getStringCache ( ) . fullString = result = toNormalizedString ( IPv6StringCache . fullParams ) ; } return result ; }
This produces a string with no compressed segments and all segments of full length which is 4 characters for IPv6 segments and 3 characters for IPv4 segments .
70
30
150,769
@ Override public String toNormalizedString ( ) { String result ; if ( hasNoStringCache ( ) || ( result = getStringCache ( ) . normalizedString ) == null ) { getStringCache ( ) . normalizedString = result = toNormalizedString ( IPv6StringCache . normalizedParams ) ; } return result ; }
The normalized string returned by this method is consistent with java . net . Inet6address . IPs are not compressed nor mixed in this representation .
71
30
150,770
private int [ ] getCompressIndexAndCount ( CompressOptions options , boolean createMixed ) { if ( options != null ) { CompressionChoiceOptions rangeSelection = options . rangeSelection ; RangeList compressibleSegs = rangeSelection . compressHost ( ) ? getZeroRangeSegments ( ) : getZeroSegments ( ) ; int maxIndex = - 1 , maxCount = 0 ; int segmentCount = getSegmentCount ( ) ; boolean compressMixed = createMixed && options . compressMixedOptions . compressMixed ( this ) ; boolean preferHost = ( rangeSelection == CompressOptions . CompressionChoiceOptions . HOST_PREFERRED ) ; boolean preferMixed = createMixed && ( rangeSelection == CompressOptions . CompressionChoiceOptions . MIXED_PREFERRED ) ; for ( int i = compressibleSegs . size ( ) - 1 ; i >= 0 ; i -- ) { Range range = compressibleSegs . getRange ( i ) ; int index = range . index ; int count = range . length ; if ( createMixed ) { //so here we shorten the range to exclude the mixed part if necessary int mixedIndex = IPv6Address . MIXED_ORIGINAL_SEGMENT_COUNT - addressSegmentIndex ; if ( ! compressMixed || index > mixedIndex || index + count < segmentCount ) { //range does not include entire mixed part. We never compress only part of a mixed part. //the compressible range must stop at the mixed part count = Math . min ( count , mixedIndex - index ) ; } } //select this range if is the longest if ( count > 0 && count >= maxCount && ( options . compressSingle || count > 1 ) ) { maxIndex = index ; maxCount = count ; } if ( preferHost && isPrefixed ( ) && ( ( index + count ) * IPv6Address . BITS_PER_SEGMENT ) > getNetworkPrefixLength ( ) ) { //this range contains the host //Since we are going backwards, this means we select as the maximum any zero segment that includes the host break ; } if ( preferMixed && index + count >= segmentCount ) { //this range contains the mixed section //Since we are going backwards, this means we select to compress the mixed segment break ; } } if ( maxIndex >= 0 ) { return new int [ ] { maxIndex , maxCount } ; } } return null ; }
Chooses a single segment to be compressed or null if no segment could be chosen .
526
17
150,771
public static int getHostSegmentIndex ( int networkPrefixLength , int bytesPerSegment , int bitsPerSegment ) { if ( bytesPerSegment > 1 ) { if ( bytesPerSegment == 2 ) { return networkPrefixLength >> 4 ; } return networkPrefixLength / bitsPerSegment ; } return networkPrefixLength >> 3 ; }
Returns the index of the segment containing the first byte outside the network prefix . When networkPrefixLength is null or it matches or exceeds the bit length returns the segment count .
78
35
150,772
@ Override public void validate ( ) throws AddressStringException { if ( isValidated ( ) ) { return ; } synchronized ( this ) { if ( isValidated ( ) ) { return ; } //we know nothing about this address. See what it is. try { parsedAddress = getValidator ( ) . validateAddress ( this ) ; isValid = true ; } catch ( AddressStringException e ) { cachedException = e ; isValid = false ; throw e ; } } }
Validates this string is a valid address and if not throws an exception with a descriptive message indicating why it is not .
102
24
150,773
protected boolean isChangedByMask ( int maskValue , Integer segmentPrefixLength ) throws IncompatibleAddressException { boolean hasBits = ( segmentPrefixLength != null ) ; if ( hasBits && ( segmentPrefixLength < 0 || segmentPrefixLength > getBitCount ( ) ) ) { throw new PrefixLenException ( this , segmentPrefixLength ) ; } //note that the mask can represent a range (for example a CIDR mask), //but we use the lowest value (maskSegment.value) in the range when masking (ie we discard the range) int value = getSegmentValue ( ) ; int upperValue = getUpperSegmentValue ( ) ; return value != ( value & maskValue ) || upperValue != ( upperValue & maskValue ) || ( isPrefixed ( ) ? ! getSegmentPrefixLength ( ) . equals ( segmentPrefixLength ) : hasBits ) ; }
returns a new segment masked by the given mask
200
10
150,774
public boolean isMaskCompatibleWithRange ( int maskValue , Integer segmentPrefixLength ) throws PrefixLenException { if ( ! isMultiple ( ) ) { return true ; } return super . isMaskCompatibleWithRange ( maskValue , segmentPrefixLength , getNetwork ( ) . getPrefixConfiguration ( ) . allPrefixedAddressesAreSubnets ( ) ) ; }
Check that the range resulting from the mask is contiguous otherwise we cannot represent it .
81
16
150,775
public boolean isBitwiseOrCompatibleWithRange ( int maskValue , Integer segmentPrefixLength ) throws PrefixLenException { return super . isBitwiseOrCompatibleWithRange ( maskValue , segmentPrefixLength , getNetwork ( ) . getPrefixConfiguration ( ) . allPrefixedAddressesAreSubnets ( ) ) ; }
Similar to masking checks that the range resulting from the bitwise or is contiguous .
72
17
150,776
public IPv6AddressSegment join ( IPv6AddressCreator creator , IPv4AddressSegment low ) throws IncompatibleAddressException { int shift = IPv4Address . BITS_PER_SEGMENT ; Integer prefix = getJoinedSegmentPrefixLength ( shift , getSegmentPrefixLength ( ) , low . getSegmentPrefixLength ( ) ) ; if ( isMultiple ( ) ) { //if the high segment has a range, the low segment must match the full range, //otherwise it is not possible to create an equivalent range when joining if ( ! low . isFullRange ( ) ) { throw new IncompatibleAddressException ( this , low , "ipaddress.error.invalidMixedRange" ) ; } } return creator . createSegment ( ( getSegmentValue ( ) << shift ) | low . getSegmentValue ( ) , ( getUpperSegmentValue ( ) << shift ) | low . getUpperSegmentValue ( ) , prefix ) ; }
Joins with another IPv4 segment to produce a IPv6 segment .
212
14
150,777
public HostName toHostName ( ) { HostName host = fromHost ; if ( host == null ) { fromHost = host = toCanonicalHostName ( ) ; } return host ; }
If this address was resolved from a host returns that host . Otherwise does a reverse name lookup .
42
19
150,778
public boolean matchesWithMask ( IPAddress other , IPAddress mask ) { return getSection ( ) . matchesWithMask ( other . getSection ( ) , mask . getSection ( ) ) ; }
Applies the mask to this address and then compares values with the given address
43
15
150,779
public IPv6Address toLinkLocalIPv6 ( ) { IPv6AddressNetwork network = getIPv6Network ( ) ; IPv6AddressSection linkLocalPrefix = network . getLinkLocalPrefix ( ) ; IPv6AddressCreator creator = network . getAddressCreator ( ) ; return creator . createAddress ( linkLocalPrefix . append ( toEUI64IPv6 ( ) ) ) ; }
Converts to a link - local Ipv6 address . Any MAC prefix length is ignored . Other elements of this address section are incorporated into the conversion . This will provide the latter 4 segments of an IPv6 address to be paired with the link - local IPv6 prefix of 4 segments .
88
59
150,780
public MACAddress toEUI64 ( boolean asMAC ) { if ( ! isExtended ( ) ) { //getSegmentCount() == EXTENDED_UNIQUE_IDENTIFIER_48_SEGMENT_COUNT MACAddressCreator creator = getAddressCreator ( ) ; MACAddressSegment segs [ ] = creator . createSegmentArray ( EXTENDED_UNIQUE_IDENTIFIER_64_SEGMENT_COUNT ) ; MACAddressSection section = getSection ( ) ; section . getSegments ( 0 , 3 , segs , 0 ) ; MACAddressSegment ffSegment = creator . createSegment ( 0xff ) ; segs [ 3 ] = ffSegment ; segs [ 4 ] = asMAC ? ffSegment : creator . createSegment ( 0xfe ) ; section . getSegments ( 3 , 6 , segs , 5 ) ; Integer prefLength = getPrefixLength ( ) ; if ( prefLength != null ) { MACAddressSection resultSection = creator . createSectionInternal ( segs , true ) ; if ( prefLength >= 24 ) { prefLength += MACAddress . BITS_PER_SEGMENT << 1 ; //two segments } resultSection . assignPrefixLength ( prefLength ) ; } return creator . createAddressInternal ( segs ) ; } else { MACAddressSection section = getSection ( ) ; MACAddressSegment seg3 = section . getSegment ( 3 ) ; MACAddressSegment seg4 = section . getSegment ( 4 ) ; if ( seg3 . matches ( 0xff ) && seg4 . matches ( asMAC ? 0xff : 0xfe ) ) { return this ; } } throw new IncompatibleAddressException ( this , "ipaddress.mac.error.not.eui.convertible" ) ; }
Convert to IPv6 EUI - 64 section
394
10
150,781
@ Override public Iterator < ? extends IPAddressSeqRange > prefixIterator ( int prefixLength ) { if ( ! isMultiple ( ) ) { return new Iterator < IPAddressSeqRange > ( ) { IPAddressSeqRange orig = IPAddressSeqRange . this ; @ Override public boolean hasNext ( ) { return orig != null ; } @ Override public IPAddressSeqRange next ( ) { if ( orig == null ) { throw new NoSuchElementException ( ) ; } IPAddressSeqRange result = orig ; orig = null ; return result ; } @ Override public void remove ( ) { throw new UnsupportedOperationException ( ) ; } } ; } return new Iterator < IPAddressSeqRange > ( ) { Iterator < ? extends IPAddress > prefixBlockIterator = prefixBlockIterator ( prefixLength ) ; private boolean first = true ; @ Override public boolean hasNext ( ) { return prefixBlockIterator . hasNext ( ) ; } @ Override public IPAddressSeqRange next ( ) { IPAddress next = prefixBlockIterator . next ( ) ; if ( first ) { first = false ; // next is a prefix block IPAddress lower = getLower ( ) ; if ( hasNext ( ) ) { if ( ! lower . includesZeroHost ( prefixLength ) ) { return create ( lower , next . getUpper ( ) ) ; } } else { IPAddress upper = getUpper ( ) ; if ( ! lower . includesZeroHost ( prefixLength ) || ! upper . includesMaxHost ( prefixLength ) ) { return create ( lower , upper ) ; } } } else if ( ! hasNext ( ) ) { IPAddress upper = getUpper ( ) ; if ( ! upper . includesMaxHost ( prefixLength ) ) { return create ( next . getLower ( ) , upper ) ; } } return next . toSequentialRange ( ) ; } @ Override public void remove ( ) { throw new UnsupportedOperationException ( ) ; } } ; }
Iterates through the range of prefixes in this range instance using the given prefix length .
437
18
150,782
public static IPAddressSeqRange [ ] join ( IPAddressSeqRange ... ranges ) { int joinedCount = 0 ; Arrays . sort ( ranges , Address . ADDRESS_LOW_VALUE_COMPARATOR ) ; for ( int i = 0 ; i < ranges . length ; i ++ ) { IPAddressSeqRange range = ranges [ i ] ; if ( range == null ) { continue ; } for ( int j = i + 1 ; j < ranges . length ; j ++ ) { IPAddressSeqRange range2 = ranges [ j ] ; if ( range2 == null ) { continue ; } IPAddress upper = range . getUpper ( ) ; IPAddress lower = range2 . getLower ( ) ; if ( compareLowValues ( upper , lower ) >= 0 || upper . increment ( 1 ) . equals ( lower ) ) { //join them ranges [ i ] = range = range . create ( range . getLower ( ) , range2 . getUpper ( ) ) ; ranges [ j ] = null ; joinedCount ++ ; } else break ; } } if ( joinedCount == 0 ) { return ranges ; } IPAddressSeqRange joined [ ] = new IPAddressSeqRange [ ranges . length - joinedCount ] ; for ( int i = 0 , j = 0 ; i < ranges . length ; i ++ ) { IPAddressSeqRange range = ranges [ i ] ; if ( range == null ) { continue ; } joined [ j ++ ] = range ; if ( j >= joined . length ) { break ; } } return joined ; }
Joins the given ranges into the fewest number of ranges . If no joining can take place the original array is returned .
342
25
150,783
public IPAddressSeqRange intersect ( IPAddressSeqRange other ) { IPAddress otherLower = other . getLower ( ) ; IPAddress otherUpper = other . getUpper ( ) ; IPAddress lower = this . getLower ( ) ; IPAddress upper = this . getUpper ( ) ; if ( compareLowValues ( lower , otherLower ) <= 0 ) { if ( compareLowValues ( upper , otherUpper ) >= 0 ) { return other ; } else if ( compareLowValues ( upper , otherLower ) < 0 ) { return null ; } return create ( otherLower , upper ) ; } else if ( compareLowValues ( otherUpper , upper ) >= 0 ) { return this ; } else if ( compareLowValues ( otherUpper , lower ) < 0 ) { return null ; } return create ( lower , otherUpper ) ; }
Returns the intersection of this range with the given range a range which includes those addresses in both this and the given rqnge .
189
27
150,784
public IPAddressSeqRange [ ] subtract ( IPAddressSeqRange other ) { IPAddress otherLower = other . getLower ( ) ; IPAddress otherUpper = other . getUpper ( ) ; IPAddress lower = this . getLower ( ) ; IPAddress upper = this . getUpper ( ) ; if ( compareLowValues ( lower , otherLower ) < 0 ) { if ( compareLowValues ( upper , otherUpper ) > 0 ) { // l ol ou u return createPair ( lower , otherLower . increment ( - 1 ) , otherUpper . increment ( 1 ) , upper ) ; } else { int comp = compareLowValues ( upper , otherLower ) ; if ( comp < 0 ) { // l u ol ou return createSingle ( ) ; } else if ( comp == 0 ) { // l u == ol ou return createSingle ( lower , upper . increment ( - 1 ) ) ; } return createSingle ( lower , otherLower . increment ( - 1 ) ) ; // l ol u ou } } else if ( compareLowValues ( otherUpper , upper ) >= 0 ) { // ol l u ou return createEmpty ( ) ; } else { int comp = compareLowValues ( otherUpper , lower ) ; if ( comp < 0 ) { return createSingle ( ) ; // ol ou l u } else if ( comp == 0 ) { return createSingle ( lower . increment ( 1 ) , upper ) ; //ol ou == l u } return createSingle ( otherUpper . increment ( 1 ) , upper ) ; // ol l ou u } }
Subtracts the given range from this range to produce either zero one or two address ranges that contain the addresses in this range and not in the given range . If the result has length 2 the two ranges are in increasing order .
349
47
150,785
protected boolean isNetworkSection ( int networkPrefixLength , boolean withPrefixLength ) { int segmentCount = getSegmentCount ( ) ; if ( segmentCount == 0 ) { return true ; } int bitsPerSegment = getBitsPerSegment ( ) ; int prefixedSegmentIndex = getNetworkSegmentIndex ( networkPrefixLength , getBytesPerSegment ( ) , bitsPerSegment ) ; if ( prefixedSegmentIndex + 1 < segmentCount ) { return false ; //not the right number of segments } //the segment count matches, now compare the prefixed segment int segPrefLength = getPrefixedSegmentPrefixLength ( bitsPerSegment , networkPrefixLength , prefixedSegmentIndex ) ; return ! getSegment ( segmentCount - 1 ) . isNetworkChangedByPrefix ( segPrefLength , withPrefixLength ) ; }
this method is basically checking whether we can return this for getNetworkSection
189
14
150,786
public Integer getBlockMaskPrefixLength ( boolean network ) { Integer prefixLen ; if ( network ) { if ( hasNoPrefixCache ( ) || ( prefixLen = prefixCache . networkMaskPrefixLen ) == null ) { prefixLen = setNetworkMaskPrefix ( checkForPrefixMask ( network ) ) ; } } else { if ( hasNoPrefixCache ( ) || ( prefixLen = prefixCache . hostMaskPrefixLen ) == null ) { prefixLen = setHostMaskPrefix ( checkForPrefixMask ( network ) ) ; } } if ( prefixLen < 0 ) { return null ; } return prefixLen ; }
If this address section is equivalent to the mask for a CIDR prefix block it returns that prefix length . Otherwise it returns null . A CIDR network mask is an address with all 1s in the network section and then all 0s in the host section . A CIDR host mask is an address with all 0s in the network section and then all 1s in the host section . The prefix length is the length of the network section .
137
92
150,787
public boolean containsNonZeroHosts ( IPAddressSection other ) { if ( ! other . isPrefixed ( ) ) { return contains ( other ) ; } int otherPrefixLength = other . getNetworkPrefixLength ( ) ; if ( otherPrefixLength == other . getBitCount ( ) ) { return contains ( other ) ; } return containsNonZeroHostsImpl ( other , otherPrefixLength ) ; }
Returns whether this address contains the non - zero host addresses in other .
90
14
150,788
public boolean matchesWithMask ( IPAddressSection other , IPAddressSection mask ) { checkMaskSectionCount ( mask ) ; checkSectionCount ( other ) ; int divCount = getSegmentCount ( ) ; for ( int i = 0 ; i < divCount ; i ++ ) { IPAddressSegment div = getSegment ( i ) ; IPAddressSegment maskSegment = mask . getSegment ( i ) ; IPAddressSegment otherSegment = other . getSegment ( i ) ; if ( ! div . matchesWithMask ( otherSegment . getSegmentValue ( ) , otherSegment . getUpperSegmentValue ( ) , maskSegment . getSegmentValue ( ) ) ) { return false ; } } return true ; }
Applies the mask to this address section and then compares values with the given address section
166
17
150,789
protected String toHexString ( boolean with0xPrefix , CharSequence zone ) { if ( isDualString ( ) ) { return toNormalizedStringRange ( toIPParams ( with0xPrefix ? IPStringCache . hexPrefixedParams : IPStringCache . hexParams ) , getLower ( ) , getUpper ( ) , zone ) ; } return toIPParams ( with0xPrefix ? IPStringCache . hexPrefixedParams : IPStringCache . hexParams ) . toString ( this , zone ) ; }
overridden in ipv6 to handle zone
121
9
150,790
public IPv4Address getEmbeddedIPv4Address ( int byteIndex ) { if ( byteIndex == IPv6Address . MIXED_ORIGINAL_SEGMENT_COUNT * IPv6Address . BYTES_PER_SEGMENT ) { return getEmbeddedIPv4Address ( ) ; } IPv4AddressCreator creator = getIPv4Network ( ) . getAddressCreator ( ) ; return creator . createAddress ( getSection ( ) . getEmbeddedIPv4AddressSection ( byteIndex , byteIndex + IPv4Address . BYTE_COUNT ) ) ; /* address creation */ }
Produces an IPv4 address from any sequence of 4 bytes in this IPv6 address .
133
18
150,791
public boolean isIPv4Mapped ( ) { //::ffff:x:x/96 indicates IPv6 address mapped to IPv4 if ( getSegment ( 5 ) . matches ( IPv6Address . MAX_VALUE_PER_SEGMENT ) ) { for ( int i = 0 ; i < 5 ; i ++ ) { if ( ! getSegment ( i ) . isZero ( ) ) { return false ; } } return true ; } return false ; }
Whether the address is IPv4 - mapped
99
8
150,792
public boolean isIPv4Compatible ( ) { return getSegment ( 0 ) . isZero ( ) && getSegment ( 1 ) . isZero ( ) && getSegment ( 2 ) . isZero ( ) && getSegment ( 3 ) . isZero ( ) && getSegment ( 4 ) . isZero ( ) && getSegment ( 5 ) . isZero ( ) ; }
Whether the address is IPv4 - compatible
85
8
150,793
public boolean isWellKnownIPv4Translatable ( ) { //rfc 6052 rfc 6144 //64:ff9b::/96 prefix for auto ipv4/ipv6 translation if ( getSegment ( 0 ) . matches ( 0x64 ) && getSegment ( 1 ) . matches ( 0xff9b ) ) { for ( int i = 2 ; i <= 5 ; i ++ ) { if ( ! getSegment ( i ) . isZero ( ) ) { return false ; } } return true ; } return false ; }
Whether the address has the well - known prefix for IPv4 translatable addresses as in rfc 6052 and 6144
118
24
150,794
@ Override public Inet6Address toInetAddress ( ) { if ( hasZone ( ) ) { Inet6Address result ; if ( hasNoValueCache ( ) || ( result = valueCache . inetAddress ) == null ) { valueCache . inetAddress = result = ( Inet6Address ) toInetAddressImpl ( getBytes ( ) ) ; } return result ; } return ( Inet6Address ) super . toInetAddress ( ) ; }
we need to cache the address in here and not in the address section if there is a zone
101
19
150,795
public String toMixedString ( ) { String result ; if ( hasNoStringCache ( ) || ( result = stringCache . mixedString ) == null ) { if ( hasZone ( ) ) { stringCache . mixedString = result = toNormalizedString ( IPv6StringCache . mixedParams ) ; } else { result = getSection ( ) . toMixedString ( ) ; //the cache is shared so no need to update it here } } return result ; }
Produces a string in which the lower 4 bytes are expressed as an IPv4 address and the remaining upper bytes are expressed in IPv6 format .
100
29
150,796
@ Override public String toNormalizedString ( ) { String result ; if ( hasNoStringCache ( ) || ( result = stringCache . normalizedString ) == null ) { if ( hasZone ( ) ) { stringCache . normalizedString = result = toNormalizedString ( IPv6StringCache . normalizedParams ) ; } else { result = getSection ( ) . toNormalizedString ( ) ; //the cache is shared so no need to update it here } } return result ; }
The normalized string returned by this method is consistent with java . net . Inet6address .
103
19
150,797
@ Override public String toNormalizedWildcardString ( ) { String result ; if ( hasNoStringCache ( ) || ( result = stringCache . normalizedWildcardString ) == null ) { if ( hasZone ( ) ) { stringCache . normalizedWildcardString = result = toNormalizedString ( IPv6StringCache . wildcardNormalizedParams ) ; } else { result = getSection ( ) . toNormalizedWildcardString ( ) ; //the cache is shared so no need to update it here } } return result ; }
note this string is used by hashCode
114
8
150,798
public String toNormalizedString ( boolean keepMixed , IPv6StringOptions params ) { if ( keepMixed && fromString != null && getAddressfromString ( ) . isMixedIPv6 ( ) && ! params . makeMixed ( ) ) { params = new IPv6StringOptions ( params . base , params . expandSegments , params . wildcardOption , params . wildcards , params . segmentStrPrefix , true , params . ipv4Opts , params . compressOptions , params . separator , params . zoneSeparator , params . addrLabel , params . addrSuffix , params . reverse , params . splitDigits , params . uppercase ) ; } return toNormalizedString ( params ) ; }
Constructs a string representing this address according to the given parameters
159
12
150,799
public IPv4AddressSection mask ( IPv4AddressSection mask , boolean retainPrefix ) throws IncompatibleAddressException , PrefixLenException , SizeMismatchException { checkMaskSectionCount ( mask ) ; return getSubnetSegments ( this , retainPrefix ? getPrefixLength ( ) : null , getAddressCreator ( ) , true , this :: getSegment , i -> mask . getSegment ( i ) . getSegmentValue ( ) , false ) ; }
Does the bitwise conjunction with this address . Useful when subnetting .
102
15