summaryrefslogtreecommitdiffstats
path: root/EssentialsUpdate/src/f00f/net/irc/martyr/util/CtcpUtil.java
blob: ed31c46e7ad35ede8a374e6217fd5f3aa1150d3c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package f00f.net.irc.martyr.util;

import java.util.NoSuchElementException;

public class CtcpUtil
{
	public static final char CTCP_TAG_DELIM = '\001';
	
	/**
	 * Returns a new string ready for sending via MessageCommand.
     *
     * @param action Action string to create
     * @return Action string ready for sending
	 */
	public static String makeActionString( String action )
	{
		return makeCtcpString( "ACTION " + action );
	}
	
	public static String makeCtcpString( String s )
	{
		return "" + CTCP_TAG_DELIM + s + CTCP_TAG_DELIM;
	}
	
	/**
	 * Parses the string into tokens, where each token is either a
	 * CTCP escaped sequence or not.
	 */
	public static class CtcpTokenizer
	{
		private String str;

		public CtcpTokenizer( String in )
		{
			this.str = in;
		}

		public boolean isNextACtcp()
		{
			return str.charAt(0) == CTCP_TAG_DELIM;
		}
		
		public boolean hasNext()
		{
			return !str.equals("");
		}
		
		public String next()
		{
			return nextToken();
		}
		public String nextToken()
		{
			if( !hasNext() )
			{
				throw new NoSuchElementException();
			}
			
			int pos = str.indexOf( CTCP_TAG_DELIM, 1 );
			String result;
			if( isNextACtcp() )
			{
				if( pos < 0 )
				{
					// Error?  Well, whatever, return the rest of the
					// string.
					result = str.substring( 1 );
					str = "";
					return result;
				}
				else
				{
					// ^Aour string^A(rest of string)
					// Lose both ^A
					result = str.substring( 1, pos );
					str = str.substring( pos + 1 );
					return result;
				}
			}
			else 
			{
				// Not a CTCP
				if( pos < 0 )
				{
					result = str;
					str = "";
					return result;
				}
				else
				{
					result = str.substring( 0, pos );
					str = str.substring( pos );
					return result;
				}
			}
		}
	}
}